当前位置: 首页 > news >正文

python与flask框架

一、理论
Flask是一个轻量级的web框架,灵活易用。提供构建web应用所需的核心工具。

Flask依赖python的两个库
    Werkzeug:flask的底层库,提供了WSGI接口、HTTP请求和响应处理、路由等核心功能。
    Jinja2:模板引擎,用于动态生成HTML页面。
二、实践
 

1、第一个flask应用
[root@localhost ~]# pip config set global.index-url http://mirrors.aliyun.com/pypi/simple
Writing to /root/.config/pip/pip.conf
[root@localhost ~]# pip3 config set global.index-url http://mirrors.aliyun.com/pypi/simple
Writing to /root/.config/pip/pip.conf
[root@localhost ~]# pip3 config set install.trusted-host mirrors.aliyun.com
Writing to /root/.config/pip/pip.conf
[root@localhost ~]# pip3 install --upgrade pip[root@localhost ~]# pip install flask[root@localhost ~]# vim a.py
from flask import Flask# 创建Flask应用实例
app=Flask(__name__)# 定义路由和视图函数
@app.route('/')  # 用户的访问url为根时,flask会调用hello_world()函数。
def hello_world():return 'Hello,World!'# 启动应用
if __name__ == '__main__':  # 该行用于确认当前脚本是否是通过命令行直接运行的,而不是作为其他模块或程序的一部分被导入的。app.run(host='0.0.0.0',port='5000',debug=True)    # 启动flask开发服务器,debug=true表示启用调试模式,可在开发过程中自动重载应用,并在发生错误时显示详细信息。 host指定监听的地址,这里监听本机所有可用的地址,port指定监听的端口。[root@localhost ~]# python3 a.py  # 运行该服务。* Serving Flask app 'a'* Debug mode: on
WARNING: This is a development server. Do not use it in a production deployment. Use a production WSGI server instead.* Running on all addresses (0.0.0.0)* Running on http://127.0.0.1:5000* Running on http://192.168.10.101:5000
Press CTRL+C to quit* Restarting with stat* Debugger is active!* Debugger PIN: 112-870-242[root@localhost ~]# firewall-cmd --add-port=5000/tcp # 开放端口
success [root@localhost ~]# curl 192.168.10.101:5000
Hello,World![root@localhost ~]# # 这里会这样显示是因为return的末尾未加\n(换行),所以导致这样显示。(命令行中输入完命令在末尾默认会加上换行,所以不会出现这种情况。)修改代码from flask import Flask# 创建Flask应用实例
app=Flask(__name__)# 定义路由和视图函数
@app.route('/')
def hello_world():return 'Hello,World!\n'  # 加上换行符即可。# 启动应用
if __name__ == '__main__':app.run(host='0.0.0.0',port='5000',debug=True)[root@localhost ~]# curl 192.168.10.101:5000
Hello,World!
[root@localhost ~]# c^C[root@localhost ~]# vim a.py 
[root@localhost ~]# python3 a.py* Serving Flask app 'a'* Debug mode: on
WARNING: This is a development server. Do not use it in a production deployment. Use a production WSGI server instead.* Running on all addresses (0.0.0.0)* Running on http://127.0.0.1:5000* Running on http://192.168.10.101:5000
Press CTRL+C to quit* Restarting with stat* Debugger is active!* Debugger PIN: 112-870-242
192.168.10.101 - - [21/Apr/2025 09:08:50] "GET / HTTP/1.1" 200 -
192.168.10.101 - - [21/Apr/2025 09:08:53] "GET / HTTP/1.1" 200 -2、flask路由与视图函数
flask通过装饰器@app.route()来定义路由,而视图函数则负责处理用户的请求并返回响应。[root@localhost ~]# vim a.py
from flask import Flask# 创建Flask应用实例
app=Flask(__name__)# 定义路由和视图函数
@app.route('/')
def hello_world():return 'Hello,World!\n'@app.route('/greet/<name>')  # 这里定义了路径ip/greet/<name> 如果输入1,参数1会传递到下面的return中,会显示hello,1.
def greet(name):return f'Hello,{name}!\n'  # f是用于字符串格式化,将输出结果显示为字符串。# 启动应用
if __name__ == '__main__':app.run(host='0.0.0.0',port='5000',debug=True)[root@localhost ~]# python3 a.py* Serving Flask app 'a'* Debug mode: on
WARNING: This is a development server. Do not use it in a production deployment. Use a production WSGI server instead.* Running on all addresses (0.0.0.0)* Running on http://127.0.0.1:5000* Running on http://192.168.10.101:5000
Press CTRL+C to quit* Restarting with stat* Debugger is active!* Debugger PIN: 112-870-242
192.168.10.101 - - [21/Apr/2025 09:14:38] "GET /greet/1 HTTP/1.1" 200 -[root@localhost ~]# curl 192.168.10.101:5000/greet/1
Hello,1!注意,这里只能这样写,写为192.168.10.101/greet/1:5000会失败,它会去找80端口。因为url的格式就是这样,平时访问网页,就是ip:port只不过port被隐藏了(因为是80,443常用端口,不需要写)。[root@localhost ~]# curl 192.168.10.101/greet/1:5000
curl: (7) Failed to connect to 192.168.10.101 port 80 after 0 ms: Couldn't connect to serverURL的组成部分:协议(protocol):指定了资源应该使用的访问方式,常见的协议有http、https、ftp等主机名(hostname):资源所在的服务器地址,可以是ip地址或域名。端口号(port):服务器上用于访问资源的技术接口。路径(path):资源在服务器上的具体位置。参数(parameters):提供给服务器的额外信息,通常以键值对的形式出现。查询(query):通过?与url的其他部分分隔,用于提供额外的请求信息。片段(fragment):通常以#开始,指向资源内部的一个锚点,如网页中的一个特定部分。url完整格式 http://www.hostname.com:80/index.html?lang=zh#contenthttp是协议,www.hostname.com是主机名,80是端口,/index.html是路径,lang=zh是查询参数,content是片段标识符。3、指定允许的请求方法。
[root@localhost ~]# vim a.py 
from flask import Flask# 创建Flask应用实例
app=Flask(__name__)# 定义路由和视图函数
@app.route('/')
def hello_world():return 'Hello,World!\n'@app.route('/greet/<name>')
def greet(name):return f'Hello,{name}!\n'@app.route('/submit',methods=['POST'])	
def submit():return 'Form submitted successfully!\n'  # Form是html里定义请求方式时用到的关键字。# 启动应用
if __name__ == '__main__':app.run(host='0.0.0.0',port='5000',debug=True) [root@localhost ~]# python3 a.py * Serving Flask app 'a'* Debug mode: on
WARNING: This is a development server. Do not use it in a production deployment. Use a production WSGI server instead.* Running on all addresses (0.0.0.0)* Running on http://127.0.0.1:5000* Running on http://192.168.10.101:5000
Press CTRL+C to quit* Restarting with stat* Debugger is active!* Debugger PIN: 112-870-242[root@localhost ~]# curl 192.168.10.101:5000/submit
<!doctype html>
<html lang=en>
<title>405 Method Not Allowed</title>
<h1>Method Not Allowed</h1>
<p>The method is not allowed for the requested URL.</p>
[root@localhost ~]# curl -XPOST 192.168.10.101:5000/submit
Form submitted successfully!4、使用jinja2模板渲染html[root@localhost ~]# mkdir templates
[root@localhost ~]# ls
anaconda-ks.cfg  a.py  templates  # 模板文件与主程序(a.py必须在同一级目录下,否则会找不到,名称也必须叫templates,否则也会找不到。)
[root@localhost ~]# cd templates/
[root@localhost templates]# vim greet.html
<html lang="en">
<head><meta charset="UTF-8"><title>Flask Example</title>
</head>
<body><h1>Hello,{{ name }}!<h1>  #  {{ }}  这种格式是jinja2模板格式。name同样是参数传递,ip/greet/name中的name会传递到这里。
</body>
</html>[root@localhost ~]# vim a.py 
from flask import Flask
from flask import render_template# 创建Flask应用实例
app=Flask(__name__)# 定义路由和视图函数
@app.route('/')
def hello_world():return 'Hello,World!\n'@app.route('/submit',methods=['POST'])
def submit():return 'Form submitted successfully!\n'@app.route('/greet/<name>')
def greet(name):return render_template('greet.html',name=name)# 启动应用
if __name__ == '__main__':[root@localhost ~]# python3 a.py* Serving Flask app 'a'* Debug mode: on
WARNING: This is a development server. Do not use it in a production deployment. Use a production WSGI server instead.* Running on all addresses (0.0.0.0)* Running on http://127.0.0.1:5000* Running on http://192.168.10.101:5000
Press CTRL+C to quit* Restarting with stat* Debugger is active!* Debugger PIN: 112-870-242[root@localhost ~]# curl 192.168.10.101:5000/greet/aaa
<html lang="en">
<head>	<meta charset="UTF-8"><title>Flask Example</title>
</head>
<body><h1>Hello,aaa!<h1>
</body>4、模板继承与块[root@localhost ~]# ls
anaconda-ks.cfg  a.py  templates
[root@localhost ~]# cat a.py
from flask import Flask
from flask import render_template# 创建Flask应用实例
app=Flask(__name__)# 定义路由和视图函数
@app.route('/')
def hello_world():return 'Hello,World!\n'@app.route('/submit',methods=['POST'])
def submit():return 'Form submitted successfully!\n'@app.route('/index')
def index():return render_template('index.html')# 启动应用
if __name__ == '__main__':app.run(host='0.0.0.0',port='5000',debug=True)[root@localhost ~]# cd templates/
[root@localhost templates]# ls
base.html  greet.html  index.html
[root@localhost templates]# cat base.html 
<html lang="en">
<head><meta charset="UTF-8"><title>{% block title %}My Website{% endblock %}</title>  # 定义块开始与结束位置,并定义其中的内容。子模板引用父模板就是通过块来引用的。
</head>
<body><header><h1>Welcome to My Website</h1></header><div>  # div是html里的块级元素,属于容器,可包含标题、段落、表格等等。{% block content %}{% endblock %}  # 定义块开始与结束,content是内容。</div><footer><p>&copy; 2025 My Website</p>   # 页脚处的信息。</footer>
</body>
</html>
[root@localhost templates]# cat index.html 
{% extends 'base.html' %}{% block title %}Home{% endblock %}  # 网站标签处的显示信息。例如百度的,百度一下,你就知道。{% block content %}<h2> Welcome to the homepage !</h2>### 
{% extends 'base.html' %} 子模版继承了base.html模板。
{% block title %}Home {% endblock %} 覆盖父模板中的title块。
{% block content %} 定义页面的主要内容区域。[root@localhost ~]# python3 a.py* Serving Flask app 'a'* Debug mode: on
WARNING: This is a development server. Do not use it in a production deployment. Use a production WSGI server instead.* Running on all addresses (0.0.0.0)* Running on http://127.0.0.1:5000* Running on http://192.168.10.101:5000
Press CTRL+C to quit* Restarting with stat* Debugger is active!* Debugger PIN: 112-870-242[root@localhost ~]# curl 192.168.10.101:5000/index
<html lang="en">
<head><meta charset="UTF-8"><title>Home</title>
</head>
<body><header><h1>Welcome to My Website</h1></header><div><h2> Welcome to the homepage !</h2></div><footer><p>&copy; 2025 My Website</p></footer>
</body>

相关文章:

  • 文献阅读——NeuroBayesSLAM
  • 【MySQL】 数据库基础数据类型
  • Unity EventCenter 消息中心的设计与实现
  • 蓝牙的选型、设计及测试
  • 电力设备类——如何使用YOLOv8模型对配网缺陷检数据集进行训练、评估和可视化 这个配网销钉缺失检测图像数据集 配网缺陷检测图像数据集 配网缺陷
  • Don’t Shake the Wheel 论文阅读
  • Docker部署OpenSearch集群
  • QT中延时的用法及定时器的用法
  • 用HTML5+JavaScript实现汉字转拼音工具
  • 基于DQN的学习资源难度匹配智能体
  • 静态库的使用方法
  • 基于OAuth2-proxy和Keycloak为comfyui实现SSO
  • MCP Server 实践之旅第 3 站:MCP 协议亲和性的技术内幕
  • StringBuilder 和 StringBuffer 的线程安全分析
  • 动态规划中的 求“最长”、“最大收益”、“最多区间”、“最优策略” 双重 for + 状态转移
  • 问题六、SIMTOSIM部分遇到的问题及解决方法
  • IP隧道技术中数据包头部的变化分析:必然增加的封装机制
  • 自学嵌入式 day 23 - 数据结构 树状结构 哈希表
  • 语音合成之十五 语音合成(TTS)分句生成拼接时的响度一致性问题:现状、成因与对策
  • python开发环境管理和包管理
  • wordpress子目录 多站点/360seo
  • 河北青山建设集团有限公司网站/互联网广告平台排名
  • 企业网站建设哪里做网站好/前端性能优化有哪些方法
  • 怎样做购物网站/免费做网站推广的软件
  • 网站建设的目标有哪些/免费b站推广软件
  • 公司 网站制作/南京seo排名优化公司