【问题标题】:Creating API for SQLAlchemy Table using Flask-Restless使用 Flask-Restless 为 SQLAlchemy 表创建 API
【发布时间】:2016-01-14 07:38:06
【问题描述】:

我使用 Python、Flask、Flask-SQLAlchemy 和 Flask-Restless 创建一个 RESTful API。该数据库包含一个表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)

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

from requests import post

user = {'name':'John Doe'}
post('http://localhost:5000/api/user', json=user)

但是我应该做什么样的请求才能在followers 表中添加一些东西呢?

【问题讨论】:

    标签: python flask-sqlalchemy flask-restless


    【解决方案1】:

    您需要使用 PATCH。

    来自docs:

    PATCH /api/person/1
    
    HTTP/1.1 Host: example.com
    
        { "computers":
          {
            "add": [ {"id": 1} ]
          }
        }
    

    在你的情况下,你会做这样的事情:

    from requests import patch
    
    follower = {'id':'37'}
    cmd = {'followed': { 'add': [ follower ] } }
    patch('http://localhost:5000/api/user/1', json=cmd)
    

    【讨论】:

    • 现在我明白了,谢谢。我的代码中还有另一个问题让我感到不安:在我的代码中,db.relationship(...) 没有分配给任何东西,因此没有在数据库中创建该字段。现在我将它分配给一个字段followed。我修正了你的答案,以考虑到这一变化。非常感谢。
    猜你喜欢
    • 2015-03-11
    • 2013-02-07
    • 1970-01-01
    • 1970-01-01
    • 2013-02-06
    • 1970-01-01
    • 2016-03-18
    • 2015-05-14
    • 1970-01-01
    相关资源
    最近更新 更多