程序结构:
urls–蓝图urls—蓝图视图views:
有时候我们在写url匹配的时候,想要写使用正则表达式来实现一些复杂的需求,那么这时候我们可以使用re_path来实现。re_path的参数和path参数一模一样,只不过第一个参数也就是route参数可以为一个正则表达式
在写程序时需要的是,在urls程序中定义正则表达式,book中的urls内容为:
from django.urls import path,re_path
from . import views
from django.urls import converters
# converters:转换器 是int在里面定义的
urlpatterns = [
path('<int:book_id>',views.book),
# 设置int型的约束
path('book_detail/',views.book_detail),
# 正则表达式的方式设置复杂一些的url
re_path(r'current_year/(?P<year>\d{4})/(?P<month>\d{2})',views.current_year),
#re_path(r'current_mo/(?P<year>\d{4}$)',views.current_year),
# 这里的r''表示的是字符串原本的意思,()表示分组,(?P<year>\d{4})表示给分组起名字然后写匹配规则
]
在views中定义current_year
def current_year(request,year,month):
return HttpResponse('今年是%s年月份是%s' % (year,month))
此时,要访问该页面需要访问url为:
http://127.0.0.1:8000/book/current_year/2020/12
完成