HttpRequest 2, common request methods 3, upload pictures

A profile,

We all know that Http protocol passes a Request object in the background when a browser accesses an address. The request object contains the request header, the request parameters, and the request method. Of course, the request can be fetched in the background. Then do the logical processing.

GET request

Let’s write an interface that accepts personal information, which is the view function. Let’s create a new template named register.html and write the following form in the template:

  • Action: indicates the address to be submitted
  • Method: request mode

      
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>

<form action="/center/add" method="get">User name:<input type="text" name="name"><br>Age:<input type="text" name="age"><br>Hobbies:<input type="checkbox" name="hobby" value="Eat"><input type="checkbox" name="hobby" value="Drink"><input type="checkbox" name="hobby" value="Play"><input type="checkbox" name="hobby" value="Le"><br>

    <input type="submit" value="Submit">

</form>

</body>
</html>
Copy the code

Two views need to be written in the background at this time, one view is used to display the registration page, and the other view is used to process the parameters passed from the front end:

from flask import Flask, request, render_template

app = Flask(__name__)


@app.route('/') #
def index(a):  View function
    return render_template('register.html')


@app.route('/center/add') # stands for personal center page
def center(a):  View function
    if request.method == 'GET':  # get
        name = request.args.get('name')  # args Takes the get parameter
        age = request.args.get('age')
        hobby = request.args.getlist('hobby')  # getList takes arguments of the one-key, multi-value type
        return "Name: %s Age: %s Hobby: %s" % (name, age, hobby)


app.config['DEBUG'] = True

if __name__ == '__main__':
    # 0.0.0.0 means that any address that represents the machine is accessible
    app.run(host='0.0.0.0', port=5000)  # run the program

Copy the code

Let’s visit in the browser:

POST request

Post requests are used for login and registration, and you don’t want your sensitive information to show up in a browser address. Post request (method); Post request (method);

method="post"
Copy the code

There are two things that need to be changed in the background:

  • Request method: The default is a GET request
  • Parameter advance: change args to form
from flask import Flask, request, render_template

app = Flask(__name__)


@app.route('/') #
def index(a):  View function
    return render_template('register.html')


@app.route('/center/add', methods=['GET', 'POST']
def center(a):  View function
    if request.method == 'GET':  # get
        name = request.args.get('name')  # args Takes the get parameter
        age = request.args.get('age')
        hobby = request.args.getlist('hobby')  # getList takes arguments of the one-key, multi-value type
        return "Name: %s Age: %s Hobby: %s" % (name, age, hobby)
    elif request.method == 'POST':
        name = request.form.get('name')  # form takes the post argument
        age = request.form.get('age')
        hobby = request.form.getlist('hobby')  # getList takes arguments of the one-key, multi-value type
        return "Name: %s Age: %s Hobby: %s" % (name, age, hobby)


app.config['DEBUG'] = True

if __name__ == '__main__':
    # 0.0.0.0 means that any address that represents the machine is accessible
    app.run(host='0.0.0.0', port=5000)  # run the program

Copy the code

When we click submit:

If it is Pos mode t, we can combine the view function into one:

  • Front end: The form can be submitted to the current address without action

      
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>

<form method="post">User name:<input type="text" name="name"><br>Age:<input type="text" name="age"><br>Hobbies:<input type="checkbox" name="hobby" value="Eat"><input type="checkbox" name="hobby" value="Drink"><input type="checkbox" name="hobby" value="Play"><input type="checkbox" name="hobby" value="Le"><br>

    <input type="submit" value="Submit">

</form>

</body>
</html>
Copy the code
  • Back-end: Handles different operations based on the request
from flask import Flask, request, render_template

app = Flask(__name__)


@app.route('/register', methods=['GET', 'POST']
def register(a):  View function
    if request.method == 'GET':  # get
        return render_template('register.html')  # return template
    elif request.method == 'POST':
        name = request.form.get('name')  # form takes the post argument
        age = request.form.get('age')
        hobby = request.form.getlist('hobby')  # getList takes arguments of the one-key, multi-value type
        return "Name: %s Age: %s Hobby: %s" % (name, age, hobby)


app.config['DEBUG'] = True

if __name__ == '__main__':
    # 0.0.0.0 means that any address that represents the machine is accessible
    app.run(host='0.0.0.0', port=5000)  # run the program

Copy the code

We visit the browser address is: http://0.0.0.0:5000/register

Upload files

Upload file is also a function we often use, the front-end upload a file, and then back-end processing save to the server. A file is a multimedia resource. Enctype =”multipart/form-data”. Create a template named upload.html and write the following code in the template:


      
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>

<form action="" method="post" enctype="multipart/form-data">
    <input type="file" name="file">
    <input type="submit" value="On">
</form>

</body>
</html>
Copy the code

We will create a new upload.py file and create a folder named media in the directory of this file to hold our uploaded images:

upload.py

from flask import Flask, request, render_template, redirect, url_for
from werkzeug.utils import secure_filename
import os
from flask import send_from_directory

app = Flask(__name__)

UPLOAD_FOLDER = 'media'
ALLOWED_EXTENSIONS = set(['txt'.'pdf'.'png'.'jpg'.'jpeg'.'gif'])
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER


# check whether the uploaded file is an acceptable suffix
def allowed_file(filename):
    return "." in filename and filename.rsplit('. '.1) [1].lower() in ALLOWED_EXTENSIONS


@app.route("/upload", methods=['GET', 'POST'])
def upload(a):
    if request.method == 'GET':  # get
        return render_template('upload.html')  # return template
    else:
        if "file" not in request.files:
            return redirect(request.url)

        file = request.files.get('file')  # fetch file

        if file.filename == ' ':
            return redirect(request.url)

        if file and allowed_file(file.filename):
            filename = secure_filename(file.filename)  # use this function to determine if the file name is safe.
            file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))  # save file
            return redirect(url_for('show',
                                    filename=filename))


# Show pictures
@app.route('/show/<filename>')
def show(filename):
    # send_from_directory can load files from directories
    return send_from_directory(app.config['UPLOAD_FOLDER'],
                               filename)


if __name__ == '__main__':
    # 0.0.0.0 means that any address that represents the machine is accessible
    app.run(host='0.0.0.0', port=5000, debug=True)  # run the program


Copy the code

Let’s visit in the browser:

Select an image from your computer and click Upload: