- 分享一個前後端分離(Python3 + Flask +Vuew)的個人博客,一個使用Python Flask 框架編寫的個人博客。項目很輕。卻很實用。
- GitHub地址:哆啦瞎夢
- 技術棧:Flask、Vue、Docker
- 初始化,項目結構我就不再寫了,之前寫過了,沒有的可以看我之前的文章。或者直接私信我,我特地準備了一個乾淨的模板
返回格式定製化編寫
# flask_app>restful_api_manage中創建hellper.py
from flask import request, jsonify, make_response
def get_url_no_param():
full_path = str(request.full_path)
main_path = full_path.split('?')
return main_path[0]
def common_response(handle, code, content, error_code=0, message="",results=[]):
http_code = 200 if code in [204, 304, 401, 404, 409, 400] else code
if int(http_code) not in [204, 304]:
response_dict = {
"results": content,
"error_code": error_code,
"message": message,
"request": request.method + ' ' + get_url_no_param()
}
return make_response(jsonify(**response_dict),code)
return make_response("", code)
def error_response_default(handle, code, message,error_code):
return common_response(handle, code, None, error_code=error_code, message=message)
- 上面直接上代碼,直接複製過去就可以使用的
- 下面一部分 爲解釋代碼其實這段代碼主要做的就是定製一個返回統一樣式在json序列化返回出去
# 我定製化返回的接口樣式,你也可以自己修該自己喜歡的樣式
{
"error_code": 0,
"message": "",
"request": "POST /v1/login",
"results":{
}
}
# error_code 作爲自定義錯誤返回碼
# message 作爲返回錯誤信息
# request 作爲請求的url地址
# results 作爲返回的數據
- json 和 jsonify 的區別[返回區別,接受參數區別]
import json
from flask import Flask, jsonify
app = Flask(__name__)
@app.route('/hello')
def hello():
# return json.dumps({'name':"hello",'word':"word"})
return jsonify({'name':"hello",'word':"word"})
# 從測試結果上看 jsonify調用了json的dumps 並且jsonify的作用實際上就是將我們
#傳入的json形式數據序列化成爲json字符串,作爲響應的body,並且設置響應的
#Content-Type爲application/json,構造出響應返回至客戶端,json則設置的是text/html