Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to use the Python flask framework

2025-01-17 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

Shulou(Shulou.com)06/01 Report--

This article introduces the knowledge of "how to use the Python flask framework". In the operation of actual cases, many people will encounter such a dilemma, so let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!

Run flask

Flask has a built-in CLI (Command Line Interface, command line interface) system through the dependency package Click. When we install Flask, we automatically add a flask command script, through which we can execute built-in commands, extended commands, or commands we define ourselves. Where the flask run command is used to start the built-in development server:

(helloflask) $flask run * Environment: production WARNING: This is a development server. Do not use it in a production deployment. Use a production WSGI server instead. * Debug mode: off * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)

Make sure that the virtual environment (pipenv shell) is activated before executing the command, otherwise you need to start the development server using the pipenv run flask run command. There will be no more prompts later.

By default, the development server running the flask run command listens to the http://127.0.0.1:5000/ address (press Crtl+C to exit) and enables multithreaded persistence. When we open a browser to visit this address, we will see "Hello,flask!" on the website page.

Localhost and 127.0.0.1

Http://127.0.0.1, or localhost, is the IP address that points to the local machine and is generally used for testing.

Flask uses port 5000 by default, and the above address allows you to use http://localhost:5000/.

Except for the difference in address, there is no actual difference between the two, that is, the mapping relationship between domain name and IP address.

The most popular Flask program from flask import Flask # ⑴ app = Flask (_ _ name__) # ⑵ @ app.route ('/') # ⑶ def index (): # ⑷ return 'Hello flask!' # ⑸ if _ _ name__ = ='_ _ main__': app.run () # ⑹

Once the service is started, it can be accessed in the browser. The whole process of the request is as follows:

When the user accesses this address in the browser address bar, it is called http://127.0.0.1:5000/ here

The server parses the request and finds that the URL rule that the request URL matches is /, so the corresponding processing function hello () is called.

Get the return value of the hello () function and return it to the client (browser) after processing

The browser accepts the response and displays it on the window

Code logic

⑴ first we import the Flask class from the flask package

From flask import Flask # ⑴

⑵ creates a program object app by instantiating this class:

App = Flask (_ _ name__) # ⑵

⑶ uses the app.route () decorator to bind the function to the corresponding URL, and when the user accesses the URL in the browser, it triggers the function, gets the return value, and displays the return value to the browser window.

⑷ decorator registered handler, this function is to handle a request handler, Flask officially calls it the view function (view funciton)! You can understand it as a request handler.

⑸ returns the response content

# the first parameter to fill in the app.route () decorator is the URL rule string, where / refers to the root address. @ app.route ('/') # ⑶ def index (): # ⑷ return 'Hello flask!' # ⑸

The run method of the ⑹ Flask application instance starts the WEB server

If _ _ name__ = ='_ _ main__': app.run () # ⑹ more startup options

Make the server visible externally

The Web server we started above is invisible by default. You can add the-- host option after the run command to set the host address to 0.0.0.0 to make it visible:

$flask run-host=0.0.0.0

This allows the server to listen for all external requests. Personal computers (hosts) generally do not have a public IP (public address), so your program can only be accessed by other users in the local domain through your personal computer's internal IP (private address). For example, your internal IP is 192.168.191.1. When other users in the authority domain visit http://192.168.191.1:5000, they will also see the line "Hello,Flask!" displayed in the browser. .

Change the default port

The Web server provided by Flask listens to port 5000 by default. You can change it by passing parameters during startup:

$flask run-port=8000

At this point, the server listens for requests from port 8000, and the home page address of the program becomes http://localhost:8000/ accordingly.

Save parameters to a file

The host and port options when executing the flask run command can also be set through the environment variables FLASK_RUN_HOST and FLASK_RUN_PORT. In fact, Flask built-in commands can use this mode to define the default option value, namely "FLASK__"

If you don't want to specify it every time, you can save the content to a .flaskenv or .env file in the current directory (you need to install python-dotenv).

# some flask built-in commands # need to install python-dotenv FLASK_ENV=development in advance # set the current development mode FLASK_RUN_PORT = 5050 # set the port to run FLASK_RUN_HOST = 0.0.0.0 # set the listening ip

You can also use the flask-- help command to view all available commands.

Set up the running environment

Development environment (development enviroment) and production environment (production enviroment) are concepts that we will come across frequently later. The development environment refers to the computer environment when we write and test programs locally, while the production environment, as opposed to the development environment, refers to the server environment when the platform is deployed online for users to access.

Depending on the running environment, Flask programs, extensions, and other programs change their behavior and settings. To distinguish between the running environment of the program, Flask provides a FLASK_ENV environment variable to set the environment, which defaults to production (production). At the time of development, we can set it to development, which turns on all the features of persistent development. For ease of management, we will write the value of the environment variable FLASK_ENV to the .flaskenv file:

FLASK_ENV=development

Now start the program and you will see the following output prompt:

(helloflask) $flask run * Environment: development * Debug mode: on * Restarting with stat * Debugger is active! * Debugger PIN: 161,372,375 * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit) Python Shell

There are many operations that need to be performed in Python Shell (that is, the Python interactive interpreter). When developing Flask programs, instead of using the python command to start Python Shell directly, we use the flask shell command:

(helloflask) $flask shellPython 3.6.5 | Anaconda, Inc. | (default, Mar 29 2018, 13:32:41) [MSC v.1900 64 bit (AMD64)] on win32App: app [development] Instance: C:\ Users\ Administrator\ Desktop\ helloflask\ instance > >

As with other flask commands, we need to make sure that the program instance can be found properly before executing this command.

If the prompt before the code paragraph is three greater than signs, that is, ">", then the code needs to be executed in the Python Shell opened with the flask shell command.

The Python Shell opened with the flask shell command automatically contains the program context and has been imported into the app instance:

> > app > app.name'app' >

Context (context) can be understood as environment. In order to run the program properly, some operation-related states and data need to be temporarily saved, which are collectively referred to as contexts. In Flask, there are two kinds of contexts, namely, program context and request context.

This is the end of "how to use the Python flask Framework". Thank you for reading. If you want to know more about the industry, you can follow the website, the editor will output more high-quality practical articles for you!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Internet Technology

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report