[python] Flash Web Application Framework

brief introduction

Flask is a lightweight WSGI Web application framework. It is designed to make getting started quick and easy and can be extended to complex applications. Originally a simple wrapper around Werkzeug and Jinja, it has become one of the most popular Python Web application frameworks.

Flash source code
Flash User Guide

1, Simple example

from flask import Flask

app = Flask(__name__)

def hello():
    return "Hello, World!"
def index():
    return 'Index Page'
if __name__ == '__main__':

What does this code do?

  • 1. First, we imported the Flask class. An example of this class will be our WSGI application.

  • 2. Next, we create an instance of this class. The first parameter is the name of the application module or package__ name__ It is a convenient shortcut for most situations. This is necessary so that Flask knows where to look for resources, such as templates and static files.

  • 3. Then we use the route() decorator to tell Flask which URL should trigger our function.

  • 4. This function returns the message we want to display in the user's browser. The default content type is HTML, so the HTML in the string will be rendered by the browser.

2, Detailed usage summary of Flask

1. HTML escape

When HTML (the default response type in Flask) is returned, any user supplied values presented in the output must be escaped to prevent injection attacks. The HTML template rendered using Jinja described later will do this automatically.

escape() is displayed here and can be used manually. It has been omitted from most examples for brevity, but you should always pay attention to how you use untrusted data.

from markupsafe import escape

def hello(name):
    return f"Hello, {escape(name)}!"

If a user tries to submit a name, escaping will cause it to be rendered as text instead of running a script in the user's browser.

Capture a value from the URL in the route and pass it to the view function. These variable rules are explained below.

2. Routing

Modern Web applications use meaningful URLs to help users. If the page uses a meaningful URL that they can remember and use to directly access the page, users are more likely to like the page and return.

2.1. Use the route() decorator to bind the function to the URL.

def index():
    return 'Index Page'

def hello():
    return 'Hello, World'

2.2 variable rules

You can add the variable part to the URL < variable by using the tag part_ name>. Then, your function receives < variable_ Name > as keyword parameter. Alternatively, you can use a converter to specify the type of parameter,

for example<converter:variable_name>.
from markupsafe import escape

def show_user_profile(username):
    # show the user profile for that user
    return f'User {escape(username)}'

def show_post(post_id):
    # show the post with the given id, the id is an integer
    return f'Post {post_id}'

def show_subpath(subpath):
    # show the subpath after /path/
    return f'Subpath {escape(subpath)}'

Converter type:

Converter typemeaning
string(default) accepts any text without slashes
intAccept positive integers
floatAccept positive floating point values
pathLike string s, but also accept slashes
uuidAccept UUID string

2.3. Unique URLs / redirection behavior

The following two rules are different when using slashes.

def projects():
    return 'The project page'

def about():
    return 'The about page'

The specification URLprojects of the endpoint has a trailing slash. It is similar to a folder in a file system. If the URL you visit does not have a trailing slash (/ projects), Flask redirects you to the canonical URL /projects / with a trailing slash ().

The specification URLabout of the endpoint has no trailing slash. It is similar to the pathname of a file. Accessing a URL with a trailing slash (/ about /) produces a 404 "not found" error. This helps keep the URLs of these resources unique, helping search engines avoid indexing the same page twice.

2.4 website construction

To build the URL of a specific function, use the url_for() function. It accepts the name of the function as its first parameter and any number of keyword parameters, and each keyword parameter corresponds to the variable part of the URL rule. An unknown variable is attached to the URL as a query parameter.

Why use URL inversion_ For () instead of hard coding them into templates to build URLs?

  • Inversion is often more descriptive than hard coding URL s.
  • You can change the URL at once without having to remember to change the hard coded URL manually.
  • URL construction handles the escape of special characters transparently.
  • The generated path is always absolute, avoiding the unexpected behavior of relative paths in the browser.
  • If your application is outside the root of the URL, for example, in /myapplication instead of /_ For () can handle it correctly for you.

For example, here we use test_ request_ Use the context () method to try the url_for(). test_request_context() tells flag to act as if it is processing a request, even when we use a Python shell. See context local variables.

from flask import url_for

def index():
    return 'index'

def login():
    return 'login'

def profile(username):
    return f'{username}\'s profile'

with app.test_request_context():
    print(url_for('login', next='/'))
    print(url_for('profile', username='John Doe'))

Access the following path:


2.5 HTTP method

Web applications use different HTTP methods when accessing URL s. When using Flask, you should be familiar with HTTP methods. By default, routes only respond to GET requests. You can use the methods parameter of the decorator to handle different HTTP methods. route()

from flask import request

@app.route('/login', methods=['GET', 'POST'])
def login():
    if request.method == 'POST':
        return do_the_login()
        return show_the_login_form()
def do_the_login():
    return 'login'
def show_the_login_form():
    return 'show_the_login_form'

If GET exists, Flask will automatically add support for this method and process the request according to http rfread. Again, it is implemented automatically for you. HEADOPTIONS

Keywords: Python Front-end Flask

Added by joshi_v on Sun, 27 Feb 2022 11:54:07 +0200