当前位置:网站首页>[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 !
     Please add a picture description

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)

 Insert picture description here

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)

 Insert picture description here
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.

 Insert picture description here

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'})

 Insert picture description here

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

 Insert picture description here

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

原网站

版权声明
本文为[Hall owner a Niu]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/177/202206260141322633.html