前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >apiflask基本用法

apiflask基本用法

原创
作者头像
Alan_1
发布2023-05-01 23:53:26
5000
发布2023-05-01 23:53:26
举报
文章被收录于专栏:Alan的blogAlan的blog

基本用法

环境

代码语言:text
复制
pip install apiflask

Create an app instance with APIFlask class

代码语言:python
复制
from apiflask import APIFlask

app = APIFlask(__name__)


@app.get('/')
def index():
    return {'message': 'hello'}

The default title and version of the API will be APIFlask and 0.1.0; you can pass the title and the version arguments to change these settings:

代码语言:python
复制
app = APIFlask(__name__, title='Wonderful API', version='1.0')

To run this application, you can save it as app.py, then run the flask run command:

代码语言:shell
复制
flask run
 * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)

If your script's name isn't app.py, you will need to declare which application should be started before execute flask run. See the note below for more details.

If you want to make the application restart whenever the code changes, you can enable reloader with --reload option:

代码语言:txt
复制
 flask run --reload
开启debug模式
代码语言:shell
复制
flask --debug run

Move to new API decorators

从APIFlask 0.12开始,四个独立的API装饰器 (i.e. @input, @output, @doc, and @auth_required) 被移动到APIFlaskAPIBlueprint classes. 现在用您的应用程序或蓝图实例访问它们:

代码语言:python
复制
from apiflask import APIFlask

app = APIFlask(__name__)

@app.get('/')
@app.input(Foo)
@app.output(Bar)
def hello():
    return {'message': 'Hello'}

代替:

代码语言:python
复制
from apiflask import APIFlask, input, output

app = APIFlask(__name__)

@app.get('/')
@input(Foo)
@output(Bar)
def hello():
    return {'message': 'Hello'}

使用@app.input验证和反序列化请求数据的输入

要验证和反序列化请求体或请求查询参数,我们需要首先创建一个数据模式类。可以将其视为描述有效传入数据的一种方式。如果您已经熟悉了marshmallow,那么您已经知道如何编写数据模式。

  • A schema class should inherit the apiflask.Schema class
  • fields are represented with field classes in apiflask.fields
  • 要用特定规则验证字段,您可以传递一个验证器或一个验证器列表 (import them from apiflask.validators) 到 field class的 validate 属性/参数: Here is a simple input schema for a Pet input resource:
代码语言:python
复制
from apiflask import Schema
from apiflask.fields import Integer, String
from apiflask.validators import Length, OneOf


class PetIn(Schema):
    name = String(required=True, validate=Length(0, 10))
    category = String(required=True, validate=OneOf(['dog', 'cat']))

使用此模式,我们声明输入请求正文应以以下格式出现:

代码语言:json
复制
{
    "name": "the name of the pet",
    "category": "the category of the pet: one of dog and cat"
}

现在让我们将它添加到用于创建新宠物的视图函数中:

代码语言:python
复制
from apiflask import APIFlask, Schema, input
from apiflask.fields import Integer, String
from apiflask.validators import Length, OneOf

app = APIFlask(__name__)


class PetIn(Schema):
    name = String(required=True, validate=Length(0, 10))
    category = String(required=True, validate=OneOf(['dog', 'cat']))


@app.post('/pets')
@app.input(PetIn)
def create_pet(data):
    print(data)
    return {'message': 'created'}, 201

您只需要将模式类传递给 @app.input 装饰器。收到请求后,APIFlask 将根据模式验证请求主体。

如果验证通过,数据将以 dict 的形式作为位置参数注入到视图函数中。否则,将返回包含验证结果详细信息的错误响应。

在上面的示例中,我使用名称数据来接受输入数据字典。您可以将参数名称更改为您喜欢的任何名称。因为这是一个字典,你可以做这样的事情来创建一个 ORM 模型实例:

代码语言:python
复制
@app.post('/pets')
@app.input(PetIn)
@app.output(PetOut)
def create_pet(pet_id, data):
    pet = Pet(**data)
    return pet

或者像这样更新一个 ORM 模型类实例:

代码语言:python
复制
@app.patch('/pets/<int:pet_id>')
@app.input(PetIn)
@app.output(PetOut)
def update_pet(pet_id, data):
    pet = Pet.query.get(pet_id)
    for attr, value in data.items():
        setattr(pet, attr, value)
    return pet

如果你想用不同的位置标记输入,你可以为 @app.input() 装饰器传递一个位置参数,值可以是:

  • Request JSON body: 'json' (default)
  • Upload files: 'files'
  • Form data: 'form'
  • Form data and files: 'form_and_files'
  • Cookies: 'cookies'
  • HTTP headers: 'headers'
  • Query string: 'query' (same as 'querystring')
  • Path variable (URL variable): 'path' (same as 'view_args', added in APIFlask 1.0.2)

Use@app.output to format response data

类似地,我们可以用@app为输出数据定义一个模式。输出装饰。下面是一个例子:

代码语言:python
复制
from apiflask.fields import String, Integer


class PetOut(Schema):
    id = Integer()
    name = String()
    category = String()

现在将它添加到用于获取宠物资源的视图函数中

代码语言:python
复制
from apiflask import APIFlask, output
from apiflask.fields import String, Integer

app = APIFlask(__name__)


class PetOut(Schema):
    id = Integer()
    name = String(dump_default='default name') #使用 dump_default 参数为输出字段设置默认值:
    category = String()


@app.get('/pets/<int:pet_id>')
@app.output(PetOut)
def get_pet(pet_id):
    return {
        'name': 'Coco',
        'category': 'dog'
    }

输出响应的默认状态代码为 200,您可以使用status_code参数设置不同的状态代码:

代码语言:python
复制
@app.post('/pets')
@app.input(PetIn)
@app.output(PetOut, status_code=201)
def create_pet(data):
    data['id'] = 2
    return data

如果要返回 204 响应,可以使用 apiflask.schemas 中的EmptySchema

代码语言:python
复制
from apiflask.schemas import EmptySchema


@app.delete('/pets/<int:pet_id>')
@app.output(EmptySchema, status_code=204)
def delete_pet(pet_id):
    return ''
    
#从 0.4.0 版本开始,您可以使用空字典来表示空模式:
@app.delete('/pets/<int:pet_id>')
@app.output({}, status_code=204)
def delete_pet(pet_id):
    return ''

当你想传递一个头字典时,你可以将该字典作为返回元组的第二个元素传递:

代码语言:python
复制
@app.post('/pets')
@app.input(PetIn)
@app.output(PetOut, status_code=201)
def create_pet(data):
    # ...
    # equals to:
    # return pet, 201, {'FOO': 'bar'}
    return pet, {'FOO': 'bar'}

使用@app.auth_required来保护你的视图

基于Flask-HTTPAuth,APIFlask提供了三种类型的身份验证:

HTTP Basic

要实现HTTP基本身份验证,你需要:

  • 使用HTTPBasicAuth创建一个auth对象from apiflask import APIFlask, HTTPBasicAuth app = APIFlask(__name__) auth = HTTPBasicAuth() # create the auth object @auth.verify_password def verify_password(username, password): # get the user from the database, check the password # then return the user if the password matches # ... @app.route('/') @app.auth_required(auth) def hello(): return f'Hello, {auth.current_user}!'
  • 使用@auth.verify_password注册一个回调函数,该函数应接受usernamepassword,并返回相应的用户对象或None
  • 使用@app.auth_required(auth)保护视图函数。
  • 在视图函数中使用auth.current_user访问当前用户对象。
HTTP Bearer

要实现HTTP Bearer身份验证,你需要:

  • 使用HTTPTokenAuth创建一个auth对象from apiflask import APIFlask, HTTPTokenAuth app = APIFlask(__name__) auth = HTTPTokenAuth() # create the auth object # or HTTPTokenAuth(scheme='Bearer') @auth.verify_token # register a callback to verify the token def verify_token(token): # verify the token and get the user id # then query and return the corresponding user from the database # ... @app.get('/') @app.auth_required(auth) # protect the view def hello(): # access the current user with auth.current_user return f'Hello, {auth.current_user}'!
  • 使用@auth.verify_token注册一个回调函数,该函数应接受令牌,并返回相应的用户对象或None
  • 使用@app.auth_required(auth)保护视图函数。
  • 在视图函数中使用auth.current_user访问当前用户对象。

API密钥(在header)

类似于Bearer类型,但在创建auth对象时将方案设置为ApiKey

代码语言:python
复制
from apiflask import HTTPTokenAuth

HTTPTokenAuth(scheme='ApiKey')

或使用自定义头:

代码语言:python
复制
from apiflask import HTTPTokenAuth

HTTPTokenAuth(scheme='ApiKey', header='X-API-Key')

# ...

您可以使用HTTPBasicAuthHTTPTokenAuth中的description参数来设置OpenAPI安全描述。

请参阅Flask-HTTPAuth的文档以了解详细信息。但是,请记住从APIFlask导入HTTPBasicAuthHTTPTokenAuth,并对视图函数使用@app.auth_required而不是@auth.login_required

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 基本用法
    • 环境
      • Create an app instance with APIFlask class
        • 开启debug模式
      • Move to new API decorators
        • 使用@app.input验证和反序列化请求数据的输入
          • Use@app.output to format response data
            • 使用@app.auth_required来保护你的视图
              • HTTP Basic
              • HTTP Bearer
          相关产品与服务
          多因子身份认证
          多因子身份认证(Multi-factor Authentication Service,MFAS)的目的是建立一个多层次的防御体系,通过结合两种或三种认证因子(基于记忆的/基于持有物的/基于生物特征的认证因子)验证访问者的身份,使系统或资源更加安全。攻击者即使破解单一因子(如口令、人脸),应用的安全依然可以得到保障。
          领券
          问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档