Flash Web Development Foundation

Flask is not only a free web framework, but also a young and dynamic small framework. It has complete development documents, high community activity and many supporters. The design goal of flask is to implement a WSGI micro framework, and its core code is very simple.

Introduction to flash framework

The share of flash framework in small and medium-sized enterprises is relatively high. Web framework is generally used to develop lightweight web applications. In terms of market share, flash framework also ranks high. This paper mainly introduces the basic knowledge of Flask framework, including its basic structure and its comparison with Django framework.

Basic structure of flash framework

The Flask framework mainly relies on two libraries: werkzeug and jinja2.

werkzeug: is a WSGI toolset that is a standard python interface between web applications and multiple servers.

jinja2: responsible for rendering the template and displaying the template file composed of HTML, CSS and JavaScript.

The basic structure diagram of Flask framework is as follows:

In order to improve development efficiency and reduce redundant code, the Flask framework will spare time for the common part of Web development so that it can be used multiple times in different pages. When the client wants to obtain some information data from the Web server, it will launch an HTTP request (for example, we usually enter a URL in the browser). The Web application will carry out corresponding business processing in the background (for example, reading the database or doing some calculations), and then read the data required by the user to generate the corresponding HTTP response. If you are accessing static resources, you can directly return the resources without business operations.

Install flash

Here I suggest that readers install anaconda to create virtual environments and install third-party libraries.

Installing flash on Windows systems

pip install flask

First knowledge of flash web program

The following is a program to demonstrate the process of developing web programs with the flash framework

from json.tool import main
import flask    # Import falsk module
app = flask.Flask(__name__)  #Instantiate flash
@app.route('/') # Decorator operation to realize URL address
def hello():    # Define business processing function (Hello)
    return "This is our first one flask program"

if __name__ == '__main__':
    app.run()   # Run program

Analyze the basic structure of web program

app.run()

The function of the above code is to call run() in the flash class method to run the current flash web program on the local server. The name of the current flash web program is app. The prototype of the run method is as follows:

(method) run: (host: str | None = None, port: int | None = None, debug: bool | None = None, load_dotenv: bool = True, **options: Any) -> None

Three of the parameters are commonly used, but they are optional.

  • Host: the host name of the current flash program. The default value is 127.0.0.1 or localhost
  • Port: the port number corresponding to the host running the current flash program. The default value is 5000
  • debug: set whether to display debugging information. The default value is False. If it is set to True, debugging information will be displayed. It is suggested that readers can open debugging information during program development.

The purpose of debugging is that if the code changes during debugging, the server will automatically restart and run the flash web program, so as to improve the effect of program operation. If it is not set to debug mode, you need to manually restart the program every time, which is quite troublesome.

Routing processing

At present, in the field of web development, the mainstream third-party framework mainly uses URL routing technology to access a specific page. In the flash web program, the client (browser) sends the access request to the web server, and the web server sends the request to the flash web program. The flask framework maps routes to python functions.

Flash framework supports three routing technologies

(1) Use route method ()

In the Flask framework, an ordinary hash number is associated with a specific URL by using the routing function route(). When the Web server receives the URL request, it will call the function associated with route () and return the function response content.

@app.route('/hello')
def hello():
    return "Hello, I'm python"

Enter in the browser http://127.0.0.1:5000/hello , the response content will appear.

(2) Routing method add_url_rule()

def hello():
    return "Hello, I'm python"
app.add_url_rule('/hello', 'hello', hello)

(3) Map different URL s to the same function

In flash web, you can use multiple different URL s to map to multiple functions at the same time. Only two decorators need to be set.

@app.route('/')
@app.route('/hello')
def hello():    # Define business processing function (Hello)
    return "This is our first one flask program"

Processing URL parameters

In a web program, the URL is not necessarily static, but may be dynamic. It is necessary to declare the variable name in the list parameter in the corresponding processing function.

from unicodedata import name
from flask import Flask
app = Flask(__name__)


@app.route('/hello/<name>')
def hello(name):
    return 'Hello %s' % name

if __name__ == '__main__':
    app.run(debug=True)

The parameter name in the URL is a variable. If you enter it in the browser

http://127.0.0.1:5000/hello/jack

Then "jack" will be passed to the hello() function as a parameter. Therefore, the running result is as follows:

In the URL of the Flask framework, in addition to the string type parameters, the following parameters can also be used:

  • int: indicates an integer parameter, such as "/ hello/1"
  • float: indicates a floating-point parameter, such as "hello/1.1"
from tkinter import N
from flask import Flask
app = Flask(__name__)


@app.route('/blog/<int:ID>')
def show_age(ID):
    return 'My age is:%d' % ID + 'year'

@app.route('/rev/<float:No>')
def show_money(No):
    return 'My height is%f' % No + 'cm'


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

After running the above code, enter the following URL in the browser:

http://127.0.0.1:5000/blog / integer parameter
http://127.0.0.1:5000/rev / floating point parameters

Deliver HTTP request

In computer applications, HTTP protocol is the basis of data communication in the Internet. Readers need to be familiar with only two HTTP methods: GET and POST. In the Flask framework, the default method is the GET method. By using the URL decorator to pass the "method type" parameter, the same URL can process two request methods at the same time.

from flask import Flask, request


html_txt = """<html>
    <body>
        <h2>If so get request</h2>
        <form method='post'>
            <input type='submit' value='Press I send post request' />
        </form>
    </body>
</html>
"""
app = Flask(__name__)
@app.route('/hello', methods=['GET', 'POST'])
def hello():
    if request.method == 'GET':
        return html_txt
    else:
        return '<h2>I've received it post request</h2>'


if __name__ == '__main__':
    app.run(debug=True)

The above procedures implement POST requests and GET requests in the same URL. In addition, the Flask framework can use URLs_ For() to specify the URL.

Method url_for() can pass two parameters:

  • endpoint: indicates the name of the function to be passed
  • **values: keyword parameters, that is, there are multiple formal parameters of key=value, corresponding to the variable part in the URL.
from flask import Flask, redirect, url_for
app = Flask(__name__)


@app.route('/admin')
def hello_admin():
    return 'Hello, administrator'

@app.route('/guest/<guest>')
def hello_guest(guest):
    return 'Hello%s,Are you a tourist' % guest

@app.route('/user/<name>')
def hello_user(name):
    if name == 'admin':
        return redirect(url_for('hello_admin'))
    else:
        return redirect(url_for('hello_guest', guest=name))


if __name__ == '__main__':
    app.run(debug=True)

In the above code, enter in the browser http://127.0.0.1:5000/user/admin , the URL will be redirected to http://127.0.0.1:5000/admin , execute the function hello_ The function of admin(); If the received parameter is not admin, the URL will be redirected to http://127.0.0.1:5000/guest/ Parameter, execute function hello_ The function of guest().

Simulate user login system

Write the form login HTML, the function is to realize the static HTML form. The name can be entered in the form. After clicking the submit button, the data in the form will be sent to the specified URL using the POST method: http://127.0.0.1:5000/login .

<!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>
    <form action="http://127.0.0.1:5000/login" method="post">
        <p>Please output naming</p>
        <p><input type="text" name="username" /></p>
        <p><input type="submit" value="Sign in"></p>
    </form>
</body>
</html>

Next, write login Py, because when the form is submitted, it will be mapped to the login() function. Because the server receives data through the POST method, you can obtain the value of the passed parameter username form through the following code.

request.form.get('username')

Server code, as follows:

from flask import Flask, redirect, request, url_for



app = Flask(__name__)
@app.route('/success/<name>')
def success(name):
    return 'welcome%s' % name + 'Log in to this system'

@app.route('/login', methods=['GET', 'POST'])
def login():
    if request.method == 'POST':
        user = request.form.get('username')
        print(user)
        return redirect(url_for('success', name=user))
    else:
        # return 'Please Login'
        user = request.form['username']
        return redirect(url_for('success', name=user))


if __name__ == '__main__':
    app.run(debug=True)

After clicking login, codings will be passed as a parameter to the parameter name after / success /.

Tags: Flask

Posted by lew14 on Sat, 16 Apr 2022 03:49:21 +0930