Python Flask Header & Payload Reflection
2022-11-23
使用 Python Flask 設計反射 Reuqest 來源的 Self-Hosted Server 方便進行 API 介接上的測試 😀
說明
安裝 Flask
mkdir flask
cd flask
python3 -m venv venv
venv\Scripts\activate
pip install Flask
啟動 flask
flask --app main run
flask --app main --debug run
Flask 結構
/main.py
/templates/base.html
/templates/index.html
/templates/form.html
/templates/404.html
main.py
from flask import Flask
app = Flask(__name__)
@app.route("/")
def welcome():
return "Hello World"
後端框架實現功能
Routing
@app.route("/", methods = ['GET', 'POST'])
def htmlRequest():
if request.method == 'GET':
...
if request.method =='POST':
...
Error Handle
@app.errorhandler(404)
def page_not_found(error):
return make_response(render_template('404.html', error=error), 404)
Json Response
from flask import jsonify
@app.route("/json", methods = ['GET', 'POST'])
def jsonRequest():
viewModel = {
"headers": { k:v for k, v in request.headers.items()},
}
return jsonify(viewModel)
Url Generate
<a class="btn btn-primary" href="{{ url_for('postFormRequest') }}">Post Form</a>
<form method="post" action="{{ url_for('htmlRequest', foo=10, bar=30) }}">
...
</form>
HTTP Data Handle
注意 request 的資料物件不是 Dict 在 jsonify
會發生例外錯誤,必須主動透過 dict generator
轉換為 dict 以正確處理。
viewModel = {
"headers": { k:v for k, v in request.headers.items()},
"querystring": { k:v for k, v in request.args.items()},
"payload": { k:v for k, v in request.form.items()},
"json": { k:v for k, v in request.json.items()}
}