(一)always start from hello world
排坑:
1.Django2.0 有新的 url 配置格式。
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.urls import include, path
2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))
2.动态url的参数配置
基本规则:
- 使用尖括号(<>)从url中捕获值。
- 捕获值中可以包含一个转化器类型(converter type),比如使用 <int:name> 捕获一个整数变量。若果没有转化器,将匹配任何字符串,当然也包括了 / 字符。
- 无需添加前导斜杠。
- 转换器可以自定义
- 可以使用正则
注册自定义转化器
对于一些复杂或者复用的需要,可以定义自己的转化器。转化器是一个类或接口,它的要求有三点:
- regex 类属性,字符串类型
- to_python(self, value) 方法,value是由类属性 regex 所匹配到的字符串,返回具体的Python变量值,以供Django传递到对应的视图函数中。
- to_url(self, value) 方法,和 to_python 相反,value是一个具体的Python变量值,返回其字符串,通常用于url反向引用。
使用正则表达式
如果上述的paths和converters还是无法满足需求,也可以使用正则表达式,这时应当使用 django.urls.re_path 函数。
在Python正则表达式中,命名式分组语法为 (?P<name>pattern) ,其中name为名称, pattern为待匹配的模式。
#urls.py
from django.urls import path,re_path from django.urls import register_converter from mch_test import views from . import converters register_converter(converters.TowIntConverter,'yy') #urlpatterns = [ # path('admin/', admin.site.urls), #] urlpatterns = [ path('hello/',views.hello), path('time/',views.current_datetime), #第一种写法 #<int:offset> 这里的offset是所调用的方法的参数名,int是参数类型,这里hours_ahead的offset就可以不用强制类型转换了 #path(r'time/plus/<int:offset>/',views.hours_ahead,name='time_plus'), #第二种写法 #re_path支持正则表达式,offset获得的会是string,所以需要强制类型转换 #re_path('time/plus/(?P<offset>\d{1,2})',views.hours_ahead), #第三种写法 #自己注册的方法类型,在方法类型里限制了输入 path('time/plus/<yy:offset>/',views.hours_ahead), ]
#views.py from django.shortcuts import render from django.http import HttpResponse,Http404 import datetime # Create your views here. def hello(request): return HttpResponse("Hello world,i start from here.") def current_datetime(request): now = datetime.datetime.now() html = "<html><body>It is now %s.</body></html>" % now return HttpResponse(html) def hours_ahead(request, offset): try: offset = int(offset) except ValueError: raise Http404() dt = datetime.datetime.now() + datetime.timedelta(hours=offset) html = "<html><body>In %s hour(s), it will be %s.</body></html>" % (offset, dt) return HttpResponse(html)
#converters.py class TowIntConverter: regex = '\d{1,2}' def to_python(self,value): return value def to_url(self,value): return value
浙公网安备 33010602011771号