天天看点

Flask 学习-2.url访问地址(路由配置)

前言

通过url 地址可以访问一个网页,Flask 框架使用 route() 装饰器来把函数绑定到 URL。

路由

使用 route() 装饰器来把函数绑定到 URL。

from flask import Flask

app = Flask(__name__)


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


@app.route('/hello')
def hello():
    return 'Hello, World'


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

除了上面的写死的路径,url 还可以用变量

url 使用变量

url 使用变量能接受的类型

  • string (缺省值) 接受任何不包含斜杠的文本
  • int 接受正整数
  • float 接受正浮点数
  • path 类似 string ,但可以包含斜杠
  • uuid 接受 UUID 字符串

通过把 URL 的一部分标记为 <variable_name> 就可以在 URL 中添加变量。

标记的 部分会作为关键字参数传递给函数。通过使用 converter:variable_name

from markupsafe import escape

@app.route('/user/<username>')
def show_user_profile(username):
    # show the user profile for that user
    return f'User {escape(username)}'

@app.route('/post/<int:post_id>')
def show_post(post_id):
    # show the post with the given id, the id is an integer
    return f'Post {post_id}'

@app.route('/path/<path:subpath>')
def show_subpath(subpath):
    # show the subpath after /path/
    return f'Subpath {escape(subpath)}'      

唯一的URL / 重定向行为

以下两条规则的不同之处在于是否使用尾部的斜杠。

@app.route('/projects/')
def projects():
    return 'The project page'

@app.route('/about')
def about():
    return 'The about page'      

projects 的 URL 是中规中矩的,尾部有一个斜杠,看起来就如同一个文件夹。

访问一个没有斜杠结尾的 URL ( /projects )时 Flask 会自动进行重 定向,帮您在尾部加上一个斜杠( /projects/ )。

about 的 URL 没有尾部斜杠,因此其行为表现与一个文件类似。如果访问这 个 URL 时添加了尾部斜杠(​​

​/about/​

​​ )就会得到一个 404 “未找到” 错 误。

这样可以保持 URL 唯一,并有助于搜索引擎重复索引同一页面。

url_for() 函数

url_for() 函数用于构建指定函数的 URL。它把函数名称作为第一个 参数。它可以接受任意个关键字参数,每个关键字参数对应 URL 中的变量。未知变量 将添加到 URL 中作为查询参数。

为什么不在把 URL 写死在模板中,而要使用反转函数 url_for() 动态构建?

  • 反转通常比硬编码 URL 的描述性更好。
  • 您可以只在一个地方改变 URL ,而不用到处乱找。
  • URL 创建会为您处理特殊字符的转义,比较直观。
  • 生产的路径总是绝对路径,可以避免相对路径产生副作用。
  • 如果您的应用是放在 URL 根路径之外的地方(如在 /myapplication 中,不在 / 中), url_for() 会为您妥善处理。

例如,这里我们使用 test_request_context() 方法来尝试使用 url_for() 。

test_request_context() 告诉 Flask 正在处理一个请求,而实际上也许我们正处在交互 Python shell 之中, 并没有真正的请求。

from flask import url_for

app = Flask(__name__)

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

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

@app.route('/user/<username>')
def profile(username):
    return f'{username}\'s profile'

with app.test_request_context():
    print(url_for('index'))
    print(url_for('login'))
    print(url_for('login', next='/'))
    print(url_for('profile', username='John Doe'))      
/
/login
/login?next=/
/user/John%20Doe