使用flask-restless获得404错误

时间:2017-10-31 19:06:56

标签: python mysql flask flask-sqlalchemy flask-restless

我有一个现有的mysql数据库,我试图创建一个API来访问它,但我收到了404错误。我有两个版本的代码无法正常工作。

有人可以指出我正确的方向吗?

网址我正在使用:http://127.0.0.1:5000/api/email

V1:

from flask import Flask
from flask.ext.restless import APIManager
from flask_sqlalchemy import SQLAlchemy

app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql+pymysql://pathtodb/emails'
db = SQLAlchemy(app)

class Email(db.Model):
    __tablename__ = 'emails'
    id = db.Column(db.Integer, primary_key=True)
    status = db.Column(db.String(20))
    email = db.Column(db.String())

    def __init__(self, status, email):
        self.status = status
        self.email = email

api_manager = APIManager(app, flask_sqlalchemy_db=db)
api_manager.create_api(Email, methods=['GET', 'POST', 'DELETE', 'PUT'])

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

V2:

from flask import Flask
from flask.ext.restless import APIManager
from sqlalchemy import *
from sqlalchemy.ext.declarative import declarative_base

app = Flask(__name__)
Base = declarative_base()
engine = create_engine('mysql+pymysql://pathtodb/emails', echo=True)
metadata = MetaData(bind=engine)

class Email(Base):
    __tablename__ = Table('emails', metadata, autoload=True)
    id = Column(Integer, primary_key=True)
    status = Column(String(20))
    email = Column(String())


api_manager = APIManager(app, flask_sqlalchemy_db=engine)
api_manager.create_api(Email, methods=['GET', 'POST', 'DELETE', 'PUT'])

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

网址我正在使用:http://127.0.0.1:5000/api/email

1 个答案:

答案 0 :(得分:4)

使用flask-restless时,在调用方法api_manager.create_api()时会自动生成链接,格式为:

'http://127.0.0.1:5000/api/{tablename}'  # default domain and port

其中{tablename}是给予模型类的__tablename__,而不是方法中调用的类名。

文档提到了一个例子here