当前位置:网站首页>【Flask】获取请求信息、重定向、错误处理
【Flask】获取请求信息、重定向、错误处理
2022-07-06 01:26:00 【科皮子菊】
前序文章:
获取请求数据
我们知道,对于 Web 应用程序,对客户端发送到服务器的数据做出反应至关重要。在 Flask 中,这个信息由全局request对象提供。
request对象
使用它的第一步则是从flask模块中导入:
from flask import request
前面的文章中介绍过,在httpt协议中,一个请求有多种可能,如GET,POST等。我们可以通过request.method来获取。在html端有时我们使用form表单(POST,PUT方法会进行数据请求)去提交数据,那么服务端获取form表单中数据的方式是通过form属性获取。一个简单的案例如下:
@app.route('/login', methods=['POST', 'GET'])
def login():
error = None
if request.method == 'POST':
if valid_login(request.form['username'],
request.form['password']):
return log_the_user_in(request.form['username'])
else:
error = 'Invalid username/password'
# the code below is executed if the request method
# was GET or the credentials were invalid
return render_template('login.html', error=error)
当key没有在form中时,就会包KeyError的异常。那么根据具体情形对齐进行try except操作进行捕捉。
对于html端在URL中传参时(?key=value),我们可以使用args的属性获取参数:
searcgword=request.args.get('key', '')
文件上传
还有一种数据类型就是文件。使用Flask也是比较方便的。我们只需要保证form表单中设置enctype='multipart/form-data',否则文件是不可以传输的。
上传的文件存储在运存中或者文件系统中的临时文件中。获取这个数据则是使用request的files属性。每个上传的文件都会存到那个字典中。它的行为就是Python的file对象,但是具有save()方法去允许你存储数据到服务器的文件系统中。一个简单的案例如下:
from flask import request
@app.route('/upload', methods=['GET', 'POST'])
def upload_file():
if request.method == 'POST':
f = request.files['the_file']
f.save('/var/www/uploads/uploaded_file.txt')
...
如果您想知道文件在上传到您的应用程序之前在客户端上是如何命名的,您可以访问filename属性。但是请记住,这个值是可以伪造的,所以永远不要相信那个值。如果要使用客户端的文件名将文件存储在服务器上,通过 Werkzeug 为您提供的secure_filename()函数传递它,如下:
from werkzeug.utils import secure_filename
@app.route('/upload', methods=['GET', 'POST'])
def upload_file():
if request.method == 'POST':
file = request.files['the_file']
file.save(f"/var/www/uploads/{
secure_filename(file.filename)}")
...
Cookies
如果你想访问cookies中的数据,我们则可以通过cookies属性。如果想设置cookies,我们则需要借用响应对象中的set_cookie方法。同样cookies属性是request对象的一个字典。如果您想使用Session,请不要直接使用 cookie,而是使用 Flask 中的Session,它会在 cookie 之上为您添加一些安全性。
读取cookies中内容的案例:
from flask import request
@app.route('/')
def index():
username = request.cookies.get('username')
# use cookies.get(key) instead of cookies[key] to not get a
# KeyError if the cookie is missing.
存储cookies内容案例:
from flask import make_response
@app.route('/')
def index():
resp = make_response(render_template(...))
resp.set_cookie('username', 'the username')
return resp
请注意,cookie 是在响应对象上设置的。由于您通常只从视图函数返回字符串,因此 Flask 会为您将它们转换为响应对象。如果您明确想要这样做,您可以使用 make_response() 函数,然后对其进行修改。有时您可能希望在响应对象尚不存在的位置设置 cookie。这可以通过使用延迟请求回调模式来实现。对于这些内容,则需要深入了解官方文档了。
重定向和错误处理
要将用户重定向到另一个端点,请使用 redirect() 函数;要使用错误代码提前中止请求,请使用 abort() 函数:
from flask import abort, redirect, url_for
@app.route('/')
def index():
return redirect(url_for('login'))
@app.route('/login')
def login():
abort(401)
this_is_never_executed()
这是一个相当没有意义的示例,因为用户将从索引重定向到他们无法访问的页面(401 表示访问被拒绝),但它显示了它是如何工作的。
默认情况下,每个错误代码都会显示一个黑白错误页面。如果要自定义错误页面,可以使用 errorhandler() 装饰器:
from flask import render_template
@app.errorhandler(404)
def page_not_found(error):
return render_template('page_not_found.html'), 404
注意 render_template() 调用后的 404。这告诉 Flask 该页面的状态码应该是 404,这意味着未找到。默认情况下假定为 200,这意味着:一切顺利。
边栏推荐
- VMware Tools installation error: unable to automatically install vsock driver
- A glimpse of spir-v
- About error 2003 (HY000): can't connect to MySQL server on 'localhost' (10061)
- 有谁知道 达梦数据库表的列的数据类型 精度怎么修改呀
- Convert binary search tree into cumulative tree (reverse middle order traversal)
- SSH login is stuck and disconnected
- 【详细】快速实现对象映射的几种方式
- [Yu Yue education] Liaoning Vocational College of Architecture Web server application development reference
- Superfluid_ HQ hacked analysis
- 【已解决】如何生成漂亮的静态文档说明页
猜你喜欢

The inconsistency between the versions of dynamic library and static library will lead to bugs

Loop structure of program (for loop)

Dede collection plug-in free collection release push plug-in

ORA-00030

Condition and AQS principle

Dedecms plug-in free SEO plug-in summary

晶振是如何起振的?

Finding the nearest common ancestor of binary search tree by recursion

500 lines of code to understand the principle of mecached cache client driver

基於DVWA的文件上傳漏洞測試
随机推荐
Huawei Hrbrid interface and VLAN division based on IP
MCU lightweight system core
Who knows how to modify the data type accuracy of the columns in the database table of Damon
【已解决】如何生成漂亮的静态文档说明页
【SSRF-01】服务器端请求伪造漏洞原理及利用实例
Is chaozhaojin safe? Will it lose its principal
3D模型格式汇总
JMeter BeanShell的基本用法 一下语法只能在beanshell中使用
普通人下场全球贸易,新一轮结构性机会浮出水面
MySQL learning notes 2
False breakthroughs in the trend of London Silver
Leetcode study - day 35
Test de vulnérabilité de téléchargement de fichiers basé sur dvwa
Recursive method to realize the insertion operation in binary search tree
视频直播源码,实现本地存储搜索历史记录
MUX VLAN configuration
[pat (basic level) practice] - [simple mathematics] 1062 simplest fraction
Four commonly used techniques for anti aliasing
Development trend of Ali Taobao fine sorting model
Alibaba-Canal使用详解(排坑版)_MySQL与ES数据同步