Flask-Restful基本设置

时间:2016-06-14 21:22:45

标签: python flask flask-restful

当我尝试转到/api时,我将数据库转换为api。

from flask import Flask , render_template   
from flask_restful import Resource, Api,marshal_with, fields
from flask_sqlalchemy import SQLAlchemy

app = Flask(__name__)
app.config.from_object('config')
api = Api(app)
db = SQLAlchemy(app)

class songbook(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    song_book = db.Column(db.String(80))
    title = db.Column(db.String(120))
    artist = db.Column(db.String(120))
    disc_number = db.Column(db.String(120))
    track_number = db.Column(db.String(120))

    def __init__(self, song_book, title, artist, disc_number, track_number):
        self.song_book = song_book  
        self.title = title
        self.artist = artist
        self.disc_number = disc_number
        self.track_number = track_number

resource_fields = {
    'song_book': fields.String,
    'title': fields.String,
    'artist': fields.String,
    'disc_number': fields.String,
    'track_number': fields.String,
}

class HelloWorld(Resource):
    @marshal_with(songbook)
    def get(self):
        return songbook.query.all()

api.add_resource(HelloWorld, '/api')

@app.route('/')
def hello_world():
    return render_template("index.html")

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

我收到错误代码

  

AttributeError:类型对象'songbook'没有属性'items'

我试图向here学习。任何其他文档或链接都会有所帮助。

1 个答案:

答案 0 :(得分:0)

此注释需要字典@marshal_with

你最后给了你的songbook课程,虽然你可能def __dict__(self)(不确定,没有尝试过)并让它返回一个模式,看起来你的意思改为做@marshal_with(resouce_fields)