flask-restless 为数据库模型创建 RESTful API

flask-restless简介

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

flask-restless实例

import flask
import flask.ext.sqlalchemy
import flask.ext.restless

# Create the Flask application and the Flask-SQLAlchemy object.
app = flask.Flask(__name__)
app.config['DEBUG'] = True
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:////tmp/test.db'
db = flask.ext.sqlalchemy.SQLAlchemy(app)

# Create your Flask-SQLALchemy models as usual but with the following two
# (reasonable) restrictions:
#   1. They must have a primary key column of type sqlalchemy.Integer or
#      type sqlalchemy.Unicode.
#   2. They must have an __init__ method which accepts keyword arguments for
#      all columns (the constructor in flask.ext.sqlalchemy.SQLAlchemy.Model
#      supplies such a method, so you don't need to declare a new one).
class Person(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.Unicode, unique=True)
    birth_date = db.Column(db.Date)


class Computer(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.Unicode, unique=True)
    vendor = db.Column(db.Unicode)
    purchase_time = db.Column(db.DateTime)
    owner_id = db.Column(db.Integer, db.ForeignKey('person.id'))
    owner = db.relationship('Person', backref=db.backref('computers',
                                                         lazy='dynamic'))


# Create the database tables.
db.create_all()

# Create the Flask-Restless API manager.
manager = flask.ext.restless.APIManager(app, flask_sqlalchemy_db=db)

# Create API endpoints, which will be available at /api/ by
# default. Allowed HTTP methods can be specified as well.
manager.create_api(Person, methods=['GET', 'POST', 'DELETE'])
manager.create_api(Computer, methods=['GET'])

# start the flask loop
app.run()

flask-restless Github统计数据

AGPL-3.0

Github 1k stars

flask-restless安装命令

pip install Flask-Restless

flask-restless的Python版本要求

Flask-Restless requires Python version 2.6, 2.7, or 3.3

免责声明:内容编辑自网络,仅供参考,不保证正确性,不作任何决策依据!!以上数据皆截止于博文的写稿日期。


行业导航 / Python指南 :
























Copyright © 2022-2024 笨鸟工具 x1y1z1.com All Rights Reserved.