Flask is a lightweight Web framework.

Example:

from flask import Flask

app = Flask(__name__)

@app.route('/')
def main():
    return '<h1>hello world</h1>'

if __name__ == "__main__":
    app.run()

Start Flask Server:

$flask run --port 18888 --host 0.0.0.0

–port is used to specify the port of the service. If you want to keep the service running, add nohup in front.

To set it to Debug mode, execute: export FLASK_DEBUG=1

Windows with
setTo set the environment variable.

Parameters of the routing

Flask supports adding parameters to routes. The default type is String, but it can also be explicitly declared as int.

@app.route('/<id>') def func1(id): Id = int(id) ** 2 return STR (id) # @app.route('/<int:id>') def func2(id): Return STR (id ** 2) # @app.route('/<path:url_path>/') def func3(url_path) return 'path:%s' % url_path
Request way

Flask defaults to the GET method, and uses the methods parameter to specify more methods.

from flask import request @app.route('/', methods=['POST', 'GET']) def main(): if request.method == 'POST': Register_dict = request.form username = register_dict['usrename'] password = Register_dict. Get ('password') if request.method == 'get ': # Get the parameter of get method key = request.args.

The corresponding request method is:

import requests

params = {'username': 'un', 'password': 'pwd'}
r = requests.get(url, params=params)  # GET

data = {'username': 'un', 'password': 'pwd'}
r = requests.post(url, data=data)  # POST
The response

The parameters returned by the Flask view function will make up the response received by the user.

The first parameter is the response string; The second parameter is the status code, which Flask defaults to 200, indicating that the request has been successfully processed. The third parameter is the dictionary made up of the headers of the HTTP response.

@app.route('/') def index(): # return 'Bad Request', 400

There is a special type of response called a redirect.

from flask import redirect

@app.route('/')
def index():
    return redirect('http://www.example.com')

There is also a special response generated by the abort function to handle errors.

from flask import abort 
@app.route('/user/<id>')
def get_user(id):
    if id == 0:
        abort(404)
    return 'hello', 200

We can customize the error handling.

@app.errorHandler (404) def page_not_found(error): # return 'This page does not exist', 404