关于url的理解
一、关于url
的认识
schema://host[:port#]/path/…/[?querystring][#anchor]
- 1、
schema
指定使用的协议(例如:http
或者https
) - 2、
host
指域名或者ip地址 - 3、
port
指端口号 - 4、
path
资源路径 - 5、
querystring
发送给http
服务器的数据 - 6、
anchor
锚点
二、django
中关于url
的配置
1、在
django < 2.0
的时候配置url
的方式from django.conf.urls import url,include urlpatterns = [ url(r'^$', views.index), url(r'^blog/', include("blog.urls")), url(r'^article/', include("article.urls")), ]
2、到了
django > 2.0
后采用path
方式在
django > 2.0
的对url
做了更大的优化, 主要体现在不需要写正则来匹配开始与结束from django.contrib import admin from django.urls import path from app01 import views urlpatterns = [ path('admin/', admin.site.urls), path('ind', views.ind), path('index/', views.index) ]
3、
url
中传递数据(django < 2.0
一般我们叫正则写法)
官方提供几种传递参数的方式
Path converters
The following path converters are available by default:
- 1、str - Matches any non-empty string, excluding the path separator, '/'. This is the default if a > converter isn't included in the expression.
- 2、int - Matches zero or any positive integer. Returns an int.
- 3、slug - Matches any slug string consisting of ASCII letters or numbers, plus the hyphen and underscore characters. For example, building-your-1st-django-site.
- 4、uuid - Matches a formatted UUID. To prevent multiple URLs from mapping to the same page, dashes must be included and letters must be lowercase. For example, 075194d3-6885-417e-a8a8-6c931e272f00. Returns a UUID instance.
5、path - Matches any non-empty string, including the path separator, '/'. This allows you to match against a complete URL path rather than just a segment of a URL path as with str.
... urlpatterns = [ ... path('index/<int:id>', views.index1), path('index/<str:arg>', views.index2) ]
def index1(request, id): print(id) return HttpResponse(id) def index2(request, arg): return HttpResponse(arg)
4、给
url
配置name
值 主要有两个作用- 1、在
view
中配置重定向 - 2、在
template
中配置页面的跳转(在模板的章节会介绍)
urlpatterns = [ path('admin/', admin.site.urls), path('ind', views.ind), path('index/', views.index, name="home"), ... ]
from django.http import HttpResponse, HttpResponseRedirect from django.shortcuts import render from django.urls import reverse def index(request): return HttpResponse('我是主页') def ind(request): return HttpResponseRedirect(reverse('home'))
- 1、在
5、更多
url
的详情介绍请参考传送门