flask 是个微型的web框架,不像djagno那么庞大,django有很多内置app,缓存,信号,消息,权限,admin
flask 随着项目越来越大,使用第三方插件,越来越像django
模版渲染:jinja2
web服务器:Werkzeug WSGI
pip3 install flask
from flask import Flask
app = Flask(__name__)
@app.route('/')
def index():
return 'flask'
if __name__ == '__main__':
app.run()
Werkzeug是一个WSGI工具包,他可以作为一个Web框架的底层库。这里稍微说一下, werkzeug 不是一个web服务器,也不是一个web框架,而是一个工具包,官方的介绍说是一个 WSGI 工具包,它可以作为一个 Web 框架的底层库,因为它封装好了很多 Web 框架的东西,例如 Request,Response 等等
Werkzeug is a comprehensive WSGI web application library. It began as a simple collection of various utilities for WSGI applications and has become one of the most advanced WSGI utility libraries.
Werkzeug 是一个综合性 WSGI Web 应用程序库。它最初是 WSGI 应用程序的各种实用程序的简单集合,现已成为最先进的 WSGI 实用程序库之一。
Werkzeug doesn’t enforce any dependencies. It is up to the developer to choose a template engine, database adapter, and even how to handle requests
Werkzeug 不强制执行任何依赖关系。由开发人员选择模板引擎、数据库适配器,甚至如何处理请求
from werkzeug.wrappers import Request, Response
from werkzeug.serving import run_simple
@Request.application
def hello(request):
return Response('Hello World')
if __name__ == '__main__':
run_simple('localhost', 4000, hello)
Jinja is a fast, expressive, extensible templating engine. Special placeholders in the template allow writing code similar to Python syntax. Then the template is passed data to render the final document
Jinja 是一个快速、富有表现力、可扩展的模板引擎。模板中的特殊占位符允许编写类似于 Python 语法的代码。然后向模板传递数据以渲染最终文档
flask 2 版本加入的 ⇢ \dashrightarrow ⇢ 定制命令的工具
python manage.py init_db
Click is a Python package for creating beautiful command line interfaces in a composable way with as little code as necessary. It’s the “Command Line Interface Creation Kit”. It’s highly configurable but comes with sensible defaults out of the box
Click 是一个 Python 包,用于以可组合的方式使用尽可能少的代码创建漂亮的命令行界面。它是“命令行界面创建工具包”。它具有高度可配置性,但具有开箱即用的合理默认值
It aims to make the process of writing command line tools quick and fun while also preventing any frustration caused by the inability to implement an intended CLI API
它的目的是使编写命令行工具的过程变得快速而有趣,同时也防止因无法实现预期的 CLI API 而造成的任何挫败感
Click in three points:
arbitrary nesting of commands
automatic help page generation
supports lazy loading of subcommands at runtime
Click三点:
命令的任意嵌套
自动生成帮助页面
支持运行时延迟加载子命令
import click
@click.command()
@click.option('--count', default=1, help='打印次数')
@click.option('--name', prompt='你的名字', help='The person to greet.')
def hello(count, name):
for x in range(count):
print(f"Hello {name}!")
if __name__ == '__main__':
hello()
最新flask 要python 3.8 以上
可选依赖:这些依赖不会自动安装。如果您安装它们,Flask 将检测并使用它们
import sys
import time
import logging
from watchdog.observers import Observer
from watchdog.events import LoggingEventHandler
if __name__ == "__main__":
logging.basicConfig(level=logging.INFO,
format='%(asctime)s - %(message)s',
datefmt='%Y-%m-%d %H:%M:%S')
path = sys.argv[1] if len(sys.argv) > 1 else '.'
event_handler = LoggingEventHandler()
observer = Observer()
observer.schedule(event_handler, path, recursive=True)
observer.start()
try:
while True:
time.sleep(1)
except KeyboardInterrupt:
observer.stop()
observer.join()
pip3 install python-dotenv
import os
from dotenv import load_dotenv
from dotenv import dotenv_values
## 1 加载配置文件
# 必须在根路径下新建一个 .env 的文件,并写入配置才能返回True,会把.env下的配置文件设置进环境变量
res=load_dotenv() # take environment variables from .env
# You will probably want to add .env to your .gitignore, especially if it contains secrets like a password.
## 2 获取环境变量字典
config = dotenv_values(".env")
print(config)
print(config.get('DOMAIN'))
.env文件
DOMAIN=example.org
ADMIN_EMAIL=admin@${DOMAIN}
ROOT_URL=${DOMAIN}/app
DEBUG=Ture
Use a virtual environment to manage the dependencies for your project, both in development and in production.
在开发和生产中,使用虚拟环境来管理项目的依赖关系
What problem does a virtual environment solve? The more Python projects you have, the more likely it is that you need to work with different versions of Python libraries, or even Python itself. Newer versions of libraries for one project can break compatibility in another project.
虚拟环境解决什么问题?您拥有的 Python 项目越多,您就越有可能需要使用不同版本的 Python 库,甚至是 Python 本身。一个项目的较新版本的库可能会破坏另一项目的兼容性。
Virtual environments are independent groups of Python libraries, one for each project. Packages installed for one project will not affect other projects or the operating system’s packages.
虚拟环境是一组独立的 Python 库,每个项目对应一个。为一个项目安装的软件包不会影响其他项目或操作系统的软件包
Virtual environments are independent groups of Python libraries, one for each project. Packages installed for one project will not affect other projects or the operating system’s packages.
虚拟环境是一组独立的 Python 库,每个项目对应一个。为一个项目安装的软件包不会影响其他项目或操作系统的软件包
Python comes bundled with the venv module to create virtual environments.
Python 使用 venv 模块来创建虚拟环境
在cmd中
mkdir myproject
:创建一个文件夹myprojectcd myproject
:进入文件夹py -3 -m venv .venv
:创建虚拟环境.venv\Scripts\activate
pip install flask
from flask import Flask
app = Flask(__name__)
@app.route('/')
def index():
return 'hello world'
flask py文件名字 app run
flask --app 文件名.py run
python -m flask --app py文件名字 run
if __name__ == '__main__':
app.run()
python 5-app.py
,需在末尾添加flask app run
启动:flask --app 5-app.py run --debug
pip install fastapi
pip install uvicorn
from fastapi import FastAPI
import asyncio
app = FastAPI()
@app.get("/")
async def read_root():
# 如果有io
await asyncio.sleep(2)
return {"Hello": "World"}
uvicorn 文件名:app