博客
关于我
Django知识点之urls.py路由设置
阅读量:737 次
发布时间:2019-03-22

本文共 4135 字,大约阅读时间需要 13 分钟。

路由系统

路由系统分类

在Django中,路由系统分为两种类型:FBV(Function-Based View)和CBV(Class-Based View)。两种路由类型都支持,但有些框架只支持一种。

1.1 FBV(Function-Based View)

FBV使用函数处理请求,通常在Django 1.XX及更早版本中使用。在views.py中,你可以用函数来处理请求。

1.2 CBV(Class-Based View)

CBV使用类来处理请求,通常在Django 2.XX及更晚版本中使用。CBV需要继承django.views.generic.View类。在URLS.py中,你使用as_view()方法将类转换为可用的路由。


URLS.PY 文件路由配置

URL配置文件用于定义路由规则,包括直接调用函数或转发到子路由文件。Django支持使用正则表达式和固定字符串匹配。

示例配置

from django.conf.urls import urlfrom django.urls import include, pathurlpatterns = [    path(r'blog/', blog.views.index),    path(r'bbs/', bbs.views.index),    path(r'pathreg/', include('app.urls'))]
  • path()用于固定字符串或格式匹配。
  • include()用于包含子路由文件。

URL规则模块的匹配方式

2.1 url 函数

url()函数用于定义路由规则,可使用正则表达式或固定字符串。

url 的用法

from django.conf.urls import urlurlpatterns = [    url(r'^test/$', views.test_views.view),    url(r'^test/(?P\d+)$', views.test_views.view, name='test_url'),]

2.2 path 函数

path()函数在Django 2.1X以后替代url(),它支持固定的匹配模式(如int, str, slug等)。

path 的用法

from django.urls import pathurlpatterns = [    path(r'pathtest/', pathtest.views.index),    path(r'pathtest/
/', pathtest.views.index), path(r'pathtest/
/', pathtest.views.index),]

2.3 re_path 函数

re_path()函数用于正则表达式匹配,适用于复杂的路由规则。

re_path 的用法

from django.urls import re_pathurlpatterns = [    re_path(r'^test/(?P\d+)$', views.test_views.view),]

path 函数的匹配规则

path()函数支持以下匹配模式:

  • int:匹配正整数。
  • str:匹配字符串。
  • slug:匹配字母、数字和短划线的组合。
  • uuid:匹配UUID对象。
  • path:匹配所有字符串,包括斜杠。

示例

urlpatterns = [    path(r'pathtest/
', pathtest.views.index), path(r'pathtest/
', pathtest.views.index),]

视图处理

3.1 FBV 加载方式

FBV直接从views.py加载函数。例如:

from django.shortcuts import renderdef index(request):    return render(request, 'pathtest.html')

3.2 CBV 加载方式

CBV需要继承View类,并在URLS.py中使用as_view()方法。例如:

from django.views.generic import Viewclass CBV1(View):    def get(self, request):        return render(self.request, 'pathtest.html')

在URLS.py中:

urlpatterns = [    path(r'pathtest1/', pathtest.views.CBV1.as_view()),    path(r'pathtest2/', pathtest.views.CBV2.as_view()),]

4.1 视图参数传递

视图函数可以通过kwargs接收参数。例如:

from django.urls import pathimport pathtest.viewsurlpatterns = [    path(r'pathtest1/
', pathtest.views.CBV1.as_view(), name='pathtest1'),]

视图函数示例

class CBV1(View):    def get(self, request, url_args, *args, **kwargs):        return render(request, 'pathtest.html', {'url_args': url_args})

5.1 URL 的命名空间

使用name参数可以为路由赋予命名空间,便于模板中引用。例如:

urlpatterns = [    path(r'pathtest1/', pathtest.views.CBV1.as_view(), name='pathtest1'),]

模板中使用:

{% url 'pathtest1' %}

自定义匹配规则

6.1 定义自定义转换器

在URLS.py中定义自定义匹配规则,例如:

class NumLine:    regex = '[-0-9]+'    def to_python(self, value):        return str(value)    def to_url(self, value):        return str(value)from django.urls import register_converter, pathregister_converter('numline', NumLine, 'numline')urlpatterns = [    path(r'pathtest1/param', pathtest.views.CBV1.as_view(), name='pathtest1'),]

模板中使用

{% url 'pathtest1' '-0--' 1111 %}

路由文件的包含方式

7.1 子路由文件

使用include()函数包含子路由文件。例如:

urlpatterns = [    path(r'pathreg/', include('app.urls')),]

子路由文件中:

from django.urls import pathurlpatterns = [    path(r'index/', views.CBV1.as_view()),]

高级路由功能

8.1 自定义方法

在View类中定义多种HTTP方法。例如:

from django.views.generic import Viewclass CBV1(View):    http_method_names = ['get', 'post']    def get(self, request):        return HttpResponse('GET请求')    def post(self, request):        return HttpResponse('POST请求')

将视图注册路由时:

urlpatterns = [    path(r'pathtest1/', CBV1.as_view()),]

命名空间优化

8.1 全局命名空间

在project/urls.py中定义全局命名空间。例如:

from django.urls import include, pathurlpatterns = [    path(r'/', include('pathtest.urls'), name='pathtest'),]

8.2 应用命名空间

在pathtest/urls.py中定义应用命名空间。例如:

from django.urls import path, includeurlpatterns = [    path('', CBV1.as_view(), name='pathtest1'),    path('index/', CBV2.as_view(), name='pathtest2'),]

通过reverse()函数可快速获取URL路径。例如:

reverse('pathtest:pathtest1')

进阶路由配置

9.1 正则表达式匹配

使用re_path()定义正则表达式路由。例如:

urlpatterns = [    re_path(r'^test/(?P\d+)$', views.test_views.view),    re_path(r'^test/', views.test_views.view, name='test_url'),]

通过以上配置,你可以灵活定义路由规则,支持正则匹配、参数传递和命名空间。路由系统是Django应用的核心部分,灵活配置能帮助你快速构建高效的Web应用。

转载地址:http://ntggz.baihongyu.com/

你可能感兴趣的文章
Python-Numpy的tile函数用法
查看>>
python-open函数
查看>>
Python-Pandas-将特定函数应用于给定级别-多索引数据框架
查看>>
python-queue队列通信
查看>>
python-ros No module named PyKDL
查看>>
python-social-auth 是否需要会话
查看>>
Python再获年度编程语言,微软或成最大赢家
查看>>
python-week5
查看>>
Python写表情包搜索工具(非常详细)零基础入门到精通,收藏这一篇就够了
查看>>
Python-【1】配置
查看>>
Python-从子文件夹执行绝对导入
查看>>
Python-刷新页面,直到元素可单击
查看>>
PYTHON-唤醒+VOSK+DEEPSEEK+离线合成-实现纯离线大模型问答
查看>>
Python-在Dash回调中重用函数
查看>>
PYTHON-基本数据类型-元祖类型,字典类型,集合类型
查看>>
python-外观模式
查看>>
Python-如何使用FastAPI和uvicorn.run而不阻塞线程?
查看>>
Python-字典
查看>>
python-字符串
查看>>
Python-将二进制遮罩转换为多边形
查看>>