Django 14天从小白到进阶- Day2 搞定url组件

本节内容

  • 路由系统
  • models模型
  • admin 
  • views视图
  • template模板

路由系统

我们已知,用户从浏览器发出的请求会首先打到django url的路由分发系统这里,然后再到views视图--》models模型--》template模板--》用户浏览器。

换言之,urls.py 文件主载着你整个网站的所有页面&接口的url分配。 

正式开讲django的路由语法前,先要知道路由分为以下两种:

静态路由:已经明确定义好的一条路由,比如下例,用户只能在浏览器上输入/articles/2003/ 才能匹配到这条路由,输入任何其它的都匹配不上本条。

Highlighter">
rush:python;gutter:true;">urlpatterns = [
    path('articles/2003/',views.special_case_2003),]

动态路由:定义的只是路由规则,比如只能输入数字、或特定排列、长度的字符等,你不知道用户会具体输入什么,只要符合你的规则即可。比如通过博客园每发篇文章,就会为这篇文章产生一个新的url,这个url肯定不可能是后台程序员手动给你填加的,那他得累死。肯定是他写好规则,比如8662706就代表这个文章编号,这个编号可能是数据库中此文章的id,这个不管,程序员在定义路由时,只需规定,后面用户输入的url必须是数字就行。

Django urls.py 配置

Django 的路由本质上是通过正则表达式来对用户请求的url进行匹配 

Highlighter">
rush:python;gutter:true;">from django.urls import re_path

from app01 import views

urlpatterns = [
re_path(r'articles/2003/$',# 静态路由
re_path(r'^articles/(?P[0-9]{4})/$',views.year_archive),# 动态路由
re_path(r'^articles/(?P[0-9]{4})/(?P[0-9]{2})/$',views.month_archive),# 动态路由
re_path(r'^articles/(?P[0-9]{4})/(?P[0-9]{2})/(?P[\w-]+)/$',views.article_detail),# 动态路由
]  

 

以上路由对应views.py视图方法

Highlighter">
rush:python;gutter:true;">def special_case_2003(request):
return HttpResponse("<a href="https://www.jb51.cc/tag/dddd/" target="_blank" class="keywords">dddd</a>")

def year_archive(request,year):
return HttpResponse("year_archive" + str(year))

def month_archive(request,year,month):
return HttpResponse("month_archive %s-%s" %(year,month))

def article_detail(request,month,slug):
return HttpResponse("article_detail %s-%s %s" %(year,slug))

 

虽然实现了路由匹配,但url中的代码看着很笨拙+丑陋,不过在黑暗的django 1.0时代,大家只能这么玩。不过解放之神django2.0来啦,带来了路由匹配新玩法。

Highlighter">
rush:python;gutter:true;">from django.urls import path

from . import views

urlpatterns = [
path('articles/2003/',path('articles//',path('articles///',path('articles////',]

先说,实现的功能跟之前用re写的路由一样,但是直观来看,是不是干净了很多?

下面解释语法,我太懒,直接把官网解释copy来啦,

Notes:

    To capture a value from the URL,use angle brackets.
  • Captured values can optionally include a converter type. For example,use teral notranslate"> to capture an integer parameter. If a converter isn’t included,any string,excluding a teral notranslate">/ character,is matched.
  • There’s no need to add a leading slash,because every URL has that. For example,it’s teral notranslate">articles,not teral notranslate">/articles.

Example requests:

    A request to teral notranslate">/articles/2005/03/ would match the third entry in the list. Django would call the functionteral notranslate">.
  • teral notranslate">/articles/2003/ would match the first pattern in the list,not the second one,because the patterns are tested in order,and the first one is the first test to pass. Feel free to exploit the ordering to insert special cases like this. Here,Django would call the functionteral notranslate">views.special_case_2003(request)
  • teral notranslate">/articles/2003 would not match any of these patterns,because each pattern requires that the URL end with a slash.
  • teral notranslate">/articles/2003/03/building-a-django-site/ would match the final pattern. Django would call the functionteral notranslate">.

Path converters

The following path converters are available by default:

    teral notranslate">str - Matches any non-empty string,excluding the path separator, teral notranslate">'/'. This is the default if a converter isn’t included in the expression.
  • teral notranslate">int - Matches zero or any positive integer. Returns an int.
  • teral notranslate">slug - Matches any slug string consisting of ASCII letters or numbers,plus the hyphen and underscore characters. For example,teral notranslate">building-your-1st-django-site.
  • teral notranslate">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, teral notranslate">075194d3-6885-417e-a8a8-6c931e272f00. Returns a  instance.
  • teral notranslate">path - Matches any non-empty string,including the path separator, teral notranslate">'/'. This allows you to match against a complete URL path rather than just a segment of a URL path as with teral notranslate">str.

上面这些自带的converter已经可以满足你大部分的url匹配需求,但有特殊情况不能满足时,你还可以自定义converter哈。

自定义Path Converter

A converter is a class that includes the following:

    teral notranslate">regex class attribute,as a string.  
  • teral notranslate"> method,which handles converting the matched string into the type that should be passed to the view function. It should raise teral notranslate">ValueError if it can’t convert the given value.
  • teral notranslate">

For example:

Highlighter">
rush:python;gutter:true;">class FourDigitYearConverter:
    regex = '[0-9]{4}'
def to_python(self,value):
    return int(value)

def to_url(self,value):
    return '%04d' % value</pre>

  

通过上面的regex参数来看, 其实django 2.0 这个path converter本质上也只是通过对正则表达式进行了封装,使其调用更简单而已。

Register custom converter classes in your URLconf using :

Highlighter">
rush:python;gutter:true;">from django.urls import register_converter,path

from . import converters,views

register_converter(converters.FourDigitYearConverter,'yyyy')

urlpatterns = [
path('articles/2003/',path('articles//',...
]

  

include 子url 

Highlighter">
rush:python;gutter:true;">from django.urls import include,path

urlpatterns = [

... snip ...

path('com<a href="https://www.jb51.cc/tag/munit/" target="_blank" class="keywords">munit</a>y/',include('aggregator.urls')),path('contact/',include('contact.urls')),# ... snip ...

]

  

django 在匹配url时,只要遇到include()语法, 就会把url分成2部分,比如上面代码里的url,只要匹配上community/,就会把整条url丢给include('aggregator.urls')子urls.py。 子urls.py负责匹配后面的部分。

减少重复的url

如果url 中出向很多重复的部分,可以按下面的方法聚合

django.urls <span style="color: #0000ff;">from apps.main <span style="color: #0000ff;">import<span style="color: #000000;"> views as main_views
<span style="color: #0000ff;">from credit <span style="color: #0000ff;">import<span style="color: #000000;"> views as credit_views

extra_patterns =<span style="color: #000000;"> [
path(<span style="color: #800000;">'<span style="color: #800000;">reports/<span style="color: #800000;">'<span style="color: #000000;">,credit_views.report),path(<span style="color: #800000;">'<span style="color: #800000;">reports//<span style="color: #800000;">'<span style="color: #000000;">,path(<span style="color: #800000;">'<span style="color: #800000;">charge/<span style="color: #800000;">'<span style="color: #000000;">,credit_views.charge),]

urlpatterns =<span style="color: #000000;"> [
path(<span style="color: #800000;">''<span style="color: #000000;">,main_views.homepage),path(<span style="color: #800000;">'<span style="color: #800000;">help/<span style="color: #800000;">',include(<span style="color: #800000;">'<span style="color: #800000;">apps.help.urls<span style="color: #800000;">'<span style="color: #000000;">)),path(<span style="color: #800000;">'<span style="color: #800000;">credit/<span style="color: #800000;">'<span style="color: #000000;">,include(extra_patterns)),]

in this example,the teral notranslate"> URL will be handled by the teral notranslate"> Django view.

传递额外参数给views

URLconfs have a hook that lets you pass extra arguments to your view functions,as a Python dictionary.

The  function can take an optional third argument which should be a dictionary of extra keyword arguments to pass to the view function.

For example:

Highlighter">
rush:python;gutter:true;">from django.urls import path
from . import views

urlpatterns = [
path('blog//',views.year_archive,{'foo': 'bar'}),]

In this example,for a request to teral notranslate">/blog/2005/,Django will call teral notranslate">.

*注:这个功能很少用,知道就行了。 

到此,我们就掌握了django url系统的大部分用法,是不是很简单?

Now,it's time to move forward。

  

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


我最近重新拾起了计算机视觉,借助Python的opencv还有face_recognition库写了个简单的图像识别demo,额外定制了一些内容,原本想打包成exe然后发给朋友,不过在这当中遇到了许多小问题,都解决了,记录一下踩过的坑。 1、Pyinstaller打包过程当中出现warning,跟d
说到Pooling,相信学习过CNN的朋友们都不会感到陌生。Pooling在中文当中的意思是“池化”,在神经网络当中非常常见,通常用的比较多的一种是Max Pooling,具体操作如下图: 结合图像理解,相信你也会大概明白其中的本意。不过Pooling并不是只可以选取2x2的窗口大小,即便是3x3,
记得大一学Python的时候,有一个题目是判断一个数是否是复数。当时觉得比较复杂不好写,就琢磨了一个偷懒的好办法,用异常处理的手段便可以大大程度帮助你简短代码(偷懒)。以下是判断整数和复数的两段小代码: 相信看到这里,你也有所顿悟,能拓展出更多有意思的方法~
文章目录 3 直方图Histogramplot1. 基本直方图的绘制 Basic histogram2. 数据分布与密度信息显示 Control rug and density on seaborn histogram3. 带箱形图的直方图 Histogram with a boxplot on t
文章目录 5 小提琴图Violinplot1. 基础小提琴图绘制 Basic violinplot2. 小提琴图样式自定义 Custom seaborn violinplot3. 小提琴图颜色自定义 Control color of seaborn violinplot4. 分组小提琴图 Group
文章目录 4 核密度图Densityplot1. 基础核密度图绘制 Basic density plot2. 核密度图的区间控制 Control bandwidth of density plot3. 多个变量的核密度图绘制 Density plot of several variables4. 边
首先 import tensorflow as tf tf.argmax(tenso,n)函数会返回tensor中参数指定的维度中的最大值的索引或者向量。当tensor为矩阵返回向量,tensor为向量返回索引号。其中n表示具体参数的维度。 以实际例子为说明: import tensorflow a
seaborn学习笔记章节 seaborn是一个基于matplotlib的Python数据可视化库。seaborn是matplotlib的高级封装,可以绘制有吸引力且信息丰富的统计图形。相对于matplotlib,seaborn语法更简洁,两者关系类似于numpy和pandas之间的关系,seabo
Python ConfigParser教程显示了如何使用ConfigParser在Python中使用配置文件。 文章目录 1 介绍1.1 Python ConfigParser读取文件1.2 Python ConfigParser中的节1.3 Python ConfigParser从字符串中读取数据
1. 处理Excel 电子表格笔记(第12章)(代码下载) 本文主要介绍openpyxl 的2.5.12版处理excel电子表格,原书是2.1.4 版,OpenPyXL 团队会经常发布新版本。不过不用担心,新版本应该在相当长的时间内向后兼容。如果你有新版本,想看看它提供了什么新功能,可以查看Open
1. 发送电子邮件和短信笔记(第16章)(代码下载) 1.1 发送电子邮件 简单邮件传输协议(SMTP)是用于发送电子邮件的协议。SMTP 规定电子邮件应该如何格式化、加密、在邮件服务器之间传递,以及在你点击发送后,计算机要处理的所有其他细节。。但是,你并不需要知道这些技术细节,因为Python 的
文章目录 12 绘图实例(4) Drawing example(4)1. Scatterplot with varying point sizes and hues(relplot)2. Scatterplot with categorical variables(swarmplot)3. Scat
文章目录 10 绘图实例(2) Drawing example(2)1. Grouped violinplots with split violins(violinplot)2. Annotated heatmaps(heatmap)3. Hexbin plot with marginal dist
文章目录 9 绘图实例(1) Drawing example(1)1. Anscombe’s quartet(lmplot)2. Color palette choices(barplot)3. Different cubehelix palettes(kdeplot)4. Distribution
Python装饰器教程展示了如何在Python中使用装饰器基本功能。 文章目录 1 使用教程1.1 Python装饰器简单示例1.2 带@符号的Python装饰器1.3 用参数修饰函数1.4 Python装饰器修改数据1.5 Python多层装饰器1.6 Python装饰器计时示例 2 参考 1 使
1. 用GUI 自动化控制键盘和鼠标第18章 (代码下载) pyautogui模块可以向Windows、OS X 和Linux 发送虚拟按键和鼠标点击。根据使用的操作系统,在安装pyautogui之前,可能需要安装一些其他模块。 Windows: 不需要安装其他模块。OS X: sudo pip3
文章目录 生成文件目录结构多图合并找出文件夹中相似图像 生成文件目录结构 生成文件夹或文件的目录结构,并保存结果。可选是否滤除目录,特定文件以及可以设定最大查找文件结构深度。效果如下: root:[z:/] |--a.py |--image | |--cat1.jpg | |--cat2.jpg |
文章目录 VENN DIAGRAM(维恩图)1. 具有2个分组的基本的维恩图 Venn diagram with 2 groups2. 具有3个组的基本维恩图 Venn diagram with 3 groups3. 自定义维恩图 Custom Venn diagram4. 精致的维恩图 Elabo
mxnet60分钟入门Gluon教程代码下载,适合做过深度学习的人使用。入门教程地址: https://beta.mxnet.io/guide/getting-started/crash-course/index.html mxnet安装方法:pip install mxnet 1 在mxnet中使
文章目录 1 安装2 快速入门2.1 基本用法2.2 输出图像格式2.3 图像style设置2.4 属性2.5 子图和聚类 3 实例4 如何进一步使用python graphviz Graphviz是一款能够自动排版的流程图绘图软件。python graphviz则是graphviz的python实