Flask Framework API Specification & Flask Project

Insert picture description here

Flask

Restful API specification

First install the flask_restful module, the command is as follows

pip install flask_restful

Here we have decorated the Flask object with the API specification, defined the class view and defined the get and post methods in the class view. The specific syntax is reqparse.RequestParser()to instantiate the transmission object, 对象.add_argument()add parameters, and specify properties 对象.parse_args()for Get all parameters

from flask import Flask  # 用于创建 Flask 实例
from flask_restful import Api, Resource, reqparse, inputs
# 用于绑定 Flask 对象, 继承父类, 实例化对象, 判断 url

web = Flask(__name__)
# 使用 Api 来绑定 web
api = Api(web)


class IndexView(Resource):
    def get(self):
        p = reqparse.RequestParser()
        p.add_argument('name', type=str, help='名字错误', required=True)  
        # required 参数的作用是只有修饰的变量接收到值时, 才能执行返回语句
        p.add_argument('password', type=str, help='密码错误', required=True)
        args = p.parse_args()
        print(args)
        return {'info': '登录成功'}

    def post(self):
        parse = reqparse.RequestParser()
        parse.add_argument('username', type=str, help='用户名错误', required=True)
        parse.add_argument('password', type=str, help='密码错误', required=True)
        parse.add_argument('age', type=int, help='年龄错误', required=True)
        parse.add_argument('gender', type=str, help='性别错误', choices=['man', 'woman'])
        parse.add_argument('url', type=inputs.url, help='url 错误')  # inputs.url 方法自动判断是否为 url
        args = parse.parse_args()  # 获取 parse 对象所有参数的键值
        print(args)
        return {'info': '登录成功'}


# 给视图函数类增添 url, 和起别名
api.add_resource(IndexView, '/', endpoint='index')


if __name__ == '__main__':
    web.run(debug=True, port=2000)  # 运行 Flask 实例

get method

No parameters are passed, the name is first judged, and the name is queried, but the name is not received, all return the following string

Insert picture description here


Pass the parameter name, then the password is judged, and the password is queried but the password is not received, all return the following string

Insert picture description here


Pass the parameters name, password, and the query is received, all return the following string

Insert picture description here

post method (postman demo)

All parameters passed

Insert picture description here


Pass the first parameter username

Insert picture description here

Flask framework combined with Restful large modules

Python file (manage.py)

Console operation of this file, the specific operation to create a migration warehouse python manage.py db initwill generate a migration folder migrations, all the migrated files stored position, create a migration script python manage.py db migrate, update the database python manage.py db upgrade(in this case generate a table in the database)

from flask_script import Manager
from flask_migrate import Migrate, MigrateCommand
# 以上为二个插件
from exts import db  # 导入 db 数据库
from flask_restful_demo import web  # 导入 web 实例

import models  # 导入模型


manage = Manager(web)

Migrate(web, db)

manage.add_command('db', MigrateCommand)


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

Python file (config.py)

Here is the configuration file for the association of web objects and databases

HOSTNAME = '127.0.0.1'  # 地址
DATABASE = 'mysql_1'  # 数据库
PORT = 3306  # 端口
USERNAME = 'root'  # 用户名
PASSWORD = 'root'  # 密码
DB_URL = 'mysql+pymysql://{}:{}@{}:{}/{}'.format(USERNAME, PASSWORD, HOSTNAME, PORT, DATABASE)  # 创建 url

SQLALCHEMY_DATABASE_URI = DB_URL
SQLALCHEMY_TRACK_MODIFICATIONS = False

Python file (exts.py)

Here is the sqlalchemy plug-in database

from flask_sqlalchemy import SQLAlchemy

db = SQLAlchemy()

Python file (flask_restful_demo.py)

This file is executed with a browser, and data is obtained from the database

from flask import Flask  # 用于实例化 Flask 对象
from flask_restful import Api, Resource, fields, marshal_with
# 用于绑定 Flask 对象, 继承父类, 实例化对象, 判断 url

import config
from exts import db
from models import Article

web = Flask(__name__)  # 实例化 Flask 对象
web.config.from_object(config)  # 绑定配置文件
db.init_app(web)  # 绑定 app
api = Api(web)  # 使用 Api 来绑定 app


class IndexView(Resource):

    resource_fields = {
        'article_title': fields.String(attribute='title'),
        'content': fields.String(attribute='content'),
        # 'author': fields.String, 访问的是另一个表格的数据, 使用方法 fields.Nested
        'author': fields.Nested({
            'username': fields.String(attribute='username'),
            'email': fields.String(attribute='email'),
        })
    }

    @marshal_with(resource_fields)  # 装饰器装饰属性 resource_fields
    def get(self, article_id):
        article = Article.query.get(article_id)  # 查询 article 表的第一行数据
        return article

    def post(self):
        return {'info': '登录成功'}


api.add_resource(IndexView, '/article/<article_id>', endpoint='article')  # 参数传入 marshal_with 装饰器


if __name__ == '__main__':
    web.run(debug=True, port=7500)

The database adds a few rows of data, as follows

Insert picture description here


Insert picture description here

For example, when the url is /article/1, the first row of data is queried

Insert picture description here


For example, when the url is /article/2, the query is the second row of data

Insert picture description here


Python file (models.py)

Here is a table for the database

from exts import db
# 创建二个表格, table , article


class User(db.Model):
    __tablename__ = 'table'
    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    username = db.Column(db.String(50))
    email = db.Column(db.String(50))


class Article(db.Model):
    __tablename__ = 'article'
    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    title = db.Column(db.String(50))
    content = db.Column(db.String(50))
    uid = db.Column(db.Integer, db.ForeignKey('table.id'))
    author = db.relationship('User', backref='articles')