Python Network Programming 简明教程

Python - Routing

路由是将 URL 直接映射到创建网页的代码的机制。它有助于更好地管理网页结构,并显着提高站点的性能,并且进一步增强或修改变得非常简单。在 python 中,路由在大多数网络框架中实现。我们将在本章中查看`@ {s3}`网络框架的示例。

Routing is the mechanism of mapping the URL directly to the code that creates the webpage. It helps in better management of the structure of the webpage and increases the performance of the site considerably and further enhancements or modifications become really straight forward. In python routing is implemented in most of the web frame works. We will see the examples from flask web framework in this chapter.

Routing in Flask

Flask 中的`@ {s4}`装饰器用于将 URL 绑定到函数。因此,在浏览器中提到 URL 后,将执行函数以给出结果。此处,URL`@ {s5}`规则绑定到`@ {s6}`函数。因此,如果用户访问`@ {s7}`URL,`@ {s8}`函数的输出将在浏览器中呈现。

The route() decorator in Flask is used to bind an URL to a function. As a result when the URL is mentioned in the browser, the function is executed to give the result. Here, URL '/hello' rule is bound to the hello_world() function. As a result, if a user visits http://localhost:5000/ URL, the output of the hello_world() function will be rendered in the browser.

from flask import Flask
app = Flask(__name__)

@app.route('/')
def hello_world():
   return 'Hello Tutorialspoint'

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

当我们运行以上程序时,我们得到以下输出:

When we run the above program, we get the following output −

 * Serving Flask app "flask_route" (lazy loading)
 * Environment: production
   WARNING: Do not use the development server in a production environment.
   Use a production WSGI server instead.
 * Debug mode: off
 * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
127.0.0.1 - - [06/Aug/2018 08:48:45] "GET / HTTP/1.1" 200 -
127.0.0.1 - - [06/Aug/2018 08:48:46] "GET /favicon.ico HTTP/1.1" 404 -
127.0.0.1 - - [06/Aug/2018 08:48:46] "GET /favicon.ico HTTP/1.1" 404 -

我们打开浏览器,指向 URL http://localhost:5000/ ,查看正在执行的函数的结果。

We open the browser and point to the URL http://localhost:5000/ to see the result of the function being executed.

routing 1

Using URL Variables

我们可以通过 route 传递 URL 变量,以便动态构建 URL。为此,我们使用 url_for() 函数,它接收函数名作为第一个参数,以及 URL 规则的其余参数作为可变部分。

We can pass on URL variables using route to build URLS on the fly. For this we use the url_for() function which accepts name of the function as the first argument and the rest of the arguments as variable part of the URL rule.

在下面的示例中,我们将函数名称作为参数传递给 url_for 函数,并在执行这些行时打印出结果。

In the below example we pass the function names as arguments to the url_for function and print out the result when those lines are executed.

from flask import Flask, url_for
app = Flask(__name__)

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

@app.route('/login')
def login(): pass

@app.route('/user/')
def profile(username): pass

with app.test_request_context():
    print url_for('index')
    print url_for('index', _external=True)
    print url_for('login')
    print url_for('login', next='/')
    print url_for('profile', username='Tutorials Point')

当我们运行以上程序时,我们得到以下输出:

When we run the above program, we get the following output −

/
http://localhost/
/login
/login?next=%2F
/user/Tutorials%20Point

Redirects

我们可以使用 redirect 函数使用路由将用户重定向到其他 URL。我们将新 URL 作为函数的返回值,该函数应将用户重定向。当我们在修改现有网页时暂时将用户转到其他页面时,这很有用。

We can use the redirect function to redirect the user to another URL using routing. We mention the new URL as a return value of the function whihc should redirect the user. This is helpful when we temporarily divert the users to a different page when we are modifying an existing webpage.

from flask import Flask, abort, redirect, url_for
app = Flask(__name__)

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

@app.route('/login')
def login():
    abort(401)
#    this_is_never_executed()

当执行上面的代码时,基本 URL 将转到登录页面,该页面使用 abort 函数,因此登录页面的代码永远不会执行。

When the above code is executed, the base URL goes to login page which uses the abort function so that the code for login page is never executed.