Python第三方库 - Flask(python web框架)

1 Flask

1.1 认识Flask

Web Application FrameworkWeb 应用程序框架)或简单的 Web FrameworkWeb 框架)表示一个库和模块的集合,使 Web 应用程序开发人员能够编写应用程序,而不必担心协议,线程管理等低级细节。

1.2 Pycharm安装与简单测试

1.2.1 安装

Pycharm 安装 Flask 框架
FileSettingsProject: [project name]Project Interpreter

1.2.2 简单测试

运行下面代码,打开http://127.0.0.1:5000的链接

py 复制代码
from flask import Flask
# __name__:代表当前模块,app为类的实例
app = Flask(__name__)

# 创建一个路由和视图函数的映射
@app.route('/')
def hello_world():
   return 'Hello World'

if __name__ == '__main__':
   app.run()
   #app.run(host='0.0.0.0', port=5000)
1.2.3 Debug模式(热更新)

Debug 模式从控制台可以看见

Pycharm 专业版开启方法:

右上角的项目名称 → Edit Configurations → 勾选FLASK_DEBUG选项 → 重启项目

Pycharm 社区版开启方法:

py 复制代码
# 开启Debug模式 运行时传递参数
app.run(debug=True)
1.2.4 社区版Pycharm建立Flask Project
文件夹 作用
static 存放静态文件
templates 存放模板文件

2 Flask模块的语法与使用

2.1 Flask路由与路由参数

2.1.1 路由

Flask 中的route() 装饰器用于将URL 绑定到函数,下面代码运行在http://127.0.0.1:5000/hello

py 复制代码
@app.route('/hello')
def hello_world():
   return 'hello world'

application 对象的 a dd_url_rule() 函数也可用于将 URL 与函数绑定

py 复制代码
from flask import Flask
app = Flask(__name__)

def hello_world():
   return 'hello world'

app.add_url_rule('/', 'hello', hello_world)
app.run()
2.1.2 路由参数(动态构建UrL)

通过向规则参数添加变量部分,可以动态构建URL

此变量部分标记为<variable-name>

它作为关键字参数传递给与规则相关联的函数。

py 复制代码
from flask import Flask
app = Flask(__name__)

@app.route('/hello/<name>')
def hello_name(name):
   return 'Hello %s!' % name

@app.route('/blog/<int:postID>')
def show_blog(postID):
   return 'Blog Number %d' % postID

@app.route('/rev/<float:revNo>')
def revision(revNo):
   return 'Revision Number %f' % revNo

if __name__ == '__main__':
   app.run(debug = True)
2.1.3 URL构建

url_for()函数用于动态构建特定函数的URL

py 复制代码
语法
url_for(函数名,关键字参数)

举例:
from flask import Flask, redirect, url_for
app = Flask(__name__)
@app.route('/world')
def hello_world():
   return 'Hello  world!!!'


@app.route('/test/<str>')
def hello_test(str):
   return '%s !!!' % str


@app.route('/other/<oth>')
def hello_other(oth):
   if oth =='world':
      return redirect(url_for('hello_world'))
   else:
      return redirect(url_for('hello_test',  str= '随便拉'))


if __name__ == '__main__':
   app.run(debug = True)

代码解析:
在postman输入http://127.0.0.1:5000/other/world网址,如果查接收的参数与world匹配,则重定向hello_world()函数
否则:
重定向到hello_test()函数

2.2 Flask与web交互

2.2.1 Flask和表单
py 复制代码
html代码

<style>
    form{
        margin:300px auto;
        display:block;
    }
</style>
<body>
      <form action="http://localhost:5000/test" method="post" style="width:300px;height:30px">
        <div class="">
          <label for="exampleFormControlTextarea1" class="form-label">Example textarea</label>
          <textarea class="form-control" id="exampleFormControlTextarea1" rows="3" name="txt"></textarea>
        </div>
         <input class="btn btn-primary" type="submit" value="Submit">
      </form>
</body>

py代码

from flask import Flask, redirect, url_for, request, render_template

app = Flask(__name__)

@app.route('/page')
def index():
    return render_template("1.html")

@app.route('/success/<name>')
def success(name):
    return 'welcome %s' % name

@app.route('/test',methods = ['POST', 'GET'])
def test():
    if request.method == 'POST':
        txt = request.form['txt']
        print(txt)
        return redirect(url_for('success', name=txt))
    else:
        return redirect(url_for('index'))

if __name__ == '__main__':
    app.run(debug=True)
2.2.2 Flask模板

三种常用的定界符:

py 复制代码
{{ ... }} 用来标记变量。
{% ... %} 用来标记语句,比如 if 语句,for 语句等。
{# ... #} 用来写注释。

render_template 方法渲染的模板需要在 templates 文件夹下

py 复制代码
hello.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
我的模板html内容
  <br />{{ my_str }}
  <br />{{ my_int }}
  <br />{{ my_array }}
</body>
</html>

test.py

from flask import Flask, redirect, url_for, request, render_template

app = Flask(__name__)

@app.route('/')
def index():
    # 往模板中传入的数据
    my_str = 'Hello Word'
    my_int = 10
    my_array = [3, 4, 2, 1, 7, 9]
    return render_template('hello.html',
                           my_str = my_str,
                           my_int = my_int,
                           my_array = my_array
                           )

if __name__ == '__main__':
    app.run(debug=True)
2.2.3 静态文件

例如引入static 文件下的 1.css,在 html 中写入下面的代码:

html 复制代码
    <link rel="stylesheet" href="{{ url_for('static', filename='1.css') }}" type="text/css">

3 参考文档

1\] [W3CSchool教程](https://www.w3cschool.cn/flask/flask_http_methods.html) \[2\] [社区版Pycharm自建Flask项目](https://blog.csdn.net/miracle2me/article/details/121704284?ops_request_misc=%257B%2522request%255Fid%2522%253A%2522169820506116800182773243%2522%252C%2522scm%2522%253A%252220140713.130102334..%2522%257D&request_id=169820506116800182773243&biz_id=0&utm_medium=distribute.pc_search_result.none-task-blog-2~all~top_positive~default-1-121704284-null-null.142%5Ev96%5Epc_search_result_base3&utm_term=pycharm%E7%A4%BE%E5%8C%BA%E7%89%88%E5%88%9B%E5%BB%BAflask%E9%A1%B9%E7%9B%AE&spm=1018.2226.3001.4187) \[3\] [Flask Request对象](https://zhuanlan.zhihu.com/p/623755314) \[4\] [静态文件引用](https://blog.51cto.com/u_15694353/5410660#:~:text=%E7%AC%AC%E4%B8%80%E7%A7%8D%E6%96%B9%E6%B3%95%EF%BC%9Aflask%E5%A4%84%E7%90%86%E2%80%93static%E5%A6%82%E4%B8%8B%E4%BE%8B%E6%89%80%E7%A4%BA%EF%BC%9A%3Clinkhref=%22/static/css/style.css%22rel=%22stylesheet%22type=%22text/css%22/%3E%E7%AC%AC%E4%BA%8C%E7%A7%8D%E6%96%B9%E6%B3%95%EF%BC%9Aurl_for%E6%9E%84%E9%80%A0%E8%B7%AF%E5%BE%84%E5%A6%82%E4%B8%8B%E4%BE%8B%E6%89%80%E7%A4%BA%EF%BC%9A%3Clinkhref=%22url_for,%28%22static%22,filename=%22css/s)

相关推荐
再见晴天*_*1 小时前
SpringBoot 中单独一个类中运行main方法报错:找不到或无法加载主类
java·开发语言·intellij idea
lqjun08272 小时前
Qt程序单独运行报错问题
开发语言·qt
人工智能训练师3 小时前
Ubuntu22.04如何安装新版本的Node.js和npm
linux·运维·前端·人工智能·ubuntu·npm·node.js
Seveny073 小时前
pnpm相对于npm,yarn的优势
前端·npm·node.js
酷飞飞3 小时前
Python网络与多任务编程:TCP/UDP实战指南
网络·python·tcp/ip
yddddddy4 小时前
css的基本知识
前端·css
昔人'4 小时前
css `lh`单位
前端·css
hdsoft_huge4 小时前
Java & Spring Boot常见异常全解析:原因、危害、处理与防范
java·开发语言·spring boot
风中的微尘4 小时前
39.网络流入门
开发语言·网络·c++·算法
数字化顾问5 小时前
Python:OpenCV 教程——从传统视觉到深度学习:YOLOv8 与 OpenCV DNN 模块协同实现工业缺陷检测
python