使用flaskuntillet为SQLAlchemy表创建API

2024-04-19 07:10:11 发布

您现在位置:Python中文网/ 问答频道 /正文

我使用Python、FlaskFlask-SQLAlchemyFlask-Restless创建一个restfulapi。数据库包含一个表user。每个用户可以跟踪其他用户,每个用户也可以被其他用户跟踪(如在Twitter中)。因此,我还有一个表followers来链接用户(我部分遵循了Miguel's tutorial)。这是我的代码:

# -*- coding: utf-8 -*-
from flask import Flask

from flask.ext.sqlalchemy import SQLAlchemy
from flask.ext.restless import APIManager

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

followers = db.Table('followers',
    db.Column('follower_id', db.Integer, db.ForeignKey('user.id'), nullable=False),
    db.Column('followed_id', db.Integer, db.ForeignKey('user.id'), nullable=False)
)

# Model declaration
class User(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.Unicode, nullable=False)
    # some other properties...
    followed = db.relationship('User', 
        secondary=followers, 
        primaryjoin=(followers.c.follower_id == id), 
        secondaryjoin=(followers.c.followed_id == id), 
        backref=db.backref('followers', lazy='dynamic'), 
        lazy='dynamic')

# Create the database tables.
db.create_all()

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

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

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

在数据库中添加新用户很容易:

^{pr2}$

但是我应该做什么样的请求才能在followers表中添加内容呢?在


Tags: the用户namefromimportidappflask