当前位置:网站首页>【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,这意味着:一切顺利。
边栏推荐
- Use of crawler manual 02 requests
- Vulhub vulnerability recurrence 74_ Wordpress
- internship:项目代码所涉及陌生注解及其作用
- Format code_ What does formatting code mean
- 朝招金安全吗 会不会亏损本金
- Docker compose配置MySQL并实现远程连接
- 1791. Find the central node of the star diagram / 1790 Can two strings be equal by performing string exchange only once
- Redis' cache penetration, cache breakdown, cache avalanche
- GNSS terminology
- [technology development -28]: overview of information and communication network, new technology forms, high-quality development of information and communication industry
猜你喜欢
Daily practice - February 13, 2022
Huawei converged VLAN principle and configuration
SSH login is stuck and disconnected
Poj2315 football games
现货白银的一般操作方法
[solved] how to generate a beautiful static document description page
General operation method of spot Silver
Finding the nearest common ancestor of binary search tree by recursion
500 lines of code to understand the principle of mecached cache client driver
3D视觉——4.手势识别(Gesture Recognition)入门——使用MediaPipe含单帧(Singel Frame)和实时视频(Real-Time Video)
随机推荐
internship:项目代码所涉及陌生注解及其作用
Idea sets the default line break for global newly created files
SCM Chinese data distribution
Live broadcast system code, custom soft keyboard style: three kinds of switching: letters, numbers and punctuation
网易智企逆势进场,游戏工业化有了新可能
Paging of a scratch (page turning processing)
Ordinary people end up in Global trade, and a new round of structural opportunities emerge
General operation method of spot Silver
Gartner released the prediction of eight major network security trends from 2022 to 2023. Zero trust is the starting point and regulations cover a wider range
How does Huawei enable debug and how to make an image port
MUX VLAN configuration
3D model format summary
ClickOnce 不支持请求执行级别“requireAdministrator”
A glimpse of spir-v
How to extract MP3 audio from MP4 video files?
ORA-00030
[pat (basic level) practice] - [simple mathematics] 1062 simplest fraction
Poj2315 football games
Leetcode skimming questions_ Verify palindrome string II
直播系统代码,自定义软键盘样式:字母、数字、标点三种切换