flask

安装:pip install flask

检查版本:

复制代码
import importlib.metadata
print(importlib.metadata.version("flask"))  

hello word:

复制代码
from flask import Flask
app = Flask(__name__)
@app.route('/')  
def hello_world():  
    return 'Helllo World'
if __name__ == '__main__':
    app.run()

简单的wsigi应用

复制代码
""" 简单WSGI服务器实现 """
from wsgiref.simple_server import make_server


# make_server 函数是 wsgiref 模块中提供的用于创建 WSGI 服务器的函数


def main():  # main 函数用于启动服务器
    # 创建一个 WSGI 服务器实例,并将其赋值给变量 server。
    # 指定服务器的主机名为 'localhost',端口号为 8001,处理请求的 WSGI 应用程序为 hello_world 函数。
    server = make_server('localhost', 8001, hello_world)
    print('Serving HTTP on port8001...')
    # 阻塞调用,使得服务器一直运行,直到接收到停止服务器的信号
    server.serve_forever()


def hello_world(environ, start_response):  # 作为 WSGI 应用程序。environ 是包含请求信息的字典,start_response 是用于发送响应的回调函数。
    status = "200 OK"
    response_headers = [('Content-Type', 'text/html')]  # 表示响应头部分的 Content-Type 属性为 'text/html'
    start_response(status, response_headers)
    path = environ['PATH_INFO'][1:] or 'hello world'
    return [b'<h1> %s </h1>' % path.encode()]   # 构建一个包含 HTML 标签的响应内容,并将其作为字节类型的列表返回


if __name__ == '__main__':
    main()



项目模式

debug模式

if name == 'main':

app.run(debug=True)

设置host和port

复制代码
app.run(host='0.0.0.0', port=5000)

app.config模式

app.config['配置项名称'] = 值

Flask 变量规则

<variable>: 使用尖括号包围的变量名称,表示该部分 URL 是一个变量。这个变量将作为参数传递给视图函数,默认情况下是字符串类型。

<int:variable>: 表示该变量应该是一个整数。Flask 会自动将匹配到的字符串转换为整数,并传递给视图函数。

<float:variable>: 表示该变量应该是一个浮点数。

<path:variable>: 将匹配任何路径,包括斜杠。这个规则常用于捕获完整的 URL 路径。

<string(length=2):variable>: 使用 string 转换器可以限制变量的类型为字符串,并且可以指定长度限制,例如 <string(length=2):variable> 表示该变量应该是一个长度为 2 的字符串。

<any(值1, 值2, ...):variable>: 使用 any 转换器可以限制变量只能是指定列表中的某个值,例如 <any('admin', 'user'):variable> 表示该变量只能是 'admin' 或 'user'。

相关推荐
Jay-r14 分钟前
手势粒子特效系统 Gesture Particle FX(附源码下载)
python·ai·编程·pygame·百度云·手势控制
额恩6619 分钟前
ResearchPilot 第三阶段总结报告
python·算法
fliter21 分钟前
Go设计取舍之一: goroutine 为什么保持匿名、无状态
后端
fliter28 分钟前
Go设计取舍之二: maps.Keys和Values为什么返回迭代器
后端
红叶舞32 分钟前
基于线段树的数据结构
数据结构·python·算法
热心市民lcj33 分钟前
Spring Boot 整合 Caffeine 本地缓存实战
spring boot·后端·缓存
创世宇图37 分钟前
Video2Txt:160 行代码实现本地视频转文字
python·faster-whisper·video2txt·large-v3-turbo
Revolution6137 分钟前
Nest.js 是什么:怎样用它写出第一个后端接口
后端·node.js·nestjs
aiopencode1 小时前
SwiftUI Introspect生产环境完全指南:为什么它是安全可靠的选择
后端·ios
shengjk11 小时前
x86架构发展史:从8086到x86-64,一文看懂40多年CPU指令集如何改变世界
后端