Django urls.py重构及参数传递详解

yipeiwu_com5年前Python基础

1. 内部重构#

2. 外部重构#

website/blog/urls.py

website/website/urls.py

3. 两种参数处理方式 #

1. blog/index/?id=1234&name=bikmin#

#urls.py

url(r'^blog/index/$','get_id_name')

#views.py

from django.http import HttpResponse
from django.template import loader,Context

def get_id_name(request):
  html = loader.get_template("index.html")
  id = request.GET.get("id")
  name = request.GET.get("name")
  context = Context({"id":id,"name":name})
  return HttpResponse(html.render(context))

#index.html

<body>
  <li>id:{{ id }}</li>
  <li>name:{{ name }}</li>
</body>

效果如下

2. blog/index/1234/bikmin#

#urls.py

url(r'^blog/index/(\d{4})/(\w+)/$','blog.views.get_id_name')

#views.py

from django.http import HttpResponse
from django.template import loader,Context

def get_id_name(request,p1,p2):
  html = loader.get_template("index.html")
  context = Context({"id":p1,"name":p2})
  return HttpResponse(html.render(context))

#index.html

<body>
  <li>id:{{ id }}</li>
  <li>name:{{ name }}</li>
</body>

效果如下:

3.blog/index/1234/bikmin (和-2不一样的在于views.py,接收的参数名是限定的)#

#urls.py

#限定id,name参数名
url(r'blog/index/(?P<id>\d{4})/(?P<name>\w+)/$','get_id_name')

#views.py

from django.http import HttpResponse
from django.template import loader,Context

def get_id_name(request,id,name):
  html = loader.get_template("index.html")
  context = Context({"id":id,"name":name})
  return HttpResponse(html.render(context))

#index.html

<body>
  <li>id:{{ id }}</li>
  <li>name:{{ name }}</li>
</body>

效果如下

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

Python实现Mysql数据库连接池实例详解

Python实现Mysql数据库连接池实例详解

python连接Mysql数据库: Python编程中可以使用MySQLdb进行数据库的连接及诸如查询/插入/更新等操作,但是每次连接MySQL数据库请求时,都是独立的去请求访问,相当...

python使用urllib模块开发的多线程豆瓣小站mp3下载器

复制代码 代码如下:#! /usr/bin/python2.7# -- coding:utf-8 -- import os, urllib,urllib2, thread,threadi...

python实现图片文件批量重命名

python实现图片文件批量重命名

本文实例为大家分享了python实现文件批量重命名的具体代码,供大家参考,具体内容如下 代码: # -*- coding:utf-8 -*- import os class I...

Python用5行代码写一个自定义简单二维码

Python用5行代码写一个自定义简单二维码

python的优越之处就在于他可以直接调用已经封装好的包 首先,下载pillow和qrcode包  终端下键入一下命令: pip3 install pillow #pyt...

Python中利用Scipy包的SIFT方法进行图片识别的实例教程

Python中利用Scipy包的SIFT方法进行图片识别的实例教程

scipy scipy包包含致力于科学计算中常见问题的各个工具箱。它的不同子模块相应于不同的应用。像插值,积分,优化,图像处理,,特殊函数等等。 scipy可以与其它标准科学计算程序库进...