Flask
1、flask初步学习
1.1 创建虚拟环境
mkvirtualenv fl_3 -p python3
1.2 安装
pip install flask
2、案例
2.1 创建一个flask项目
from flask import Flask
app = Flask(__name__)
#__name__指向程序所在的包
#配置路由
@app.route('/')
def hello_world():
return 'Hello World!'
@app.route("/index")
def index():
return "这是我写的路由关系"
if __name__ == '__main__':
app.run(debug=True)
# app.config
- 首先我们导入了 Flask 类。 该类的实例将会成为我们的 WSGI 应用。
- 接着我们创建一个该类的实例。第一个参数是应用模块或者包的名称。如果你使用 一个单一模块(就像本例),那么应当使用 name ,因为名称会根据这个 模块是按应用方式使用还是作为一个模块导入而发生变化(可能是 ‘main’ , 也可能是实际导入的名称)。这个参数是必需的,这样 Flask 才能知道在哪里可以 找到模板和静态文件等东西。更多内容详见 Flask 文档。
- 然后我们使用 route() 装饰器来告诉 Flask 触发函数的 URL 。
- 函数名称被用于生成相关联的 URL 。函数最后返回需要在用户浏览器中显示的信息。
把它保存为 hello.py 或其他类似名称。请不要使用 flask.py 作为应用名称,这会与 Flask 本身发生冲突。
2.2 Flask创建对象的几个参数
"""
def __init__(
self,
import_name, flask程序所在包的名称,决定了访问静态的时候查找路径
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,
):
"""
2.3 run的参数
"""
:param host: the hostname to listen on. Set this to ``'0.0.0.0'`` to
have the server available externally as well. Defaults to
``'127.0.0.1'`` or the host in the ``SERVER_NAME`` config variable
if present.
:param port: the port of the webserver. Defaults to ``5000`` or the
port defined in the ``SERVER_NAME`` config variable if present.
:param debug: if given, enable or disable debug mode. See
:attr:`debug`.
:param load_dotenv: Load the nearest :file:`.env` and :file:`.flaskenv`
files to set environment variables. Will also change the working
directory to the directory containing the first file found.
:param options: the options to be forwarded to the underlying Werkzeug
server. See :func:`werkzeug.serving.run_simple` for more
information.
"