URL结构详解
定义
统一资源定位符
作用
用来表示互联网上的某个资源地址
语法格式为:
protocol://hostname[:port]/path[?query][#fragment]
http://tt.db.cn/mtv/showMtv?id=222&type=movie#subject
协议
协议:http通过http访问该资源。格式 http:// (明文); https通过安全的https访问该资源,格式为https:// ;file资源是本地计算机上的文件。格式:file:///
主机名
hostname: 主机名。 是指存放资源的服务器的续命系统:主机名、域名、ip
端口
端口: 默认是80
path
path:由零或多个"/"符号隔开的字符串,一般用来表示主机上的目录或文件
地址
地址。黑色标记的部分
http://tt.db.cn/mtv/showMtv?id=222&type=movie#subject 路由地址决定了服务器端如何处理这个请求
查询
查询: 用于给动态网页传递参数,可有多个参数,用&号隔开,每个参数的名和值用=。 以?开头。
http://tt.db.cn/mtv/showMtv ?id=222&type=movie#subject
fragment
fragment: 锚点
http://tt.db.cn/mtv/showMtv?id=222&type=movie #subject ,链接中这部分的字符串。用于指定网络资源中的片段。例如一个网页中有多个名词解释,可使用fragment直接定位到某一名词解释
处理URL请求
地址栏输入: http://127.0.0.1:8000/page/2003/
- django从配置文件中根据root_urlconf找到主路由文件(urls.py)
- django 加载主路由文件中的rulpatterns变量(包含很多路由的数组)
- 依次匹配urlpatterns中的path,匹配到第一个合适的终端后续匹配
- 匹配成功-调用对应的视图函数处理请求,返回响应
- 匹配失败-返回404响应
主路由-urls.py案例
注意: 需要现在
from django.contrib import admin
from django.urls import path
from . import views
urlpatterns = [
path('admin/', admin.site.urls),
path('first/', views.first_page)
]
函数视图
函数视图是用于接收一个浏览器请求(HttpRequest对象)并通过HttpResponse对象返回响应的函数。此函数可以接收浏览器请求并根据业务逻辑返回相应的响应内容给浏览器
语法:
def xxx_view(request[,其它参数…]):
return HttpResponse(html)
cat views
from django.http import HttpResponse
def first_page(request):
html = "<h1> 这是第一个页面 </h1>"
return HttpResponse(html)
路由配置-path
- path() 函数
- 导入 from django.urls import path
- 语法 path(route,views,name=None)
- 参数
route: 字符串类型,匹配的请求路径
views: 指定路径所应对的视图处理函数的名称
name:为地址起别名,在模板中地址反向解析时使用,后面讲解模板层时会重点介绍
path转换器
思考
语法:<转换器类型:自定义名>
作用:若转换器类型匹配到对应类型的数据,则将数据按照关键字传参方式传递给视图函数
例子:path(‘page/int:page’,views.xxx)
转换器类型
from django.contrib import admin
from django.urls import path
from . import views
urlpatterns = [
path('admin/', admin.site.urls),
path('first/', views.first_page),
# first/任意数字,对应处理的视图都是views.first_page
path('first/<int:num>',views.first_page)
]
from django.http import HttpResponse
def first_page(request,num): # num对应的是路由当中变量
html = "<h1> 这是第%s个页面 </h1>"%(num)
return HttpResponse(html)
浏览地址计算器
def calc_view(request, n, op, m):
result = 0
if op not in ["add", "sub", "mul"]:
return HttpResponse("输入错误")
if op == "add":
result = n+m
elif op == "sub":
result = n-m
elif op == "mul":
result = n*m
return HttpResponse("结果为:%s" %(result))
path('<int:n>/<str:op>/<int:m>', views.calc_view),
re_path(正则匹配)
re_path()函数
url的匹配过程中可以使用正则表达式进行精确匹配
语法:
re_path(reg,view,name=xxx)
正则表达式为命名分组模式(?Ppattern);匹配提取参数后用关键字传参方式传递给视图函数例子,只做两位数运算
re_path(r’^(?P\d{1,2}) / (?P\w+) / (?P\d{3,4}) $’ ,views.cal_view
from django.urls import re_path
urlpatterns = [
path('admin/', admin.site.urls),
path('first/', views.first_page),
path('first/<int:num>', views.first_page),
re_path(r'^hello/$',views.re_page)
]
def re_page(request):
html = "<h1> 这是正则页面 </h1>"
return HttpResponse(html)