当前位置:网站首页>【flask入门系列】flask处理请求和处理响应
【flask入门系列】flask处理请求和处理响应
2022-06-26 01:41:00 【馆主阿牛】
个人简介
- 作者简介:大家好,我是阿牛,全栈领域新星创作者。
- 博主的个人网站:阿牛的博客小屋
- 支持我:点赞+收藏️+留言
- 系列专栏:flask框架快速入门
- 格言:迄今所有人生都大写着失败,但不妨碍我继续向前!

前言
上一节我写了flask获取路径参数以及转换器的使用,这节我们来讲如何获取其他地方的参数以及flask如何处理响应。
flask处理请求之request对象
如果想要获取其他地方的参数,可以通过Flask提供的request对象来读取,
不同位置的参数都存放在request的不同属性中,可以看下面的表格:
| 属性 | 说明 | 类型 |
|---|---|---|
| data | 记录请求的数据,并转换为字符串 | * |
| form | 记录请求中的表单数据 | MultDict |
| args | 记录请求中的查询参数 | MultDict |
| cookies | 记录请求中的cookies信息 | Dict |
| headers | 记录请求中的报文头 | EnvironHeaders |
| method | 记录请求使用的http方法 | GET/POST |
| url | 记录请求的URL地址 | string |
| files | 记录请求上传的文件 | * |
例如,想要获取请求/articles?channel_id 的参数,可以按如下方式使用:
#导入Flask类和request对象
from flask import Flask,request
app = Flask(__name__)
@app.route('/articles')
def get_articles():
channel_id = request.args.get('channel_id')
return 'you want get articles of channel {}'.format(channel_id)

不同于django,django的requset对象必须是视图函数的第一个参数,而Flask不同,我们需要用 from flask import request,并且不需要在视图函数参数中写request。
上传图片
客户端上传图片,并保存到服务器中
@app.route('/upload',methods=['POST'])
def upload_files():
f = request.files['pic'] # pic为文件名
# with open('./demo.png','wb') as new_file:
# new_file.write(f.read())
f.save('./demo.png') # 保存图片 save()方法是框架自带的快速保存文件的方法
return 'ok'
这个是存储上传的文件的路由和视图,还可以写一个提交文件的form表单对应的html,然后后端给个返回这个html文件的路由和视图,表单将文件提交到上面这个路由就行,这里先不写这个实现,大家可以用postman这款软件自己提交图片到这个路径测试一下就可以了,当你在做前后端结合的项目的时候这些东西都会慢慢掌握!
处理响应
1.返回模板 render_template
使用 render_template 方法渲染模板并返回
例如,新建一个模板index.html,放在templates目录下:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<div>{
{ my_str }}</div>
<div>{
{ my_int }}</div>
</body>
</html>
代码中的{ { }}为jinja2模板语法。
from flask import Flask,render_template
app = Flask(__name__)
@app.route('/')
def index():
mystr = "hello aniu"
mint = 20
return render_template('index.html',my_str=mystr,my_int=mint)

跟django不同的是,返回到前端的参数是直接放到 render_template 方法中的,而django是封装成字典,当然,利用python 的语法,我们也可以将其封装成字典。
@app.route('/')
def index():
data = {
'my_str':'hello aniu',
'my_int':20
}
return render_template('index.html',**data)
**data会将字典转换成独立的参数,相当于下面这行代码:
return render_template('index.html',my_str='hello aniu',my_int=20)
2.重定向 redirect
from flask import Flask,redirect
app = Flask(__name__)
app.route('/demo1')
def demo1():
return redirect("https://www.aniu.space/")
3.返回JSON
from flask import Flask,jsonify
app = Flask(__name__)
@app.route('/demo2')
def demo2():
json_dict = {
"user_id":10,
"user_name":"aniu"
}
return jsonify(json_dict)
jsonify()跟json模块中的json.dumps()的区别:
1.json.dumps()只是将字典转换成了json字符串,并没有改变HTTP响应报文中的Content-Type。
2.jsonify()不仅将字典转换为json字符串,而且将HTTP响应报文中的Content-Type值改为了application/json.

4.自定义状态吗和响应头
1.元组方式
可以返回一个元组,这样的元组必须是(response,status,headers)的形式,且至少包含一个元素。 status 值会覆盖状态代码, headers 可以是一个列表或字典,作为额外的消息标头值。
@app.route('/demo3')
def demo2():
return ('状态码666',666,{
'aniu':'hahaha'})

2.make _ response 方式
from flask import Flask,make_response
app = Flask(__name__)
@app.route('/demo4')
def demo4():
resp = make_response("make_response测试")
resp.headers['aniu'] = 'hahaha'
resp.status = "404 not found"
return resp

结语
如果你觉得博主写的还不错的话,可以关注一下当前专栏,博主会更完这个系列的哦!也欢迎订阅博主的其他好的专栏。
系列专栏
软磨 css
硬泡 javascript
前端实用小demo
更多专栏请移步博主主页查看! 博主的个人网站也很有趣,可以光顾一下哦:阿牛的博客小屋
边栏推荐
- Google 推荐在 MVVM 架构中使用 Kotlin Flow
- vulhub复现一 activemq
- 数据库的授权
- IPhone 13 screen stuck black, unable to shut down? How to solve
- SQL column value to row value (unpivot)
- 哪个证券公司手机股票开户更好更安全?
- Oracle练习
- Chapter I: essential information collection of penetration test
- Remember a simple JVM tuning experience
- 云答题不显示第三方登陆按钮是什么情况
猜你喜欢

In depth good article: what is supernetting?

How to check and cancel subscription auto renewal on iPhone or iPad

High availability in Internet three highs (high concurrency, high performance and high availability)

Breadth first traversal based on adjacency matrix

Problem solving process of no internet access

奶牛排序问题

MySQL必须掌握4种语言!

@Query difficult and miscellaneous diseases

One year's work

How to improve code execution efficiency with arm pipeline
随机推荐
Fastadmin applet assistant is purchased, but the work order cannot be published in the problem work order
【缺陷检测】基于matlab GUI印刷电路板自动缺陷检测【含Matlab源码 1912期】
二分查找
Agent challenge - "Olympic running"
UTONMOS:以数字藏品助力华夏文化传承和数字科技发展
哪个证券公司手机股票开户更好更安全?
R 语言马尔可夫链蒙特卡洛:实用介绍
Redis Lua sandbox bypass command execution (cve-2022-0543)
基于邻接矩阵的广度优先遍历
Which securities company should I choose to open an account online? Is it safe to open an account online?
A few simple ways for programmers to exercise their waist
What is the sudden power failure of iPhone and how to solve it?
如何在 R 中的绘图中添加回归方程
云答题不显示第三方登陆按钮是什么情况
2022年挖财商学院证券开户安全嘛?
2022-06-25: given a positive number n, it means that there are tasks 0~n-1. Given an array of length N, time[i] means the time when task I is completed. Given a two-dimensional array matrix, matrix[j]
Blazor University (33)表单 —— EditContext、FieldIdentifiers
High performance and high availability computing architecture based on microblog comments
7 tips to change your life
The programmer's eight-year salary change has made netizens envious: you pay me one year's salary per month