5、flask服务 -- 请求方式与数据库连接

安装 flask-sqlalchemy:pip install flask-sqlalchemy -i https://pypi.tuna.tsinghua.edu.cn/simple/

Script Demo:

config.py

# -*- coding:utf-8 -*-

# 一般大写
DEBUG = True

# 数据库配置
SQLALCHEMY_DATABASE_URI = 'mysql+pymysql://localhost/baidu_db?user=root&password=******'
SQLALCHEMY_TRACK_MODIFICATIONS = False

app_5.py

# -*- coding:utf-8 -*-
from app import create_app

app = create_app()


if __name__ == '__main__':
    app.run(host='0.0.0.0', port=5001)

proj_dir/app/__init__.py

# -*- coding:utf-8 -*-
from flask import Flask
from app.models.user import db

def create_app():
    app = Flask(__name__)
    app.config.from_object('config')
    # 蓝图注册
    register_blueprint(app)
    
    # 数据库的初始化
    db.init_app(app)
    db.create_all(app=app)

    return app


# 蓝图注册
def register_blueprint(app):
    # 注册 api
    from app.api import api
    app.register_blueprint(api)

proj_dir/app/api/__init__.py

# -*- coding:utf-8 -*-
from flask import Blueprint

'''
函数名称在同一蓝图下不能相同,跨模块也不可以
'''

# 实例化蓝图对象
api = Blueprint('api', __name__)
# 导入
from app.api import request_method

请求方式
proj_dir/app/api/request_method.py

# -*- coding:utf-8 -*-
from app.forms.user import UserForm
from flask import jsonify, request
from . import api
from app.models.user import User, db


@api.route('/api/getUserInfo', methods=['GET', 'POST'])
def get_user_info():
    result = {
        'request_type': request.method,
        'message': 'success'
    }

    user = None
    if request.method == 'GET':
        form = UserForm(request.args)
        user = db.session.query(User).filter(User.username == form.username.data.strip()).first()
    elif request.method == 'POST':
        user = db.session.query(User).filter(User.username == request.json['username']).first()
    if user is not None:
        result['username'] = user.username
        result['userid'] = user.id

    return jsonify(result)

表单验证
proj_dir/app/models/user.py

# -*- coding:utf-8 -*-
from flask_sqlalchemy import SQLAlchemy
from sqlalchemy import Column, String, Integer

db = SQLAlchemy()


class User(db.Model):
    # 必须匹配主键
    id = Column(Integer, primary_key=True, autoincrement=True)
    username = Column(String(50), nullable=False, unique=True)

表单验证
proj_dir/app/forms/user.py

# -*- coding:utf-8 -*-
# 自动校验
from wtforms import Form, StringField, IntegerField
from wtforms.validators import DataRequired, Length

class UserForm(Form):
    # userid =IntegerField(validators=[DataRequired(), Length(min=5, max=10)])
    username = StringField(validators=[DataRequired(), Length(min=5, max=10)])


Test:

http://0.0.0.0:5001/api/getUserInfo?username=Jack Ma

http://0.0.0.0:5001/api/getUserInfo
{
    "username": "Jack Ma"
}




你可能感兴趣的:(5、flask服务 -- 请求方式与数据库连接)