引言 本文将使用Flask的第3方库(flask-restful)创建基于restful风格的Flask应用。 学习内容:
- 【安装】flask-restful
- 【最小(简)构造】flask-restful的示例
- 【代码Diff】非restful与restful
- 【整合】蓝图+flask-restful+tornado
1.Flask-Restful基础
1.安装flask-restful
pipenv install flask-restful
2.【最简】flask-restful的结构
1.构造步骤
2.代码实现
#!/usr/bin/env pytho
# -*- coding: utf-8 -*-
"""
@author:cooling
@file:rest01.py
@time:2022/04/19
"""
from flask_restful import Resource, Api # 【step1】导入flask_restful相关包
from flask import Flask,request
from flask_cors import CORS
app = Flask(__name__)
CORS(app)
# 【step2】创建组件对象
api = Api(app)
# 【step3】定义类视图(继承:Resource)
class index(Resource):
def get(self):
return "index-rest"
class helloworld(Resource):
def get(self):
return "rest-get-hello"
def post(self):
body = request.get_json()
return {"body": body}, 201
# 【step4】组件:添加类视图及设置路由
api.add_resource(index, '/')
api.add_resource(helloworld, '/hello')
if __name__ == '__main__':
app.run(host="0.0.0.0", port=8806, debug=True)
3.运行结果
2.【代码Diff】非restful与restful
3.【整合】蓝图+flask-restful+tornado
1.构造步骤
2.代码实现
1.restful-code
#!/usr/bin/env pytho
# -*- coding: utf-8 -*-
"""
@author:cooling
@file:rest02.py
@time:2022/04/19
"""
from flask import request
from flask_restful import Resource,Api #【step1】导入flask_restful相关包
from flask import Blueprint as bp #【step2】导入flask_蓝图相关包
#【step3】定义蓝图对象
restApp=bp("restApp",__name__,url_prefix="/rest")
# 【step4】创建组件对象(传入--蓝图对象restApp)
api=Api(restApp)
class user(Resource):
def get(self):
return "rest-get-user"
# 【step5】定义类视图(继承:Resource)
class user(Resource):
def get(self):
return "rest-get-user"
class helloworld(Resource):
def get(self):
return "rest-get-hello"
def post(self):
body=request.get_json()
return {"body":body},201
#【step6】组件:添加类视图及设置路由
api.add_resource(user,'/user')
api.add_resource(helloworld,'/hello')
#
# if __name__ == '__main__':
# app.run(host="0.0.0.0",port=8806,debug=True)
2.flask-main
#!/usr/bin/env pytho
# -*- coding: utf-8 -*-
"""
@author:cooling
@file:restMain.py
@time:2022/04/19
"""
import resource.flaskConfig as config1
from flask import Flask
from flask_cors import CORS
from restful.rest02 import restApp # 导入:蓝图
app = Flask(__name__)
# CORS(app) # 解决跨域
app.register_blueprint(restApp) # 绑定蓝图对象
app.debug = True
def myApp():
return app
@app.get("/")
def index():
return "index-rest-flask"
#
# if __name__ == '__main__':
# pass
3.【tornado】runFlask
#!/usr/bin/env pytho
# -*- coding: utf-8 -*-
"""
@author:cooling
@file:runFlask.py
@time:2022/04/16
"""
from tornado.wsgi import WSGIContainer
from tornado.httpserver import HTTPServer
from tornado.ioloop import IOLoop
# from main import app
from restful.restMain import app # 导入restful的main入口
flaskPort=8806
def runFlask():
print("init-flask")
http_server= HTTPServer(WSGIContainer(app))
http_server.listen(flaskPort)
print("start-flask")
IOLoop.instance().start()
if __name__ == '__main__':
runFlask()