跳转到主要内容

Flask的简单REST工具包

项目描述

这个库是一个非常小的REST工具包,旨在在您想为Flask应用创建REST API时简化您的生活。

安装它

好吧,这很简单,它被打包并在PyPI上,所以

$ pip install flask-rest

使用它

处理器

创建具有特定方法(即添加、获取、删除和更新)的类,将其注册到一个URL,然后您就完成了。

这里有一个如何使用它的简单示例

from flask import Blueprint
from flask_rest import RESTResource, need_auth

# Subclass a RestResource and configure it

api = Blueprint("api", __name__, url_prefix="/api")

# You can define a authenfier if you want to.

class ProjectHandler(object):

    def add(self): #This maps on "post /"
        form = ProjectForm(csrf_enabled=False) # just for the example
        if form.validate():
            project = form.save()
            db.session.add(project)
            db.session.commit()
            return 201, project.id
        return 400, form.errors # returns a status code and the data

    def get(self, project_id): # maps on GET /<id>
        # do your stuff here
        return 200, project

    # you can use the "need_auth" decorator to do things for you
    @need_auth(authentifier_callable, "project") # injects the "project" argument if authorised
    def delete(self, project):
        # do your stuff
        return 200, "DELETED"

一旦定义了处理器,只需将它们注册到应用程序或蓝图即可

project_resource = RESTResource(
    name="project", # name of the var to inject to the methods
    route="/projects",  # will be availble at /api/projects/*
    app=api, # the app which should handle this
    actions=["add", "update", "delete", "get"], #authorised actions
    handler=ProjectHandler()) # the handler of the request

如果应该保护一切,可以使用authentifier参数

authentifier=check_project

其中check_project是一个可调用的对象,它返回项目或如果访问未被授权则返回False。

序列化/反序列化

当您返回Python对象时,它们可以被序列化,这在大多数情况下可能很有用。目前支持的唯一序列化格式是JSON。

要序列化普通 Python对象,它们应该有一个_to_serialize属性,包含要序列化的所有属性名称。以下是一个示例

class Member():

    _to_serialize = ("id", "name", "email")

    def __init__(self, **kwargs):
        for name, value in kwargs.items():
            setattr(self, name, value)

如果您想看看这个的实际用途,请访问https://github.com/spiral-project/ihatemoney/blob/master/budget/api.py

项目详情


下载文件

下载适用于您平台的文件。如果您不确定该选择哪一个,请了解更多关于 安装包 的信息。

源代码分发

Flask-REST-1.3.tar.gz (5.3 kB 查看哈希值)

上传时间 源代码

由以下机构支持