Flask筆記(一)
pipenv創建虛擬環境
吼吼吼……(此處省略一些字)
配置文件
- config.py:
DEBUG = True
代碼(附註釋
- demo.py:
from flask import Flask, make_response app = Flask(__name__) app.config.from_object('config') @app.route('/hello/') # 通過這個裝飾器給hello函數定義一個路由,這樣就可以通過http請求執行這個函數 def hello(): # 視圖函數 # 基於類的視圖(即插視圖) return 'Hello, SixGod' # app.add_url_rule('/hello/', view_func=hello) @app.route('/hello2/') def hello2(): # content-type默認是text/html return '<html><body><p>Hi, Liushen</p></body></html>' @app.route('/hello3/') def hello3(): # status code: 200,404,301 # Response headers = { 'content-type': 'text/plain' # 如果返回的是json格式的字符串,應爲'application/json' # 'location': 'https://blog.csdn.net/hongwangdb' # 重定向 } response = make_response('<html></html>', 404) response.headers = headers return response @app.route('/hello4/') def hello4(): headers = { 'content-type': 'application/json', 'location': 'https://blog.csdn.net/hongwangdb' } return '<html></html>', 301, headers # 這樣的寫法就沒有用到Response對象,本質返回的是一個元組 if __name__ == '__main__': # 保證在生產環境下不會啓動flask自帶的外部服務器 # 生產環境 nginx前置服務器+uwsgi app.run(host='0.0.0.0', debug=app.config['DEBUG'], port=85)