Flash framework of python (2)

Find bug's master 2022-05-14 13:49:21 阅读数:213

flashframeworkpython

Our last article has demonstrated a very simple example to you , You may be confused , I don't know how it works . Maybe you can come down , But it's not clear how it works , Then this article is for you Explain the principle to help you understand , Also add some new content . Let's look at the code we wrote last time


from flask import Flask
# Instantiation Flask, The parameter is this document
app = Flask(__name__)
# Decorator , Like a decorative hat , Direct call function , The specific process can be seen in the source function
@app.route("/")
def hello():
return "hello world"
if __name__ == '__main__':
# Run the server
app.run(debug=True)

The specific explanation is as follows :

1、 First we import  Flask  class . Examples of this class will become our WSGI application . Specific about WSGI You can take a look at this website :wsgi_ Baidu Encyclopedia

2、 Then we create an instance of this class . The first parameter is the name of the application module or package . If you use The first mock exam ( Like this example ), Then you should use  __name__ , Because the name will be based on this Whether a module is used as an application or imported as a module changes ( May be ‘__main__’ , It could also be the name of the actual import ). This parameter is required , such Flask To know where to Find templates, static files, etc .

3、 And then we use  route()  Decorator to tell Flask Trigger function URL .

4、 Function names are used to generate associated URL . The function finally returns the information that needs to be displayed in the user's browser .

So let's see that the content displayed on the web page is the routing function , Here is a detailed description of routing

modern web Applications use meaningful URL , This helps users remember , Web pages will be more favored by users , Improve the return rate .

Use  route()  Decorator to bind functions to URL, You can add such a similar code to the above code

@app.route('/hello')
def welcome():
return 'welcome! thank you!'

And then run , Type in the browser :http://127.0.0.1:5000/hello, You will find the following . I'm sure you're right URL And routing are basically clear ,

Of course, these are static URL part , For some dynamic URL How to operate , Next, we introduce a variable rule : Through the URL Part of the is marked as  <variable_name>  You can go to URL Add variables to . Of the tag Part will be passed to the function as a keyword parameter . By using  <converter:variable_name> , Sure Selectively add a converter , Specify rules for variables . Please see the following example :

@app.route('/user/<username>')
def show_user_profile(username):
return 'User %s' % escape(username)
@app.route('/post/<int:post_id>')
def show_post(post_id):
return 'Post %d' % post_id
@app.route('/path/<path:subpath>')
def show_subpath(subpath):
return 'Subpath %s' % escape(subpath)

Converter type :

string( The default value ) Accept any text without slashes
int Accept positive integers
float Accept a positive floating point number
path similar  string , But it can contain slashes
uuid Accept UUID character string

Add the above example to the code we wrote , Then add import at the top

from html import escape

And then run , Enter... In the browser :http://127.0.0.1:5000/user/xiaoli, The following will appear

Enter... In the browser :http://127.0.0.1:5000/post/1, The following will appear

So if you enter :http://127.0.0.1:5000/post/xiaoli What will happen , You can try it , There will be not found, This is because the accepted type is int type , So other types cannot access

Next, enter... In the browser :http://127.0.0.1:5000/path/a/a, You'll see the following ,path Can be followed by a slash

Next, let's talk about a rule : Unique URL / Redirection behavior , First look at the following code

@app.route('/zhou/')
def projects():
return 'Mr zhou'
@app.route('/hong')
def about():
return 'Mr hong'

zhou Of URL It's regular , There's a slash at the end , It looks like a folder . Visit a... That doesn't end with a slash URL when Flask It will automatically redirect , Add a slash at the end for you .

hong  Of URL No trailing slashes , So it behaves like a file . If you visit this URL When you add a trailing slash, you get a 404 error . This will keep URL only , And to help Search engines avoid indexing the same page repeatedly .

Let's move on URL The construction of , Use url_for()  function ,url_for() The function takes the name of the function as the first argument , And one or more keyword parameters , Each parameter corresponds to URL The variable part of . Here's an example , First, import it url_for and redirect

from flask import Flask, redirect, url_for

Then add the following code on the basis of the previous , Then start

@app.route('/xiao')
def hello_xiao():
return 'Hello xiao'
@app.route('/li/<li>')
def hello_li(li):
return 'Hello %s as li' % li
@app.route('/cus/<name>')
def hello_user(name):
if name == 'xiao':
return redirect(url_for('hello_xiao'))
else:
return redirect(url_for('hello_li', li=name))

After starting , Enter the following two on the browser URL Take a look at the effect

Enter it first :http://127.0.0.1:5000/cus/xiao

Enter again :http://127.0.0.1:5000/cus/xia

At the same time, we will also find in the address bar URL Redirected , This is url_for()  Function function

Okay , This is the end of the article , More content is waiting for the next update

版权声明:本文为[Find bug's master]所创,转载请带上原文链接,感谢。 https://pythonmana.com/2022/134/202205141334069056.html