flask符合RESTful的项目蓝图的一种写法
目录结构
f1 ├── app01 │ ├── __init__.py # 必须有这个init文件,否则启动项目会报错!!! │ └── apis │ └── v1 │ ├── __init__.py │ ├── resources │ │ ├── auth.py │ │ └── book.py │ └── utils │ ├── log_scripts.py │ └── token_scripts.py └── start.py
代码
start.py
# -*- coding:utf-8 -*- from flask import Flask from app01.apis.v1 import api_v1 def register_blueprints(app): app.register_blueprint(api_v1,url_prefix="/api/v1") def create_app(): app = Flask("app01") # 注册蓝图 register_blueprints(app) return app if __name__ == '__main__': app = create_app() app.run(host="127.0.0.1",port=8989,debug=True)
v1/__init__.py
# -*- coding:utf-8 -*- from flask import Blueprint from flask_cors import CORS api_v1 = Blueprint("api_v1",__name__) CORS(api_v1) from app01.apis.v1.resources import auth,book
v1/resources/auth.py
# -*- coding:utf-8 -*- from flask.views import MethodView from app01.apis.v1 import api_v1 class AuthAPI(MethodView): def get(self): return "auth get method!!!" def post(self): return "auth post method!!!" api_v1.add_url_rule("/auth",view_func=AuthAPI.as_view("auth"),endpoint="auth",methods=["GET","POST"])
v1/resources/book.py
# -*- coding:utf-8 -*- from app01.apis.v1 import api_v1 @api_v1.route("/books",methods=["GET"],endpoint="books") def get_books(): return "get books ..." @api_v1.route("/create_book",methods=["POST"],endpoint="create_book") def create_book(): return "crate book ..."
剩下的其他逻辑的省略
xxx