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 get started with Python Flask

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

Share

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

This article will explain in detail how to get started with Python Flask. The content of the article is of high quality, so the editor will share it for you as a reference. I hope you will have a certain understanding of the relevant knowledge after reading this article.

Back in the beginning, Flask was born as a joke made by Armin Ronacher on April Fool's Day in 2010. Later, it gradually developed into a mature Python Web framework and became more and more popular among developers.

Flask is a typical micro-framework. As a Web framework, it retains only the core functions: request response processing and template rendering. These two kinds of functions are done by Werkzeug (WSGI tool Library) and Jinja (template rendering Library) respectively.

Home page

The URL of the home page is usually the root address, that is, /.

From flask import Flaskapp = Flask (_ _ name__) @ app.route ('/') def hello (): return 'Welcome to my web' if _ name__== "_ _ main__": app.run ()

Now open the browser and visit http://localhost:5000 to visit our program home page.

Analyze the code:

1. First, we import the Flask class from the flask package, and instantiate the class to create a program object, app:

From flask import Flaskapp = Flask (_ _ name__)

2. Next, we will register a handler, which is the handler that handles a request. Flask officially calls it a view funciton. The so-called "registration" is to put a decorator hat on this function. We use app.route () to install

The decorator binds the corresponding URL for the function. When the user accesses the URL in the browser, the function is triggered, the return value is obtained, and the return value is displayed to the browser window:

@ app.route ('/') def hello (): return 'Welcome to my web'

Tip: for ease of understanding, you can think of a Web program as a collection of view functions such as writing different functions to handle requests corresponding to URL.

The first parameter to fill in the app.route () decorator is the URL rule string, where the "/" refers to the root address. We only need to write out the relative address, host address, port number and so on. So, the "/" here corresponds to the part of the path after the host name, and the full URL is "http://localhost:5000/"." If the URL rule we define here is "/ hello", then the complete URL is "http://localhost:5000/hello"."

The whole process of the request is as follows:

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

two。 The server parses the request and finds that the URL rule that the request URL matches is /, so the corresponding place is called.

Rational function hello ()

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

4. The browser accepts the response and displays it on the window

Modify the return value of the view function

First of all, you are free to modify the return value of the view function. As the main body of the response, the return value will be parsed by the browser as HTML format by default, so we can add a HTML element tag:

@ app.route ('/') def hello (): return 'Hello Totoro!

'

After saving the changes, just refresh the page in the browser and you will see that the content on the page will change accordingly.

Modify URL rules

In addition, you are free to modify the URL rule string passed into the app.route decorator, but be careful to start with a slash /. For example:

@ app.route ("/ HelloWorld") def hello_word (): return "hello world"

Save the changes, then refresh the browser, and you will see a 404 error message indicating that the page was not found (Page Not Found). This is because the URL of the view function has been changed to "/ HelloWorld", and the address we access after refreshing is still the old "/". If we change the access address to "http://localhost:5000/home"", we will see the return value correctly.

A view function can also bind multiple URL, which is achieved by attaching multiple decorators, such as:

@ app.route ('/') @ app.route ('/ index') @ app.route ("/ HelloWorld") def hello_word (): return "hello world"

Now you can see the return value whether you visit "http://localhost:5000/","http://localhost:5000/HelloWorld"," or "http://localhost:5000/index"."

Previously, we called the parameter passed into the app.route decorator the URL rule because we can also define the variable part in the URL. For example, the following view function handles all requests like "/ user/":

App.route ('/ user/') def user_page (name): return 'User page'

This function will be triggered whether you visit "http://localhost:5000/user/Tom"" or "http://localhost:5000/user/Jerry"". We can also get the value of this variable in the view function in the following ways:

@ app.route ('/ user/') def user_page (name): return 'User:% s'% name modifies the view function name

The last part that can be modified is the name of the view function. First of all, the name of the view function is freely defined, independent of the URL rules. As with defining other functions or variables, you just need to let it express the meaning of the page you want to process.

In addition, it has an important role: as an endpoint (endpoint) representing a route, it is also used to generate URL. For URL in the program, to avoid handwriting, Flask provides a url_for function to generate URL. The first parameter it accepts is the endpoint value, which defaults to the name of the view function:

From flask import url_for Flask app = Flask (_ _ name__) @ app.route ('/') def hello (): return 'Hello' @ app.route (' / user/') def user_page (name): return 'User:% s'% name @ app.route ('/ test') def test_url_for (): print (url_for ('hello')) # output: / # Note how the following two calls are generated Becomes the print (url_for ('user_page') of the URL containing the URL variable Name='Tom')) # output: / user/Tom print (url_for ('user_page', name='Jerry')) # output: / user/Jerry print (url_for (' test_url_for')) # output: / test # the following call passes in extra keyword parameters They are appended to URL as query strings. Print (url_for ('test_url_for', number=2)) # output: / test?number=2 return' Test page' if _ _ name__== "_ _ main__": app.run ()

On how to start Python Flask to share here, I hope that the above content can be of some help to you, can learn more knowledge. If you think the article is good, you can share it for more people to see.

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

Development

Wechat

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

12
Report