> For the complete documentation index, see [llms.txt](https://luoran.gitbook.io/luo-ran-de-bi-ji-ben/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://luoran.gitbook.io/luo-ran-de-bi-ji-ben/python-bian-cheng/02-python-web/flask-pian/11.restful.md).

# 11.RESTFUL

## Restful API规范介绍

restful api是用于在前端与后台进行通信的一套规范。使用这个规范可以让前后端开发变得更加轻松。

### 协议

采用http或https协议

### 数据传输格式

数据之间传输的格式应该都使用json，而不使用xml

### url连接

url连接中，不能有动词，并且对于一些名词，如果出现复数，那么应该在后面加s

### HTTP请求的方法

1. GET:从服务器上获取资源
2. POST:在服务器上新创建一个资源
3. PUT:在服务器上更新资源。(客户端提供所有改变后的数据)
4. PATCH:在服务器上更新资源。(客户端只提供需要改变的属性)
5. DELETE:从服务器上删除资源

示例如下:

* GET/users/:获取所有用户
* POST/users/:新建一个用户
* GET/users/id/:根据id获取一个用户
* PUT/users/id/:更新某个id的用户的信息(需要提供用户的所有信息)
* PATCH/users/id/:更新某个id的用户信息(只需要提供更改的信息)
* DELETE/users/id/:删除一个用户

### 状态码

| 状态码 | 原生描述                  | 描述                                   |
| --- | --------------------- | ------------------------------------ |
| 200 | ok                    | 服务器成功响应客户端的请求                        |
| 400 | INVALID REQUEST       | 用户发出的请求有误，服务器没有进行新建或修改数据的操作          |
| 401 | Unauthorized          | 用户没有权限访问这个请求                         |
| 403 | Forbidden             | 因为某些原因禁止访问这个请求                       |
| 404 | NOT FOUND             | 用户发送的请求的url不存在                       |
| 406 | NOT Acceptable        | 用户请求不被服务器接收(比如服务器期望客户端发送某个字段，但是没有发送) |
| 500 | Internal server error | 服务器内部错误，比如出现了bug                     |

## 插件的基本使用

### 安装

```
pip install flask-restful
```

### 定义Restful的视图

使用flask-restful，那么定义视图函数的时候，就要继承自flask\_restful.Resource类，然后再根据当前请求的method来定义相应的方法。比如期望客户端是使用get方法发送过来的请求，那么就定义一个get方法。类似于MethodView。

```
from flask import Flask,render_template,url_for
from flask_restful import Api,Resource

app = Flask(__name__)
# 用Api来绑定app
api = Api(app)

# Json数据
class IndexView(Resource):
    def get(self,username=None):
        return {"username":"angle"}
# 可以指定多个url
api.add_resource(IndexView,'/index/<username>/','/regist/','/',endpoint='index')

with app.test_request_context():
    print(url_for('index',username='angle'))

if __name__ == '__main__':
    app.run(debug=True)
```

1. endpoint是用来给url\_for反转url的时候指定的。如果不写endpoint，那么将会使用视图的名字的小写作为endpoint。
2. add\_resource的第二个参数是访问这个视图函数的url，这个url可以跟之前的route一样，可以传递参数，并且还有一点不同的是，这个方法可以传递多个url来指定这个视图函数

![image-20200905080527168](https://cdn.jsdelivr.net/gh/TheFoxFairy/notebook-picgo@master/img/20200926141151.png)

## 参数验证

Flask-Restful插件提供了类似wtForms来验证提交的数据是否合法的包，叫做reqparse。

### 基本用法:

```
parser = reqparse.RequestParser()
parser.add_argument('username',type=str,help='请输入用户名',required=True)
args = parser.parse_args()
```

add\_argument可以指定这个字段的名字，这个字段的数据类型等。

### 参数

| 参数       | 含义                                   |
| -------- | ------------------------------------ |
| default  | 默认值，如果这个参数没有值，那么将使用这个参数指定的值          |
| required | 是否必须，如果这个参数没有值，那么将使用这个参数指定的值         |
| type     | 这个参数的数据类型，如果指定，那么将使用指定的数据类型来强制转换提交上来 |
| choices  | 选项。提交上来的值只有满足这个选项中的值才符合验证通过，否则验证不通过  |
| help     | 错误信息。如果验证失败后，将会使用这个参数指定的值作为错误信息      |
| trim     | 是否要取出前后的空格                           |

其中的type，可以使用python自带的一些数据类型，也可以使用flask\_restful.inputs下的一些特定的数据累心来强制转换。

常用的:

1. url:会判断这个参数的值是否是一个url，如果不是，就会抛出异常
2. regex:正则表达式
3. date:将这个字符串转换为datetime.date。如果转换不成功，则会抛出一个异常

```
from flask import Flask,render_template,url_for
from flask_restful import Api,Resource,reqparse,inputs

app = Flask(__name__)
# 用Api来绑定app
api = Api(app)

# Json数据
class LoginView(Resource):
    def post(self):
        # username
        # password
        parser = reqparse.RequestParser()
        parser.add_argument('birthday', type=inputs, help='生日字段验证')
        # # 验证日期
        # parser.add_argument('birthday',type=inputs.date,help='生日字段验证')
        # # 利用正则表达式验证手机号码
        # parser.add_argument('telphone',type=inputs.regex(r'1[3578]\d{9}'))
        # # 验证输入的url地址
        # parser.add_argument('home_page',type=inputs.url,help='个人中心链接验证错误')
        # parser.add_argument('username',type=str,help='用户名验证错误',default="angle")
        # parser.add_argument('password',type=str,help=u'密码验证错误',required=True,trim=True)
        # parser.add_argument('password',type=int,help=u'年龄验证错误')
        # parser.add_argument('gender',type=str,choices=['male','female','secret'],help="性别验证错误")
        args = parser.parse_args()
        print(args)
        return {"username":'angle'}
api.add_resource(LoginView,'/login/')

# with app.test_request_context():
#     print(url_for('index',username='angle'))

if __name__ == '__main__':
    app.run(debug=True)
```

## 标准化返回参数

对于一个视图函数，你可以指定好一些字段用于返回。以后可以使用ORM模型或者自定义的模型的时候，它会自动的获取模型中的相应的字段，生成json数据，然后再返回给客户端，这其中需要导入`flask_restful.marshal_with`装饰器。并且需要写一个字典，来指示需要返回的字段，以及该字段的数据类型。

```
from flask_restful import Api,Resource,fields,marshal_with

class ProfileView(Resource):
    resource_fileds = {
        'username':fields.String,
        'age':fields.Integer,
        'school':fields.String
    }

    @marshal_with(resource_fields)
    def get(self.user_id):
        user = User.query.get(user_id)
        return user
```

在get方法中，返回user的时候，flask\_restful会自动的读取user模型上的username以及age还有school属性。组装成一个json格式的字符串返回给客户端。

### 重命名属性

* 重命名属性字段

```
# 更改content属性的命名
resource_fields = {
        'title':fields.String,
        '内容':fields.String(attribute='content'),
    }
------------------------------------------------------
{
    "title": "angle",
    "内容": "angle"
}
```

### 默认值

* 为指定字段设置默认值

```
resource_fields = {
        'content':fields.String(default="angle"),
    }
```

### 复杂结构

使用fields.List可以使字段的值为列表，使用fields.Nested可以使字段的值为字典

```
class ProfileView(Resource):
    resource_field = {
        'username':fields,String,
        'age':fields.Integer,
        'school':fields.String,
        'tags':fields.List(fields.String),
        'more':fields.Nested{ {
            'signature': fields.String,
        } }
    }
```

## 细节

1. 在蓝图中，如果使用'flask-restful'，那么创建'Api'对象的时候，就不要再使用'app'了，而是使用蓝图

```
article_bp = Blueprint('article',__name__,url_prefix='/article')
api = Api(article_bp)
```

1. 如果在'flask-restful'的视图中想要返回'html'代码或者是模板，那么就应该使用\*\*'api.representation'\*\*这个装饰器来定义一个函数，在这个函数中，应该对'html'代码进行一个封装，再返回

```
@api.representation('text/html')def output_html(data,code,headers):    print(data)    # 在representation装饰的函数中，必须返回一个Response对象    resp = make_response(data)    return resp
class ListView(Resource):    def get(self):        return render_template('index.html')api.add_resource(ListView,'/list/',endpoint='list')
```
