创建项目文件:
config.py
# @ Time : 2020/5/11
# @ Author : Ellen
HOSTNAME = '127.0.0.1'
DATABASE = 'demo0511'
PORT = 3306
USERNAME = 'root'
PASSWORD = 'root'
DB_URL = 'mysql+mysqlconnector://{}:{}@{}:{}/{}?charset?'.format(USERNAME, PASSWORD, HOSTNAME, PORT, DATABASE)
SQLALCHEMY_DATABASE_URI = DB_URL
SQLALCHEMY_TRACK_MODIFICATIONS = False
exts.py
# @ Time : 2020/5/11
# @ Author : Ellen
from flask_sqlalchemy import SQLAlchemy
db = SQLAlchemy()
flask_restful_demo.py
# @ Time : 2020/5/11
# @ Author : Ellen
from flask import Flask, render_template, url_for
from flask_restful import Api, Resource, reqparse, inputs, fields, marshal_with
import config
from exts import db
from models import Article
app = Flask(__name__)
app.config.from_object(config)
db.init_app(app)
# 用Api来绑定app
api = Api(app)
class ArticleView(Resource):
resource_fields = {
'title': fields.String,
'content': fields.String,
'author': fields.Nested({
"username": fields.String,
"email": fields.String
}),
# 'tags': fields.String
'tags': fields.List(fields.Nested({
"id": fields.Integer,
"name": fields.String
}))
}
# 及使这个参数没有值 也会返回
@marshal_with(resource_fields)
def get(self, article_id):
article = Article.query.get(article_id)
# return {'title': 'ellen'}
return article
api.add_resource(ArticleView,'/article/<article_id>', endpoint='article')
if __name__ == '__main__':
app.run(debug=True)
manage.py
# @ Time : 2020/5/11
# @ Author : Ellen
from flask_script import Manager
from flask_restful_demo import app
from flask_migrate import Migrate, MigrateCommand
from exts import db
# 导入模型
import models
manager = Manager(app)
Migrate(app, db)
manager.add_command('db', MigrateCommand)
if __name__ == '__main__':
manager.run()
models.py
# @ Time : 2020/5/11 5:50
# @ Author : Ellen
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')),
db.Column('tag_id', db.Integer, db.ForeignKey('tag.id'))
)
class Article(db.Model):
tablename = 'article'
id = db.Column(db.Integer, primary_key=True)
title = db.Column(db.String(50))
content = db.Column(db.String(50))
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))
创建的表:
页面显示: