This is the 11th day of my participation in the Gwen Challenge in November. Check out the details: The last Gwen Challenge in 2021.

Flask is a Python implemented Web microframework. It is called a microframework because Flask’s core is simple and easy to extend, and has two main dependencies, the WSGI toolset: Werkzeug and the template engine: Jinja2, Flask only retains the core functions of Web development, other functions are implemented by external extensions, such as integrated database, form authentication, file upload, various open authentication technologies, etc. Flask is becoming more and more popular with developers because it allows users to choose how to extend things.

Installation and simple Flask

This can be done using the PIP Install flask command.

Creating a sample program

After the installation is complete, let’s write a Hello Flask! Example program. Create a new Python project, create a new app.py file in the project root directory, and write the following code:

from flask import Flask

app = Flask(__name__)


@app.route('/')
def index() :
    return '

Hello Flask!

'

if __name__ == '__main__': app.run() Copy the code

Code decomposition:

  • Imported and instantiatedFlaskClass:
from flask import Flask
app = Flask(__name__)
Copy the code
  • Register route:
@app.route('/')
def index() :
    return '

Hello Flask!

'

Copy the code

App.route () decorates the index() function with the url:/ as a parameter to associate the url with the function). The index() function is triggered when the user accesses the address /. This function is called a view function.

  • Starting the Web Server
if __name__ == '__main__':
    app.run()
Copy the code

When this file is executed directly with the Python app.py command, the Web server is started through app.run().

Execute in the command line windowflask runTo start the Web server, run the following command:

FlaskThe built-in development server listens by defaultHTTP: / 127.0.0.1:5000Address. When we open the browser to access this address, the following information will be displayed:

Run () =0.0.0.0 host=0.0.0.0 port= port number

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=8080, debug=True)
Copy the code

When you start the Web server using the flask run command, you can specify the listening host and port number by specifying the following parameters: –host=0.0.0 0, –port=8888.

Note: Flask’s built-in Web server is primarily for development and debugging, and is best deployed in a production environment using Gunicorn +Nginx.

Original is not easy, if small partners feel helpful, please click a “like” and then go ~

Finally, thank my girlfriend for her tolerance, understanding and support in work and life!