Flask(初步入門 二)

安裝

$ pip install flask
  • werkzeug:處理application

  • jinja2:渲染html

flask:組裝大師

初始化application

from flask import Flask
app = Flask(__name__)

添加路由

@app.route('/')
def index():
    return 'Hello Flask!'

運行服務器

app.run()
運行

請求與響應

flask的請求與響應都存放在request對象中

from flask import request

訪問http://127.0.0.1:5000/?name=zhongxin

調試

Flask的`init`

def __init__(
    self,
    import_name, 
    static_url_path=None,
    static_folder="static",
    static_host=None,
    host_matching=False,
    subdomain_matching=False,
    template_folder="templates",
    instance_path=None,
    instance_relative_config=False,
    root_path=None,
):
  • import_name:

  • static_url_path:查找靜態文件的路徑

  • static_folder:靜態文件 文件夾

  • static_host:

  • host_matching:服務器匹配

  • subdomain_matching:子域名

  • template_folder:模版文件 文件夾

  • instance_path:app的路徑

  • instance_relative_config:相對設置

  • root_path:根目錄

渲染html

from flask import render_template

@app.route('/hello')
def hello():
    a = request.args
    return render_template('index.html')
hello
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Flask</title>
</head>
<body>
你好
</body>
</html>

run方法

不要在生產環境使用調試模式,會遭到攻擊

  • debug

  • host

  • port

def run(self, host=None, port=None, debug=None, load_dotenv=True, **options):

debug

  1. debug=True的時候修改代碼會自動重啓

  2. 在前端顯示具體的錯誤信息

host

  • 其他網絡要能訪問到使用0.0.0.0

  • 固定的網絡地址使用指定地址,例如192.168.1.23

`if name__ == "__main"`的作用

  1. 該腳本運行時運行

  2. flask生成環境中不會使用run

  3. uwsgi+nginx

  • 其他情況下,如果通過模塊導入,不是執行腳本,則main不會運行

  • 生成環境使用nginx+gunicorn/uwsgi這樣的組合

使用命令行方式運行

查看幫助

$ flask --help
Usage: flask [OPTIONS] COMMAND [ARGS]...

  A general utility script for Flask applications.

  Provides commands from Flask, extensions, and the application. Loads the
  application defined in the FLASK_APP environment variable, or from a
  wsgi.py file. Setting the FLASK_ENV environment variable to 'development'
  will enable debug mode.

    $ export FLASK_APP=hello.py
    $ export FLASK_ENV=development
    $ flask run

Options:
  --version  Show the flask version
  --help     Show this message and exit.

Commands:
  routes  Show the routes for the app.
  run     Run a development server.
  shell   Run a shell in the app context.

使用下面命令可以運行

$ export FLASK_APP=hello.py
$ export FLASK_ENV=development
$ flask run


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章