学习笔记,仅供参考
利用正则的组名进行关键字传参
在之前的BlOG中,我们在urls.py里都是用位置传参的方式,将路由里的信息传递给视图函数做参数,比如:
urls.py
urlpatterns = [
path('admin/', admin.site.urls),
re_path(r'birthday/(\d{4})/(\d{1,2})/(\d{1,2})/', views.page_birth),
]
views.py
def page_bunny(request, name, age):
html = "Bunny's name is " + name + " and its age is " + age
return HttpResponse(html)
如果我们的地址为:http://127.0.0.1:8000/birthday/1997/9/28,那么"1997"就会传入year, "9"就会传入month,"28"就会传入day,就相当于这样调用方法:
page_birth(request, "1997", "9", "28")
但是如果我们给正则表达式中的每个组起组名,就相当于是关键字传参,比如:
urls.py
urlpatterns = [
path('admin/', admin.site.urls),
re_path(r'bunny/(?P<age>\d{1,2})/(?P<name>\w+)/', views.page_bunny)
]
views.py
def page_bunny(request, name, age):
html = "Bunny's name is" + name + "and its age is" + age
return HttpResponse(html)
如果我们的地址为:http://127.0.0.1:8000/bunny/10/huang/,服务器就会响应如下页面:
此时,"10"会被传入age,"huang"会被传入name,就相当于这样调用方法:
page_bunny(request,age = "10", name = "huang")
- 注意事项