Structure Flask-Restful API to use SQLAlchemy

假装没事ソ 提交于 2019-11-30 15:46:33

I ran into this same problem and it had me stumped for longer than I care to admit. Looks like this is the same problem here so despite the age of the question I'll give an answer in the hope that I can save someone else some time. The problem here is actually an order-of-packages thing. The db in the main init has to be instantiated before the user class is imported, because this imports the db itself. I think that this is a trap that a lot of people fall into because one's immediate reflex is to put all the package loaders at the top of the file - sadly, in this case, it doesn't work and you end up chasing your tail for ages...

Iain Simmons

Move your resource/model import to below where you assign the db variable (since those modules/scripts rely on the db already being instantiated):

myapi/api/__init__.py

from flask import Flask
from flask.ext.restful import Api
from flask.ext.sqlalchemy import SQLAlchemy

app = Flask(__name__)
app.debug = True
app.config['SQLALCHEMY_DATABASE_URI'] = 'postgresql://localhost/myapi'

api = Api(app)
db = SQLAlchemy(app)

from api.resources.user import User

api.add_resource(User, '/user')
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!