0
我使用Python,Flask,Flask-SQLAlchemy和Flask-Restless创建一个RESTful API。该数据库包含一个表user
。每个用户可以关注其他用户,每个用户可以跟随其他用户(如Twitter)。所以我也有一个表followers
来链接用户(我部分跟着Miguel's tutorial)。这是我的代码:使用Flask-Restless为SQLAlchemy表创建API
# -*- 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)
要添加到数据库的新用户是很容易:
from requests import post
user = {'name':'John Doe'}
post('http://localhost:5000/api/user', json=user)
但我应该做的是什么样的要求,在followers
表中添加的东西吗?
'manager.create_api(用户,方法= [ 'GET', 'POST', 'PATCH'])' –
现在我明白了,谢谢。我的代码中存在另一个令我感到困扰的问题:在我的代码中,“db.relationship(...)”没有分配给任何东西,所以该字段没有在数据库中创建。现在我将它分配给一个字段“跟随”。我修复了您的答案,将此更改考虑在内。非常感谢你。 – clemtoy
真棒,很高兴它解决了。 –