Flask restful实际应用

Flask restful实际应用

7.实际使用

通过定义一个API ,集合数据库,返回给前端数据库中的数据.

.
├── app.py
├── config.py
├── exts.py
├── manage.py
├── migrations
│   ├── alembic.ini
│   ├── env.py
│   ├── README
│   ├── script.py.mako
│   └── versions
│       ├── 07d0ca1a599d_.py
├── static
└── templates

config.py

DEBUG=True
TEMPLATES_AUTO_RELOAD=True
DB_URI = 'mysql+pymysql://root:2008.Cn123@192.168.0.101:3306/flask_restful_demo' # 确保数据库存在
# 指定数据库连接
SQLALCHEMY_DATABASE_URI = DB_URI
SQLALCHEMY_TRACK_MODIFICATIONS = False

exts.py

from flask_sqlalchemy import SQLAlchemy

db = SQLAlchemy()

sql_models.py

from exts import db

class Users(db.Model):
 __tablename__ = 'users'

 id = db.Column(db.Integer,primary_key=True,nullable=False,autoincrement=True)
 name = db.Column(db.String(40),nullable=False)
 email = db.Column(db.String(40),nullable=False)
 password = db.Column(db.String(40),nullable=False)

 # 创建双向引用
 articles = db.relationship('Articles', back_populates='users')

article_tag = db.Table('article_tag',
                    db.Column('a_id',db.Integer,db.ForeignKey('articles.id'),primary_key=True),
                    db.Column('t_id',db.Integer,db.ForeignKey('tags.id'),primary_key=True)
                    )


class Articles(db.Model):
 __tablename__ = 'articles'

 id = db.Column(db.Integer, primary_key=True, nullable=False, autoincrement=True)
 name = db.Column(db.String(40), nullable=False)
 contents = db.Column(db.Text,nullable=False)

 # 与表users是多对一的关系
 u_id = db.Column(db.Integer,db.ForeignKey('users.id'))

 # 创建双向引用
 users= db.relationship('Users', back_populates='articles')
 tags = db.relationship('Tags',secondary=article_tag ,back_populates='articles')


class Tags(db.Model):
 __tablename__ = 'tags'

 id = db.Column(db.Integer, primary_key=True, nullable=False, autoincrement=True)
 name = db.Column(db.String(40), nullable=False)

 # 创建双向引用
 articles = db.relationship('Articles',secondary=article_tag, back_populates='tags')

初始化数据库,并且生成迁移脚本

mysql>  create database flask_restful_demo;

初始化,并生成迁移脚本.

from flask_script import Manager
from app import app
from flask_migrate import Migrate,MigrateCommand
from exts import db
# 导入ORM
import sql_models

# 绑定app
manage = Manager(app)

# 导入 flask-migrate
# 导入的Migrate类 可以绑定app ,db到 migrate 中
# 导入的MigrateCommand 类可以使用 Alembic 中所有的命令
Migrate(app,db)

manage.add_command('db', MigrateCommand)

if __name__ == '__main__':
 manage.run()
  > python manage.py db init
  > python manage.py db migrate
  > python manage.py db upgrade

app.py

from flask import Flask, views
import config
from exts import db
from flask_restful import Api, Resource, marshal_with, fields
from sql_models import Users, Articles, Tags

app = Flask(__name__)
app.config.from_object(config)

# db绑定app
db.init_app(app)
# Api绑定app
api = Api(app)


@app.route('/')
def index():
    return '这是主页'


@app.route('/register/')
def register():
    '''注册数据'''
    user = Users(name='Jack', email='Jack@kning.com', password='123')
    article = Articles(name='python', contents='First paper', u_id=1)
    tag1 = Tags(name="Python")
    tag2 = Tags(name='Computer')
    article.users = user
    article.tags.append(tag1)
    article.tags.append(tag2)
    db.session.add(article)
    db.session.commit()
    return '注册成功'


# 重载方法GET,并且格式化数据输出
class ArticleOutput(Resource):
    resource_fields = {   
        # 隐藏原始数据的 字段
        'article_name': fields.String(attribute='name'),
        'article_contents': fields.String(attribute='contents'),
        'article_author': fields.String(fields.Nested({
            'author_name': fields.String(attribute='name'),
            'author_email': fields.String(attribute='email')
        })),
        'article_tags': fields.String(fields.Nested({
            'tag1': fields.String(attribute='name1'),
            'tag2': fields.String(attribute='name2')
        }))
    }
 
    # marshal_with 重载数据为 OrderDict.
    @marshal_with(resource_fields)
    def get(self, article_id):
        article_id = int(article_id)
        article = db.session.query(Articles).filter(Articles.id==article_id).first()
        
        # 原始数据
        detail = {
            'name': article.name,
            'contents': article.contents,
            #'article_name':'Python',
            #'article_contents':'first page',
            'article_author': {
                'name': article.users.name,
                'email': article.users.email
            },
            'article_tags': {
                'name1': article.tags[0].name,
                'name2': article.tags[-1].name
            }

        }
        return detail

api.add_resource(ArticleOutput, '/api/article/<int:article_id>', endpoint='article')


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

访问网站

❯ curl http://127.0.0.1:5000/api/article/1
{
    "article_name": "python",
    "article_contents": "First paper",
    "article_author": "{'name': 'Jack', 'email': 'Jack@kning.com'}",
    "article_tags": "{'name1': 'Python', 'name2': 'Computer'}"
}

8.蓝图中使用

在蓝图中使用时,初始化的对象不是app,而是蓝图bp

article_bp = Blueprint('article',__name__,url_prefix='/article')
api = Api(article_bp)

9.模板渲染

flask_restful是一个API 的实现,它返回的都是json 数据,如果要使用html ,需要先声明.

@api.representation('text/html')
def out_html(data, code, headers):
 resp = make_response(data)
 return resp


class HelloView(Resource):
 def get(self):
     return render_template('hello.html')

api.add_resource(HelloView, '/hello/', endpoint='hello')

– END –


原文始发于微信公众号(Flask学习笔记):Flask restful实际应用

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。

文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/36428.html

(0)
小半的头像小半

相关推荐

发表回复

登录后才能评论
极客之音——专业性很强的中文编程技术网站,欢迎收藏到浏览器,订阅我们!