zl程序教程

您现在的位置是:首页 >  后端

当前栏目

Flask 学习-40.Flask-RESTful 结合蓝图使用

restful学习 使用 结合 Flask 40 蓝图
2023-06-13 09:12:13 时间

前言

Flask-RESTful 结合蓝图使用设计接口

RESTful 接口

没使用蓝图之前 注册接口

from apps import create_app, db, jwt
from flask import url_for, request, jsonify
from flask_restful import reqparse, abort, Api, Resource
from apps.models import Users
app = create_app()
api = Api(app)

class Register(Resource):

    @staticmethod
    def password_validate(value, name):
        if len(value) < 6 or len(value) > 16:
            raise ValueError(name + ' length must be 6-16')
        return value

    def post(self):
        # 校验入参
        parser = reqparse.RequestParser()
        parser.add_argument('username', required=True, type=str,  nullable=False)
        parser.add_argument('password', required=True, type=self.password_validate,
                            nullable=False, help='invalid: {error_msg}')
        args = parser.parse_args()

        print(f'请求入参:{args}')

        return jsonify({
            "code": 0,
            "msg": "success"
        })

# 注册
api.add_resource(Register, '/api/v1/register')

使用 蓝图

蓝图的项目结构设计参考这篇https://www.cnblogs.com/yoyoketang/p/16624854.html

D:\demo\xuexi_flask
├── apps/
│   ├── __init__.py
│   ├── auth.py
│   ├── blog.py
│   ├── pay.py
├── templates/
│   ├── base.html
│   ├── auth/
│   │   ├── login.html
│   │   └── register.html
│   └── blog/
│       ├── create.html
└── static/
│       └── my.css
│       └── my.js
├── tests/
│   ├── test_auth.py
│   └── test_blog.py
│   └── test_pay.py
├── venv/
├── app.py

那么可以在auth.py 写注册相关的接口

from flask import (
    Blueprint, flash, g, redirect, render_template, request, session, url_for
)
from flask_restful import Api, reqparse, abort, Api, Resource

bp = Blueprint('auth', __name__, url_prefix='/auth')
api = Api(bp)

class Register(Resource):

    @staticmethod
    def password_validate(value, name):
        if len(value) < 6 or len(value) > 16:
            raise ValueError(name + ' length must be 6-16')
        return value

    def post(self):
        # 校验入参
        parser = reqparse.RequestParser()
        parser.add_argument('username', required=True, type=str,  nullable=False)
        parser.add_argument('password', required=True, type=self.password_validate,
                            nullable=False, help='invalid: {error_msg}')
        args = parser.parse_args()
        print(f'请求入参:{args}')
        return {
            "code": 0,
            "msg": "success"
        }

# 注册
api.add_resource(Register, '/api/register')

测试接口

POST http://127.0.0.1:5000/auth/api/register HTTP/1.1
User-Agent: Fiddler
Host: 127.0.0.1:5000
Content-Type: application/json
Content-Length: 56

{
    "username": "test",
    "password" : "123456"
}

接口返回

HTTP/1.1 200 OK
Server: Werkzeug/2.2.2 Python/3.8.5
Date: Fri, 02 Sep 2022 07:25:39 GMT
Content-Type: application/json
Content-Length: 40
Connection: close

{
    "code": 0,
    "msg": "success"
}

2022年第 12期《python接口web自动化+测试开发》课程,9月17号开学!

本期上课时间:2022年9月17号 - 2022年12月17号,周六周日上午9:00-11:00

报名费:报名费3000一人(周期3个月)

联系微信/QQ:283340479