2.Flask:初步入门

Flask(初步入门 二)

安装

1
$ pip install flask
  • werkzeug:处理application
  • jinja2:渲染html

flask:组装大师

初始化application

1
2
from flask import Flask
app = Flask(__name__)

添加路由

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

运行服务器

1
app.run()

运行

请求与响应

flask的请求与响应都存放在request对象中

1
from flask import request

访问http://127.0.0.1:5000/?name=zhongxin

调试

Flask的__init__

1
2
3
4
5
6
7
8
9
10
11
12
13
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

1
2
3
4
5
6
from flask import render_template

@app.route('/hello')
def hello():
a = request.args
return render_template('index.html')

hello

1
2
3
4
5
6
7
8
9
10
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Flask</title>
</head>
<body>
你好
</body>
</html>

run方法

不要在生产环境使用调试模式,会遭到攻击

  • debug
  • host
  • port
1
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这样的组合

使用命令行方式运行

查看帮助

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
$ 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.

使用下面命令可以运行

1
2
3
$ export FLASK_APP=hello.py
$ export FLASK_ENV=development
$ flask run
 wechat
欢迎您扫一扫上面的微信公众号,订阅我的博客!
您的支持将鼓励我继续创作!