Djnago——url模块
一、概况
URL是django中一个模块,是url路径到视图的一个映射,先看来来官方的解说:
## 英文版:
To design URLs for an app, you create a Python module informally called a URLconf (URL configuration). This module is pure Python code and is a mapping between URL path expressions to Python functions (your views).
This mapping can be as short or as long as needed. It can reference other mappings. And, because it’s pure Python code, it can be constructed dynamically.
Django also provides a way to translate URLs according to the active language.
## 翻译一下:
为了给一个应用设计URL,你需要创建一个Python 模块,通常被称为**URLconf**(URL configuration)。这个模块是纯粹的Python 代码,包含URL 模式(简单的正则表达式)到Python 函数(你的视图)的简单映射。
映射可短可长,随便你。它可以引用其它的映射。而且,因为它是纯粹的Python 代码,它可以动态构造。
Django 还提供根据当前语言翻译URL 的一种方法。
当然如果你创建了django项目,那么在你的主目录下的url中回有下面的说明:
"""DjangoModel URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/3.1/topics/http/urls/
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'))
"""
上面也说了,更多的信息可以访问这个网站:Django官方url解说当然必须和你的django(这里是3.1)版本相同的情况下。
二、Django如何处理一个请求
当一个用户请求Django 站点的一个页面,下面是Django 系统决定执行哪个Python 代码使用的算法:
-
Django 确定使用根 URLconf 模块。通常,这是
ROOT_URLCONF
设置的值,但如果传入HttpRequest
对象拥有urlconf
属性(通过中间件设置),它的值将被用来代替ROOT_URLCONF
设置。 -
Django 加载该 Python 模块并寻找可用的
urlpatterns
。它是django.urls.path()
和(或)django.urls.re_path()
实例的序列(sequence)。 -
Django 会按顺序遍历每个 URL 模式,然后会在所请求的URL匹配到第一个模式后停止,并与
path_info
匹配。 -
一旦有 URL 匹配成功,Djagno 导入并调用相关的视图,这个视图是一个Python 函数(或基于类的视图 class-based view )。视图会获得如下参数:
-
一个
HttpRequest
实例。 -
如果匹配的 URL 包含未命名组,那么来自正则表达式中的匹配项将作为位置参数提供。
-
关键字参数由路径表达式匹配的任何命名部分组成,并由
django.urls.path()
或django.urls.re_path()
的可选kwargs
参数中指定的任何参数覆盖。Changed in Django 3.0:
在旧版本里,带有
None
值的关键字参数也可以由未提供的命名部分组成。
-
-
如果没有 URL 被匹配,或者匹配过程中出现了异常,Django 会调用一个适当的错误处理视图。参加下面的错误处理( Error handling )。
例如:
在上篇文章中,接触了两个 URLconf,第一个在主目录中的url,第二个子啊test1app中的url:
from django.urls import include, path
urlpatterns = [
path('',