搭建Flask
最小flask应用
1 2 3 4 5 6 7 8 9
| from flask import Flask app = Flask(__name__)
@app.route("/") def hello(): return "<h1 style='color:blue'>Hello There!</h1>"
if __name__ == "__main__": app.run(host='0.0.0.0')
|
简单GET/POST请求
GET
1 2 3
| @app.route("/hello", methods=['GET']) def hello_get(): return 'hello'
|
POST
1 2 3 4 5
| @app.route("/hello", methods=['POST']) def hello_post(): img = request.files['img'] img.save('./save.jpg') return 'success'
|
return 类型
return类型支持字符串/json/元组/Response对象/重定向类型redirect。还可以附带状态码
返回字符串
json
1 2 3 4 5
| from flask import jsonify ... @app.route("/hello", methods=['GET']) def hello_get(): return jsonify({'code':200, 'msg': 'hello'})
|
元组,元组内容包括三个参数,response(响应体)
,status_code(状态码)
,headers(响应头)
1 2 3 4 5 6 7 8
| @app.route("/hello") def hello(): json_dict = { 'msg': 'hello', 'code': 200 } data = json.dumps(json_dict) return data, 200, {"ContentType":"application/json"}
|
Response对象
1 2 3 4 5 6 7 8
| from flask import make_response ...
@app.route("/hello") def hello(): response=make_response('say hello!')
return response
|
重定向类型redirect
1 2 3 4 5 6
| from flask import redirect ... @app.route("/hello") def hello():
return redirect('http://bouseng.com')
|
附带状态码
1 2 3
| @app.route("/hello") def hello(): return 'hello', 200
|
request
导入request
1
| from flask import request
|
POST表单数据:request.form
1 2 3 4 5
| name = request.form['name']
all_value = request.form.to_dict()
|
GET请求参数:request.args
1 2 3 4
| name = request.args.get('name') 获取所有GET请求参数 all_args = request.args
|
接收POST图片处理
转为base64
1 2 3 4 5 6
| import base64
@app.route('/pic2base64', methods=['POST']) def pic2base64(): pic = request.files['pic'] base64_data = base64.b64encode(pic.read())
|
转为cv2格式
1 2 3 4 5 6 7
| import cv2 import numpy as np
@app.route('/pic2cv', methods=['POST']) def pic2base64(): pic = request.files['pic'] cv_image = cv2.imdecode(np.fromstring(pic.read(), np.uint8), cv2.IMREAD_COLOR)
|
转为PIL格式
1 2 3 4 5 6
| from PIL import Image
@app.route('/pic2pil', methods=['POST']) def pic2base64(): pic = request.files['pic'] pil_image = Image.open(pic.stream).convert('RGB')
|
解决跨域
1 2 3 4 5 6 7 8 9 10
| app = Flask(__name__)
def after_request(response): response.headers['Access-Control-Allow-Origin'] = '*' response.headers['Access-Control-Allow-Methods'] = 'PUT,GET,POST,DELETE' response.headers['Access-Control-Allow-Headers'] = 'Content-Type,Authorization' response.headers['X-Content-Type-Options'] = 'nosniff' return response
app.after_request(after_request)
|
blueprint
合理使用blueprint,将程序各api模块化,使得程序不会臃肿不堪。
项目结构
———— main.py
———— applications
————————app1.py
main.py
1 2 3 4 5 6 7
| import sys sys.path.append('applications')
from app1 import app_name
app = Flask(__name__) app.register_blueprint(app_name, url_prefix='/app_name')
|
app1.py
1 2 3 4 5 6 7
| from flask import Blueprint
app_name = Blueprint('app_name', __name__)
@app_name.route('/') def hello(): return 'hello blueprint'
|