4、flask服务 -- 参数传递及校验

flask参数传递及参数校验:

Script Demo:

config.py

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

# 一般大写
DEBUG = True

app_4.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

def create_app():
    app = Flask(__name__)
    app.config.from_object('config')
    # 蓝图注册
    register_blueprint(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 login

proj_dir/app/api/login.py

# -*- coding:utf-8 -*-
from flask import jsonify, request
from . import api


@api.route('/api/login')
def login():
    userid = request.args['userid']
    username = request.args['username']
    print('---- userid:', userid)
    print('---- username:', username)

    result = {
        'userid': userid,
        'username': username,
        'level': 'L5',
        'date': '2020-05-01'
    }

    return jsonify(result)


@api.route('/api/login2')
def login2():
    from app.forms.user import UserForm
    form = UserForm(request.args)

    if form.validate():
        # userid = form.userid.data.strip()
        username = form.username.data.strip()
        result = {
            # 'userid': userid,
            'username': username,
            'status': 200,
            'message': 'success'
        }
        return jsonify(result)
    else:
        return jsonify(form.errors)


@api.route('/api/register')
def register():
    result = {
        'level': 'L1',
        'date': '2020-05-01'
    }

    return jsonify(result)

表单验证

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/login2?userid=1110&username=LiSI




你可能感兴趣的:(4、flask服务 -- 参数传递及校验)