七十八:flask.Restful之flask-Restful标准化返回参数以及准备数据
对于一个视图函数,可以指定好数据结构和字段用于返回,以后使用ORM模型或者自定义的模型的时候,它会自动获取模型中相应的字段,生成json数据,然后再返回给前端,这需要导入flask_restful.marshal_with装饰器,并且需要写一个字典,来指示要返回的字段名,以及该字段的数据类型
一、简单示例:
一般情况下返回数据
在restful规范中,要求一旦定义好了返回参数,即使这个参数没有值,也要返回,可以将此参数的值设为None返回
返回模型
二、数据准备:
项目代码
import os
SQLALCHEMY_DATABASE_URI = 'mysql+pymysql://root:123456@127.0.0.1:3306/test'
SQLALCHEMY_TRACK_MODIFICATIONS = False
SECRET_KEY = os.urandom(30)
from flask_sqlalchemy import SQLAlchemy
db = SQLAlchemy()
from exts import db
class User(db.Model):
__tablename__ = 'user'
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(50))
email = db.Column(db.String(50))
# 中间表
article_tag_table = db.Table('article_tag',
db.Column('article_id', db.Integer, db.ForeignKey('article.id'), primary_key=True),
db.Column('tag_id', db.Integer, db.ForeignKey('tag.id'), primary_key=True))
class Article(db.Model):
__tablename__ = 'article'
id = db.Column(db.Integer, primary_key=True)
title = db.Column(db.String(100))
content = db.Column(db.Text)
author_id = db.Column(db.Integer, db.ForeignKey('user.id'))
author = db.relationship('User', backref='article')
tags = db.relationship('Tag', secondary=article_tag_table, backref='tags') # 中间表外键
class Tag(db.Model):
__tablename__ = 'tag'
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(50))
from flask import Flask
import config
from exts import db
app = Flask(__name__)
app.config.from_object(config)
db.init_app(app)
if __name__ == '__main__':
app.run(debug=True)
from flask_script import Manager
from flask_migrate import Migrate, MigrateCommand
from app import app
from exts import db
import models # 导入所有模型
manager = Manager(app)
Migrate(app, db)
manager.add_command('db', MigrateCommand)
if __name__ == '__main__':
manager.run()
python manager.py db init 初始化
python manager.py db migrate 生成迁移脚本
python manager.py db upgrade 映射到数据库
添加测试数据
from flask import Flask
import config
from exts import db
from models import User, Article, Tag
app = Flask(__name__)
app.config.from_object(config)
db.init_app(app)
@app.route('/')
def index():
user = User(username='user1', email='111@qq.com')
article = Article(title='title1', content='content1')
article.author = user
tag1 = Tag(name='python')
tag2 = Tag(name='java')
article.tags.append(tag1)
article.tags.append(tag2)
db.session.add(article)
db.session.commit()
return '数据已增加'
if __name__ == '__main__':
app.run(debug=True)
调接口
讨论群:249728408