当前位置:网站首页>[flask introduction series] flask processing request and response
[flask introduction series] flask processing request and response
2022-06-26 02:44:00 【Hall owner a Niu】
Personal profile
- Author's brief introduction : Hello everyone , I'm Daniel , New star creator of the whole stack .
- Blogger's personal website : A Niu's blog house
- Stand by me : give the thumbs-up + Collection ️+ Leaving a message.
- Series column :flask Framework quick start
- Maxim : So far, all life is about failure , But it doesn't prevent me from moving forward !

Catalog
Preface
In the last section, I wrote flask Get the path parameters and the use of the converter , In this section, we will talk about how to obtain parameters in other places and flask How to handle the response .
flask Processing request request object
If you want to get parameters elsewhere , Can pass Flask Provided request Object to read ,
Parameters in different locations are stored in request In different properties of , Look at the table below :
| attribute | explain | type |
|---|---|---|
| data | Record the requested data , And convert it to a string | * |
| form | Record the form data in the request | MultDict |
| args | Record the query parameters in the request | MultDict |
| cookies | Record... In the request cookies Information | Dict |
| headers | Record the message header in the request | EnvironHeaders |
| method | Record the http Method | GET/POST |
| url | Record the requested URL Address | string |
| files | Record the file requested to upload | * |
for example , Want to get the request /articles?channel_id Parameters of , It can be used as follows :
# Import Flask Classes and request object
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)

differ django,django Of requset The object must be the first argument to the view function , and Flask Different , We need to use from flask import request, And there is no need to write... In the view function parameters request.
To upload pictures
The client uploads the picture , And save it to the server
@app.route('/upload',methods=['POST'])
def upload_files():
f = request.files['pic'] # pic For the file name
# with open('./demo.png','wb') as new_file:
# new_file.write(f.read())
f.save('./demo.png') # Save the picture save() Method is the method of quickly saving files provided by the framework
return 'ok'
This is the route and view for storing uploaded files , You can also write a submission file form The form corresponds to html, Then the back end returns this html Routing and view of files , The form submits the file to the above route , This implementation will not be written here , You can use postman This software can submit pictures to this path for testing , When you are working on a front-end and back-end project, you will gradually master these things !
Process response
1. Back to template render_template
Use render_template Method renders the template and returns
for example , Create a new template index.html, Put it in templates Under the table of contents :
<!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>
In code { { }} by jinja2 Template syntax .
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)

Follow django The difference is , The parameters returned to the front end are directly put into render_template Methods , and django Is encapsulated into a dictionary , Of course , utilize python The grammar of , We can also encapsulate it into a dictionary .
@app.route('/')
def index():
data = {
'my_str':'hello aniu',
'my_int':20
}
return render_template('index.html',**data)
**data Will convert the dictionary into independent parameters , Equivalent to the following line of code :
return render_template('index.html',my_str='hello aniu',my_int=20)
2. Redirect redirect
from flask import Flask,redirect
app = Flask(__name__)
app.route('/demo1')
def demo1():
return redirect("https://www.aniu.space/")
3. return 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() Follow json Module json.dumps() The difference between :
1.json.dumps() It just converts the dictionary into json character string , It hasn't changed HTTP In the response message Content-Type.
2.jsonify() Not only does the dictionary translate into json character string , And will HTTP In the response message Content-Type Change the value to application/json.

4. Custom status and response headers
1. Tuple mode
You can return a tuple , Such a tuple must be (response,status,headers) In the form of , And contain at least one element . status Value will override the status code , headers It can be a list or a dictionary , As an additional message header value .
@app.route('/demo3')
def demo2():
return (' Status code 666',666,{
'aniu':'hahaha'})

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

Conclusion
If you think the blogger's writing is good , You can pay attention to the current column , Bloggers will finish this series ! You are also welcome to subscribe to other good columns of bloggers .
Series column
Soft grinding css
Hard bubble javascript
The front end is practical and small demo
For more columns, please go to the blogger's home page ! Bloggers are also very interesting , You can patronize : A Niu's blog house
边栏推荐
猜你喜欢
随机推荐
程序员的八年工资变动,令网友羡慕不已:你一个月顶我一年工资
Bloc入门之Cubit详解
[机器翻译]—BLEU值的计算
What is flush software? Is online account opening safe?
How to solve the problem that the iPhone 13 lock screen cannot receive the wechat notification prompt?
Advanced cross platform application development (23): an article approaching the launch of testlight
Matlab|基于BP神经网络进行电力系统短期负荷预测
音视频与CPU架构
NoSQL之Redis配置与优化
MySQL must master 4 languages!
Which securities company is better and safer to open a mobile stock account?
The programmer's eight-year salary change has made netizens envious: you pay me one year's salary per month
图的广度优先遍历
Version management tool usage
表达式的动态解析和计算,Flee用起来真香
Wechat launched a web version transmission assistant. Is it really easy to use?
网上股票开户安全吗?
股票开户怎么开户?网上开户是否安全么?
官方零基础入门 Jetpack Compose 的中文课程来啦!
Redis Lua sandbox bypass command execution (cve-2022-0543)









