Python 之 Flask 框架学习

news2024/10/5 23:26:57

毕业那会使用过这个轻量级的框架,最近再来回看一下,依赖相关的就不多说了,直接从例子开始。下面示例中的 html 模板,千万记得要放到 templates 目录下。

Flask基础示例

hello world

from flask import Flask, jsonify, url_for

app = Flask(__name__)


@app.route('/')
def hello_world():
    return '<h1>Hello World!</h1>'


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

路由

既然涉及到web框架,就必然涉及到路由。

动态路由

动态路由就是将变量拼接到路由 url 当中,可以把字段编辑为<variable_name>,这个部分将会作为命名参数传递到你的函数。如果在动态路由中指定了变量的类型,比如 <int:user_id>,则需要按照指定类型进行传值,否则的话也会报错。参数也可以根据类似 request.args.get("id") 进行获取。

from flask import Flask, request

app = Flask(__name__)


@app.route('/')
def hello_world():
    return 'Hello World!'


@app.route('/user/<username>')
def show_user_profile(username):
    id = request.args.get("id")
    return 'User %s, id %s' % (username, id)


@app.route('/users/<int:user_id>')
def show_user_id(user_id):
    return 'User id %d' % user_id


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

构造 url

Flask 还可以用 url_for() 函数来给指定的函数构造URL,也称为反向路由。它接收函数名作为第一个参数,也接受对应 URL 规则的变量部分的命名参数。未知变量部分会添加到URL末尾作为查询条件。

from flask import Flask, url_for

app = Flask(__name__)


@app.route('/')
def hello_world():
    return url_for('article', id=1, name="look")  # /article/1?name=look


@app.route('/article/<id>')
def article(id):
    return f'id {id} article detail'


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

http方法

HTTP 有许多的不同的构造方法访问 URL 方法。默认情况下,路由只回应 GET 请求,当时通过route() 装饰器传递 methods 参数可以改变这个行为,至于每个 method 对应的行为,这块就不多细说了。

from flask import Flask, url_for, request

app = Flask(__name__)


@app.route('/', methods=['GET', 'POST'])
def index():
    if request.method == 'POST':
        return "go post method"
    elif request.method == 'GET':
        return "go get method"


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

 模板

html模板文件一般默认是放在 templates 目录下的,如果没有这个目录的话,可以自己新建一个。

templates/index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>template</title>
</head>
<body>
<h1>hello world!</h1>
</body>
</html>
from flask import Flask, render_template

app = Flask(__name__)


@app.route('/')
def hello_world():
    return render_template('index.html')


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

变量替换

而且还可以将内容传递到模板文件进行展示,下面这种也是展示 hello world!只不过我们将静态文件的内容藏起来了,通过后端返回的内容再显示出来,用的是模板语法,两种方法在前端显示的都一样。

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>template</title>
</head>
<body>
<h1>{{content}}</h1>
</body>
</html>
from flask import Flask, render_template

app = Flask(__name__)


@app.route('/')
def hello_world():
    content = "hello world!"
    return render_template('index.html', content=content)


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

当然,也可以将对象实例传递到模板中去。

user_index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>user</title>
</head>
<body>
<h1>hello {{user.name}}</h1>
</body>
</html>

models.py

class User:
    def __init__(self, id, name):
        self.id = id
        self.name = name

main.py

from flask import Flask, render_template
from models import User

app = Flask(__name__)


# 引用模板
@app.route('/')
def hello_world():
    content = 'hello world!'
    return render_template('index.html', content=content)


@app.route('/user')
def user_index():
    user = User(1, 'Looking')
    return render_template('user_index.html', user=user)


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

条件语句 

info.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>条件语句</title>
</head>
<body>
    {% if user.id == 1 %}
    <h1> Hello {{user.name}}</h1>
    {% else %}
    <h1>There is no user!</h1>
    {% endif %}
</body>
</html>
from flask import Flask, render_template
from models import User

app = Flask(__name__)


# 路由
@app.route('/info/<user_id>')
def info_judge(user_id):
    user = None
    if int(user_id) == 1:
        user = User(1, 'Looking')
    return render_template('info.html', user=user)


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

循环语句

list.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>循环语句</title>
</head>
<body>
    {% for user in users %}
    <h4>user_id: {{user.id}}; user_name: {{user.name}}</h4><br>
    {% endfor %}
</body>
</html>
from flask import Flask, render_template
from models import User

app = Flask(__name__)


# 路由
@app.route('/list')
def info_judge():
    users = []
    for i in range(5):
        users.append(User(i, f"student{i}"))
    return render_template('list.html', users=users)


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

 

模板继承

我们会发现有一些网页的有些部分是不变的,比如说页头页脚等,当跳转相同网页的时候只有中间部分会改变,这就要使用到模板的继承,可以使用 extends 实现对模板文件的继承。

base.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>模板的继承</title>
</head>
<body>
    <div>
        <H2>Header 欢迎光临!</H2>
    </div>
    {% block content %}
    {% endblock %}
    <div>
        <H2>Footer 欢迎下次再来!</H2>
    </div>
</body>
</html>

page_one.html

{% extends 'base.html'%}
{% block content %}
    <h3>{{content}}</h3>
{% endblock %}

 page_two.html

{% extends 'base.html'%}
{% block content %}
    <h3>{{content}}</h3>
{% endblock %}

 main.py

from flask import Flask, render_template
app = Flask(__name__)


# 第一页路由
@app.route('/page_one')
def one_page():
    content = '这是第一页!'
    return render_template('page_one.html', content=content)


# 第二页路由
@app.route('/page_two')
def secend_page():
    content = '这是第二页!'
    return render_template('page_two.html', content=content)


# 运行
if __name__ == "__main__":
    app.run()

消息提示

使用 flash 可以将后台处理的消息提示刷新到页面

index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Flask消息提示与异常捕获</title>
</head>
<body>
<h1>Login</h1>
    <form action="/login" method="post">
        <input type="text" name="username" placeholder="账号"><br />
        <input type="password" name="password" placeholder="密码" style="margin-top:10px"><br />
        <input type="submit" value="Submit" style="margin-left:50px;margin-top:10px">
    </form>
    <!--这里获取的是一个数组-->
    {{get_flashed_messages()[0]}}
</body>
</html>

main.py 

from flask import Flask, render_template, flash, request

app = Flask(__name__)
# 对flash的内容加密
app.secret_key = '123'


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


# 路由
@app.route('/login', methods=['POST'])
def login():
    # 获取表单上传的数据
    form = request.form
    username = form.get('username')
    password = form.get('password')
    # 进行判断
    if not username:
        flash("please enter username")
        return render_template("index.html")
    if not password:
        flash("please enter password")
        return render_template("index.html")
    if username == "looking" and password == "123456":
        flash("login success")
        return render_template("index.html")
    else:
        flash("username and password not match!")
        return render_template("index.html")


# 运行
if __name__ == "__main__":
    app.run()

异常捕获 

如果用户输入了错误的路径,创建网站的人又没有设置异常捕获及处理,它会出现404;如果处理了的话,那就显示的为处理后的页面。所以,我们的异常处理也就是对返回的 404 页面(或者其他异常)返回我们设置的页面。

404.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Flask异常捕获与处理</title>
</head>
<body>
    <h2>抱歉,你访问的页面去火星了......</h2><br />
    <h2>请检查你的网址是否输入正确!</h2>
</body>
</html>

user.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<h1>This is user page</h1>
​
</body>
</html>

 main.py

from flask import Flask, render_template, abort

app = Flask(__name__)


# 异常捕获一
@app.errorhandler(404)
def not_found():
    return render_template('404.html'), 404


# 异常捕获二
@app.route('/user/<user_id>')
def user_info(user_id):
    if int(user_id) == 1:
        return render_template("user.html")
    else:
        abort(404)


if __name__ == "__main__":
    app.run()

如果没有添加针对 404 的错误处理,就是下面这种界面。

403 是 Forbidden

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/1564963.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

舞蹈网站制作分享,舞蹈培训商城网站设计案例分享,wordpress主题分享

嘿&#xff0c;朋友们&#xff01;今天我要跟你们唠一唠一个超级酷炫的舞蹈培训商城网站设计案例。 咱先说说这个网站的目标哈&#xff0c;那就是得让喜欢舞蹈的小伙伴们能够轻轻松松找到自己心水的课程和商品。 那制作过程都有啥呢&#xff1f;别急&#xff0c;听我慢慢道来。…

C#开发中一些常用的工具类分享

一、配置文件读写类 用于在开发时候C#操作配置文件读写信息 1、工具类 ReadIni 代码 using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Runtime.InteropServices; using System.Text; using System.Threading.Tasks;namesp…

如何将本地仓库放到远程仓库中

在我们仓库创建好之后&#xff0c;我们复制好ssh 接着我们需要使用git remote add<shortname><url>这个命令 shortname就是我们远程仓库的别名 接着使用git remote -v这个命令查看一下目前远程仓库的别名和地址 原本还有一个指令git branch -M main 指定分支的名…

全志 Linux Qt

一、简介 本文介绍基于 buildroot 文件系统的 QT 模块的使用方法&#xff1a; • 如何在 buildroot 工具里编译 QT 动态库&#xff1b; • 编译及运行 qt_demo 应用程序&#xff1b; • 适配过程遇到的问题。 二、QT动态库编译 在项目根路径执行 ./build.sh buildroot_menuc…

酷开科技智慧AI让酷开系统大显身手!

时代的浪潮汹涌而至&#xff0c;人工智能作为技术革新和产业变革的重要引擎&#xff0c;正深刻地影响着各行各业。在科技的海洋中&#xff0c;AI技术正逐渐渗透到我们的日常生活中&#xff0c;为我们带来前所未有的便捷和智慧。酷开科技用技术探索智慧AI&#xff0c;别看它只是…

MySQL 中将使用逗号分隔的字段转换为多行数据

在我们的实际开发中&#xff0c;经常需要存储一些字段&#xff0c;它们使用像, - 等连接符进行连接。在查询过程中&#xff0c;有时需要将这些字段使用连接符分割&#xff0c;然后查询多条数据。今天&#xff0c;我们将使用一个实际的生产场景来详细解释这个解决方案。 场景介绍…

JeeSite Vue3:前端开发控制实现基于身份角色的权限验证

随着技术的飞速发展&#xff0c;前端开发技术日新月异。在这个背景下&#xff0c;JeeSite Vue3 作为一个基于 Vue3、Vite、Ant-Design-Vue、TypeScript 和 Vue Vben Admin 的前端框架&#xff0c;引起了广泛关注。它凭借其先进的技术栈和丰富的功能模块&#xff0c;为初学者和团…

【教程】Kotlin语言学习笔记(五)——Lambda表达式与条件控制

写在前面&#xff1a; 如果文章对你有帮助&#xff0c;记得点赞关注加收藏一波&#xff0c;利于以后需要的时候复习&#xff0c;多谢支持&#xff01; 【Kotlin语言学习】系列文章 第一章 《认识Kotlin》 第二章 《数据类型》 第三章 《数据容器》 第四章 《方法》 第五章 《L…

LangChain-03 astream_events 流输出

内容简介 尝试用 FAISS 或 DocArrayInMemorySearch 将数据向量化后检索astream_events 的效果为 |H|arrison| worked| at| Kens|ho|.|| 安装依赖 # 之前的依赖即可 pip install --upgrade --quiet langchain-core langchain-community langchain-openai # Win或Linux用户可…

算法学习——LeetCode力扣动态规划篇3(494. 目标和、474. 一和零、518. 零钱兑换 II)

算法学习——LeetCode力扣动态规划篇3 494. 目标和 494. 目标和 - 力扣&#xff08;LeetCode&#xff09; 描述 给你一个非负整数数组 nums 和一个整数 target 。 向数组中的每个整数前添加 ‘’ 或 ‘-’ &#xff0c;然后串联起所有整数&#xff0c;可以构造一个 表达式 …

【xinference】(8):在autodl上,使用xinference部署qwen1.5大模型,速度特别快,同时还支持函数调用,测试成功!

1&#xff0c;关于xinference https://www.bilibili.com/video/BV14x421U74t/ 【xinference】&#xff08;8&#xff09;&#xff1a;在autodl上&#xff0c;使用xinference部署qwen1.5大模型&#xff0c;速度特别快&#xff0c;同时还支持函数调用&#xff0c;测试成功&#…

系统IO函数接口

目录 前言 一. man手册 1.1 man手册如何查询 1.2 man手册基础 二.系统IO函数接口 三.open打开文件夹 3.1 例1 open打开文件 3.2 open打开文件代码 3.3 例2 创建文件 四.write写文件 4.1 write写文件 五. read读文件 5.1 read读文件与偏移 5.2 偏移细节 5.3 read读文件代码 六.复…

1,static 关键字.Java

目录 1.概述 2.定义格式和使用 2.1 静态变量及其访问 2.2 实例变量及其访问 2.3 静态方法及其访问 2.4 实例方法及其访问 3.小结 1.概述 static表示静态&#xff0c;是Java中的一个修饰符&#xff0c;可以修饰成员方法&#xff0c;成员变量。被static修饰后的&#xff…

STM32CubeMX配置步骤详解零 —— 引言

引子 初识 笔者接触STM32系列MCU有些年头了。初次接触是2015年&#xff0c;那时是在第二空间&#xff08;北京&#xff09;科技有限公司上班&#xff0c;是以STM32F407&#xff08;后缀好像是RGT6或ZGT6&#xff0c;记得不是很清楚了&#xff09;为主芯片做VR头戴式设备&…

40道Java经典面试题总结

1、在 Java 中&#xff0c;什么时候用重载&#xff0c;什么时候用重写&#xff1f; &#xff08;1&#xff09;重载是多态的集中体现&#xff0c;在类中&#xff0c;要以统一的方式处理不同类型数据的时候&#xff0c;可以用重载。 &#xff08;2&#xff09;重写的使用是建立…

githacker安装使用

githack下载不了文件&#xff0c;换个工具&#xff01; 项目地址 WangYihang/GitHacker: &#x1f577;️ A .git folder exploiting tool that is able to restore the entire Git repository, including stash, common branches and common tags. (github.com) 安装 pyth…

光伏行业项目管理系统解决方案!企智汇光伏项目管理系统!

光伏行业项目管理系统解决方案旨在通过整合和优化项目管理流程&#xff0c;提高光伏项目的执行效率和质量。以下是企智汇软件详细的光伏行业项目管理系统解决方案的框架&#xff1a; 一、系统概述 企智汇光伏行业项目管理系统是一个集项目规划、执行、监控和收尾于一体的综合…

Vue3:用Pinia的storeToRefs结构赋值store数据

一、情景描述 我们学习了Pinia之后&#xff0c;知道&#xff0c;数据是配置在Pinia的state里面的。 那么&#xff0c;如果有多个字段需要取出来使用&#xff0c;并且不丢失数据的响应式&#xff0c;如何优雅的操作了&#xff1f; 这里就用到了Pinia的storeToRefs函数 二、案…

【CANN训练营笔记】AscendCL图片分类应用(C++实现)

样例介绍 基于PyTorch框架的ResNet50模型&#xff0c;对*.jpg图片分类&#xff0c;输出各图片所属分类的编号、名称。 环境介绍 华为云AI1s CPU&#xff1a;Intel Xeon Gold 6278C CPU 2.60GHz 内存&#xff1a;8G NPU&#xff1a;Ascend 310 环境准备 下载驱动 wget ht…

CAPL实现关闭TCP连接的几种方式以及它们的区别

在讲正文前,我们有必要复习下关闭TCP连接的过程:四次挥手。 假设A和B建立TCP连接并进行数据传输,当A的数据发送完后,需要主动发起断开连接的请求: A发送FIN报文,发起断开连接的请求B收到FIN报文后,首先回复ACK确认报文B把自己的数据发送完,发送FIN报文,发起断开连接的…