暑期实训记录:第一周(3)

本文介绍了Flask框架中使用`route()`装饰器进行URL绑定的基本原理,展示了如何创建首页和Hello, World页面。同时,详细阐述了如何在URL中添加变量以及使用不同的转换器,如``、``和``,以接收和处理不同类型的变量。这些变量作为关键字参数传递给对应的视图函数,使得路由更加灵活和实用。
摘要由CSDN通过智能技术生成

暑期实训记录:第一周(3)

路由

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

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

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

变量规则

通过把 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)}'
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值