配置
new project
python运行的file为:app.py
Flask()启动类
class Flask(Scaffold):
'''
The flask object implements a WSGI application and acts as the central
object. It is passed the name of the module or package of the
application. Once it is created it will act as a central registry for
the view functions, the URL rules, template configuration and much more.
'''
...
def __init__(
self,
import_name: str,
static_url_path: t.Optional[str] = None,
static_folder: t.Optional[t.Union[str, os.PathLike]] = "static",
static_host: t.Optional[str] = None,
host_matching: bool = False,
subdomain_matching: bool = False,
template_folder: t.Optional[str] = "templates",
instance_path: t.Optional[str] = None,
instance_relative_config: bool = False,
root_path: t.Optional[str] = None,
):# import_name为必填项
...
WSGI在python中是一种通用接口。
百科上的说法是:
Web服务器网关接口(Python Web Server Gateway Interface,缩写为WSGI)是为Python语言定义的Web服务器和Web应用程序或框架之间的一种简单而通用的接口。
访问
app.route(“web path”)路由(请求)
由路由注解的函数叫:视图函数
flask_app.run(debug=True, host=‘0.0.0.0’, port=5000)
host为映射地址,port为端口号,debug为自动适配代码
host默认为只有服务器自己可以访问,‘0.0.0.0’是允许通过ip地址访问,此时其他主机也可以访问了(这里是指同一局域网下,部署详情以后讲解)
debug默认为False:只加载第一次代码,适用于production环境;True为自动更新代码
环境:
production生产环境
development开发环境
testing测试环境
或:
# settings:
ENV = 'development'
DEBUG = True
# app.py
from flask import Flask
import settings
app = Flask(__name__)
app.config.from_object(settings)
print(app.config)# 是一个字典,可以更改它的值来更改python的环境配置,一般在settings.py文件中进行
@app.route('/')
def hello_world():
return 'Hello World!'
if __name__ == '__main__':
app.run(host="0.0.0.0", port=5000)
启动方式可以是绿色小三角,也可以是:terminal->python app.py
使用浏览器输入网址进行访问,响应为视图函数return值
请求
brower》服务器》app》路由》视图函数》response》brower
请求格式:
请求行: method
route
协议
请求头: key:value
请求体: post请求才有
响应格式:
响应行: 状态码
响应头: key:value 例:Content-Type: text/html;charset=utf-8
响应体:返回内容html或其他
了解更多flask,可以使用官方文档学习:https://dormousehole.readthedocs.io/en/latest/