首页 > 其他分享 >1002.url路由及模板渲染方式

1002.url路由及模板渲染方式

时间:2022-12-17 21:47:48浏览次数:43  
标签:views url django URL urls import path 1002 路由

一、url基本概念及格式

URL概念:

URL(Uniform Resoure Locator)统一资源定位符是对可以从互联网上得到的资源的位置和访问方法的一种简介的表示,是互联网上标准资源的地址。互联网上的每个文件都有一个唯一的URL,它包含的信息指出文件的位置以及浏览器应该怎么处理它。

URL格式:

http://127.0.0.1:8000/hello/

URL解释:

schema://host[:port#]/path/.../[?query-string][#anchor]

schema:指定使用的协议(例如:http,https,ftp)

host:Http服务器的IP地址或者域名

port:端口号,http默认是80端口

path:访问资源的路径

query-string:发送给http服务器的数据

anchor:锚点#

urls.py的作用:

URL配置(URLconf)就像是Django所支撑网站的目录。它的本质是URL模式以及要为该URL模式调用的视图函数之间的映射表。以这样的方式告诉Django,对于那个URL调用那段代码。url的加载就是从配置文件中开始。

二、path和re_path

path基本规则:

path(‘test/<xx>’, views.test)

test/<xx>  使用尖括号(<>)从url中捕获值。包含一个转化器型(converter type),没有转化器,将匹配任何字符串,当然也包括了 / 字符。

views.test 当前的url匹配成功后就会调用后面的视图函数。

默认支持的转换器:

str:匹配除了路径分隔符( / )之外的非空字符串,这是默认的形式;

int:匹配正整数,包含0;

slug:匹配字母、数字记忆横杠、下划线组成的字符串;

uuid:匹配格式化的uuid,如071194d3-6885-417e-1818-6c931e272f-00;

path:匹配任何非空字符串,包含了路径分隔符。

转换器的使用:

1. 设置url:   

from django.contrib import admin
from django.urls import path

urlpatterns = [
    path('test/<int:xx>/', views.test3),
]

2. 在视图中将获取到的参数和参数的类型打印出来:

from django.shortcuts import render
from django.http import HttpResponse

def  test3(reuqest, xx):
    print(xx, type(xx))
    return HttpResponse('Hello %s'%xx)

注: 参数名  xx 需要保持一致。

re_path正则匹配:

urls.py

from django.contrib import admin
from django.urls import path
from . import views

urlpatterns = [
    re_path('hello/$', views.test5),
    re_path('^hello/(?P<yy>[0-9]+)/', views.test6),
]

 views.py

from django.shortcuts import render
from django.http import HttpResponse

def test5(request):
    return HttpResponse('这是用的re_path设置的‘)

def test6(request, yy):
    print(yy, type(yy))
    return HttpResponse('hello %s'%yy)

include的作用:

include例子:项目目录下的注urls.py

from django.contrib import admin
from django.urls import path,include
from . import views
urlpatterns = [
    path('admin/', admin.site.urls),
    path('book/',include('book.urls')),
]

kwargs的作用:

name的作用:

 

 

 

三、模板路径配置

 

四、模板渲染方式

标签:views,url,django,URL,urls,import,path,1002,路由
From: https://www.cnblogs.com/lxinghua/p/16989568.html

相关文章