当前位置: 代码迷 >> 综合 >> 22.flask-restless
  详细解决方案

22.flask-restless

热度:71   发布时间:2023-09-12 05:57:22.0

flask-restless

Flask-Restless为使用SQLAlchemy(或Flask-SQLAlchemy)定义的数据库模型提供简单的ReSTful API生成。生成的API以JSON格式发送和接收消息。

安装

pip install flask_restless

配置

  • 导入模块
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask_restless.manager import APIManager
  • 数据库配置
HOSTNAME = "127.0.0.1"
PORT = "3306"
DATABASE = "test"
USERNAME = "root"
PASSWORD = "123456"
DB_URI = "mysql+pymysql://{}:{}@{}:{}/{}?charset=utf8".format(USERNAME,PASSWORD,HOSTNAME,PORT,DATABASE)# Create the Flask application and the Flask-SQLAlchemy object.
app = Flask(__name__)
app.config['DEBUG'] = True
app.config['SQLALCHEMY_DATABASE_URI'] = DB_URI
db = SQLAlchemy(app)
  • 创建模型类
class Person(db.Model):id = db.Column(db.Integer, primary_key=True)name = db.Column(db.String(200))birth_date = db.Column(db.Date)class Article(db.Model):id = db.Column(db.Integer, primary_key=True)title = db.Column(db.String(200))published_at = db.Column(db.DateTime)author_id = db.Column(db.Integer, db.ForeignKey('person.id'))author = db.relationship(Person, backref=db.backref('articles',lazy='dynamic'))
  • 生成表
# Create the database tables.
db.create_all()
  • 创建Flask-Restless API manager
# Create the Flask-Restless API manager.
manager = APIManager(app, flask_sqlalchemy_db=db)
  • 创建视图映射,通过/api/<tablename>进行访问
# Create API endpoints, which will be available at /api/<tablename> by
# default. Allowed HTTP methods can be specified as well.
manager.create_api(Person, methods=['GET', 'POST', 'DELETE'])
manager.create_api(Article, methods=['GET'])

使用

通过使用http://<host>:<port>/api/<tablename>进行访问。

  • 通过post请求进行创建数据
>>> import json,requests
>>> person = {'name': 'Bob', 'age': 18}
>>> r = requests.post('http://127.0.0.1:5000/api/person', data=json.dumps(person),headers={'content-type': 'application/json'})
>>> r.status_code, r.headers['content-type'], r.data
(201,'application/json, application/json',{'age': 18, 'articles': [], 'id': 1, 'name': 'Bob'})

22.flask-restless

  • 通过get请求获取数据
>>> id = r.json()['id']
>>> r = requests.get('http://127.0.0.1:5000/api/person/%s' % id,headers={'content-type': 'application/json'})
>>> r.status_code, r.headers['content-type']
(200, 'application/json, application/json')
>>> r.json()
{'age': 18, 'articles': [], 'id': 1, 'name': 'Bob'}

22.flask-restless

常见Restful API接口

  • GET /api/person

    获取所有数据

  • GET /api/person/(int: id)

    通过指定id数据数据

    /api/person/id
    
  • GET /api/person?q=<searchjson>

    通过关键字参数q匹配参数,进行查询

    >>> import requests
    >>> import json
    >>> 
    >>> url = 'http://127.0.0.1:5000/api/person'
    >>> headers = {'Content-Type': 'application/json'}
    >>> 
    >>>  filters = [dict(name='name', op='like', val='%o%')]
    >>>  params = dict(q=json.dumps(dict(filters=filters)))
    >>>  
    >>> response = requests.get(url, params=params, headers=headers)
    >>> assert response.status_code == 200
    >>> response.json()
    {'num_results': 1, 'objects': [{'age': 18, 'articles': [], 'id': 1, 'name': 'Bob'}], 'page': 1, 'total_pages': 1}
    
    • name:指定的fieldname字段,即类的属性名称。

    • value:指定的参数值,配置op使用。

    • op:指定匹配的方式

      • 运算符
        • ==, eq, equals, equals_to
        • !=, neq, does_not_equal, not_equal_to
        • >, gt, <, lt
        • >=, ge, gte, geq, <=, le, lte, leq
        • in, not_in
        • is_null, is_not_null
        • like
        • has
        • any
    • limit

      指定要返回的最大对象数。

    • offset

      指定返回实例列表的结果集中的偏移量。

    • order_by

      {"field": <fieldname>, "direction": <directionname>}
      

      其中,是与所请求模型的字段名称相对应的字符串,而是用于升序的“ asc”或用于降序的“ desc”。

      如果是形式为 __ 的字符串,则可以在相关模型上指定字段。

    • singer

      如果指定为True,只返回一个结果

    示例

    • 任意布尔运算
    GET /api/person?q={"filters":[{"or":[{"name":"age","op":"lt","val":10},{"name":"age","op":"gt","val":20}]}]}
    

    返回仅包括年龄属性小于10或大于20的Person实例:

    {"num_results": 3,"total_pages": 1,"page": 1,"objects":[{"id": 4, "name": "Abraham", "age": 9},{"id": 5, "name": "Isaac", "age": 25},{"id": 6, "name": "Job", "age": 37}]
    }
    
    • 两个值之间的属性
    GET /api/person?q={"filters":[{"name":"age","op":"ge","val":10},{"name":"age","op":"le","val":20}]}
    

    返回包括年龄属性在10到20之间的Person实例:

    {"num_results": 6,"total_pages": 3,"page": 2,"objects":[{"id": 2, "name": "John", "age": 13},{"id": 3, "name": "Mary", "age": 18}]
    }
    
    • 一个结果
    GET /api/person?q={"filters":[{"name":"id","op":"eq","val":1}],"single":true} HTTP/1.1
    

    返回仅包含ID等于1的唯一Person实例:

    {"id": 1, "name": "Jeffrey", "age": 24}
    
    • 比较两个属性
    GET /api/person?q={"filters":[{"name":"age","op":"ge","field":"height"}]} HTTP/1.1
    

    返回包含年龄属性大于或等于height属性的值的Person实例:

    {"num_results": 6,"total_pages": 3,"page": 2,"objects":[{"id": 1, "name": "John", "age": 80, "height": 65},{"id": 2, "name": "Mary", "age": 73, "height": 60}]
    }
    
    • 关系的比较属性
    GET /api/person?q={"filters":[{"name":"computers__manufacturer","op":"any","val":"Apple"}],"single":true} HTTP/1.1
    

    返回包括与Apple相关的Person实例:

    {"num_results": 6,"total_pages": 3,"page": 2,"objects":{"id": 1,"name": "John","computers": [{ "id": 1, "manufacturer": "Dell", "model": "Inspiron 9300"},{ "id": 2, "manufacturer": "Apple", "model": "MacBook"}]},{"id": 2,"name": "Mary","computers": [{ "id": 3, "manufacturer": "Apple", "model": "iMac"}]}]
    }
    
    • any
    GET /api/person?q={"filters":[{"name":"computers","op":"any","val":{"name":"id","op":"gt","val":1}}]} HTTP/1.1
    

    返回包含具有相关计算机实例且其id字段的值大于1的Person实例:

    {"num_results": 6,"total_pages": 3,"page": 2,"objects":[{"id": 1, "name": "John", "age": 80, "height": 65, "computers": [...]},{"id": 2, "name": "Mary", "age": 73, "height": 60, "computers": [...]}]
    }
    
  • DELETE /api/person/(int: id)

    通过指定id删除数据

    /api/person/id
    
  • DELETE /api/person

    仅当在调用create_api()方法时将allow_delete_many关键字参数设置为True时,此选项才可用。

    删除与q URL查询参数中提供的搜索查询匹配的Person的所有实例。

  • POST /api/person

    创建数据

更多参见文档