对于我的webapp我想自动生成REST API。我阅读了flask_restless docs,尝试了几个教程并完成了所描述的所有内容:
我的路线位于模块 app.main.api.pv_tool.py
from . import api
from app.__init__ import db, app
from app.models import University
import flask_restless
manager = flask_restless.APIManager(app, session=db.scoped_session)
manager.create_api(University, methods=['GET'])
@api.route('/')
def index():
return 'asdf'
大学在 models.py
中定义from sqlalchemy import String, Integer
from sqlalchemy.ext.declarative import declarative_base
Base = declarative_base()
...
class University(Base):
__tablename__ = 'unis'
id = Column(Integer, primary_key=True, autoincrement=True)
name = Column(String(64), nullable=False, unique=True)
def __repr__(self):
return '<Uni %r>' % self.name
...
并且在 database.py 中建立了与现有数据库和已填充数据库的连接:
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker, scoped_session
from app.models import Base
class Database:
path = 'sqlite:///pv_tool.sqlite'
engine = None
session = None
scoped_session = None
def __init__(self, path=path):
self.engine = create_engine(path, convert_unicode=True)
Base.metadata.bind = self.engine
db_session = sessionmaker(bind=self.engine, autocommit=False)
db_session.bind = self.engine
self.session = db_session()
self.scoped_session = scoped_session(self.session)
Base.metadata.create_all()
现在在我的浏览器中或使用requests
库模块,我在http://localhost:5000上收到'asdf'回复。
但是,我无法通过以下所有方式访问我的大学数据:localhost:5000 / unis,localhost:5000 / api / unis等等。我总是收到404回复。
没有任何错误,这个问题很难实现。有没有人知道我如何调试这一般以及代码中的错误是什么?
在PyCharm Debugger中,manager对象似乎有一些API要创建: 但我不知道接下来我能找到什么。
另外,当我尝试在pv_tool.py中使用create_api_blueprints时,我在运行时遇到错误:
...
manager = flask_restless.APIManager(app, session=db.scoped_session)
api_bp = manager.create_api_blueprint('unis', University, methods=['GET'])
app.register_blueprint(api_bp)
...
Traceback (most recent call last): File "run.py", line 5, in <module>
from app import app File "/Users/rich/code/src/github.com/pv-tool-backend/app/__init__.py", line 4, in <module>
from app.main.api import api File "/Users/rich/code/src/github.com/pv-tool-backend/app/main/api/__init__.py", line 5, in <module>
from . import pv_tool File "/Users/rich/code/src/github.com/pv-tool-backend/app/main/api/pv_tool.py", line 11, in <module>
api_bp = manager.create_api_blueprint('unis', University, methods=['GET']) File "/Users/rich/code/src/github.com/pv-tool-backend/pv_tool_backend_venv/lib/python3.6/site-packages/flask_restless/manager.py", line 549, in create_api_blueprint
restlessinfo = app.extensions['restless'] AttributeError: type object 'University' has no attribute 'extensions'
这就是我运行应用程序的方式:
run.py
from app import app
app.run(debug=True, host='0.0.0.0', port=5000)
app模块的 init.py
from flask import Flask
from flask_cors import CORS
from app.main.api import api
from app.database import Database
db = Database()
app = Flask(__name__)
app.register_blueprint(api)
CORS(app)
从终端开始:
rich@local:~ $ python run.py
答案 0 :(得分:1)
我设法通过使用flask_sqlalchemy而不是纯sqlalchemy使其工作。