Python之路【第十九章】:Django进阶

Django路由规则

1、基于正则的URL

在templates目录下创建index.html、detail.html文件

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
{% for k,item in user_dict.items %}
<li><a target="_blank" href="/detail-{{ k }}.html">{{ item.name}}</a></li>
{% endfor %} </body>
</html>

index.html

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h2>详细信息</h2>
<h4>用户名:{{ detail_info.name }}</h4>
<h4>邮箱:{{ detail_info.email }}</h4>
</body>
</html>

detail.html

在urls.py文件增加对应路径

from django.conf.urls import url,include
from django.contrib import admin
from cmdb import views urlpatterns = [
url(r'^index', views.index),
url(r'^detail-(\d+).html/', views.detail),
]

在views.py文件创建对应方法

USER_DICT = {
'1':{'name':'root1','email':'root@live.com'},
'2':{'name':'root2','email':'root@live.com'},
'3':{'name':'root3','email':'root@live.com'},
'4':{'name':'root4','email':'root@live.com'},
} def index(request):
return render(request,"index.html",{"user_dict":USER_DICT}) def detail(request,nid):  # nid指定的是(\d+)里的内容
detail_info = USER_DICT[nid]
return render(request, "detail.html", {"detail_info": detail_info})

2、正则URL分组

在urls.py文件增加对应路径

from django.conf.urls import url,include
from django.contrib import admin
from cmdb import views urlpatterns = [
url(r'^index', views.index),
url(r'^detail-(?P<nid>\d+)-(?P<uid>\d+).html/', views.detail),
   # nid=\d+ uid=\d+
]

在views.py文件创建对应方法

def detail(request,**kwargs):
print(kwargs)
#{'nid': '4', 'uid': '3'}
nid = kwargs.get("nid")
detail_info = USER_DICT[nid]
return render(request, "detail.html", {"detail_info": detail_info})

3、request.path_info或request.path(获取当前客户端的访问路径)

在urls.py文件配置

from django.conf.urls import url,include
from django.contrib import admin
from cmdb import views urlpatterns = [
url(r'^index', views.index),
]

urls.py

在views.py文件配置

def index(request):
print(request.path_info) #获取客户端当前的访问链接
# / index
return render(request,"index.html",{"user_dict":USER_DICT})

views.py

在templates目录下的index.html

<form action="{{ request.path_info }}" method="post">
<p><input name="user" type="text" placeholder="用户名"/></p>
<p><input name="password" type="password" placeholder="密码"/></p>
<p><input type="submit" value="提交"/></p>
</form>

参考第8条

4、name(对路由关系进行命名,根据此名称生成自己想要的URL)

在views.py文件配置

def index(request,*args,**kwargs):
return render(request,"index.html")

views.py

在urls.py文件配置

from django.conf.urls import url,include
from django.contrib import admin
from cmdb import views urlpatterns = [
url(r'^asdfasdfasdf/', views.index, name='i1'), #第一种方式i1
url(r'^yug/(\d+)/(\d+)/', views.index, name='i2'), #第二种方式i2
url(r'^buy/(?P<pid>\d+)/(?P<nid>\d+)/', views.index, name='i3'), #第三种方式i3
]

在templates目录下的index.html

<body>
{#第一种方法i1 路径asdfasdfasdf/#}
{#<form action="{% url "i1" %}" method="post">#}
{#第二种方法i2 路径yug/1/2/#}
{#<form action="{% url "i2" 1 2 %}" method="post">#}
{#第三种方法i3 路径buy/1/9//#}
<form action="{% url "i3" pid=1 nid=9 %}" method="post">
<p><input name="user" type="text" placeholder="用户名"/></p>
<p><input name="password" type="password" placeholder="密码"/></p>
<p><input type="submit" value="提交"/></p>
</form>
</body>

5、路由分发(把路由分发到spp urls文件) 

主程序urls.py文件

from django.conf.urls import url,include
from django.contrib import admin urlpatterns = [
url(r'^monitor/', include('monitor.urls')), #调整到monitor目录中的urls.py文件
]

monitor下的urls.py文件

from django.conf.urls import url
from django.contrib import admin
from monitor import views
#
urlpatterns = [
url(r'^login', views.login),
]

6、默认值

在urls.py文件配置

from django.conf.urls import url
from django.contrib import admin
from cmdb import views urlpatterns = [
url(r'^index/', views.index, {'name':'root'}),
]

在views.py文件配置

def index(request,name):
print(name)
return HttpResponse('OK') #root

  

7、命名空间

主程序urls.py文件

from django.conf.urls import url,include

urlpatterns = [
url(r'^a/', include('cmdb.urls', namespace='author-polls')),
url(r'^b/', include('cmdb.urls', namespace='publisher-polls')),
]

cmdb下的urls.py文件

from django.conf.urls import url
from cmdb import views urlpatterns = [
url(r'^index/', views.detail, name='detail'),
]

在views.py文件配置  

from django.shortcuts import HttpResponse
from django.shortcuts import reverse def detail(request):
url = reverse('author-polls:detail')
print(url)
return HttpResponse('OK') # /a/index/

html模板中生成url

{% url 'author-polls:detail'  %}

8、补充生成url路径 

from . import  models
def article(request,*args,**kwargs): # 第一种方式利用path_info,访问的url
print(request.path_info)
# /article/0-0.html/ # 第二种方式用reverse,自己生成
# 需要配合urls.py文件 url(r'...',views.article ,name='article')
from django.urls import reverse
url = reverse('article',kwargs=kwargs)
print(url)
# /article/0-0.html/

  

Django类方法

1、创建class对业务进行处理

在templates目录下创建home.html文件

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<form action="/home/" method="POST">
<p>
<input type="text" name="user" placeholder="用户名"/>
</p>
<p>
<input type="password" name="pwd" placeholder="密码"/>
</p>
<p>
<input type="submit" value="提交">
</p>
</form>
</body>
</html>

home.html

在urls.py文件增加home路径

from django.conf.urls import url,include
from django.contrib import admin
from cmdb import views urlpatterns = [
# 固定语法
url(r'^home/', views.Home.as_view()),
]

在views.py文件创建类Home

from django.views import View

class Home(View):
# 先执行dispatch里面的内容
def dispatch(self,request, *args, **kwargs):
print("before")
# 调用父类中的dispatch
result = super(Home,self).dispatch(request, *args, **kwargs)
print("after")
return result # 根据反射获取用户提交方式,执行get或post方法
def get(self,request):
print(request.method)
return render(request,"home.html") def post(self,request):
print(request.method)
return render(request,"home.html")

Django请求信息

1、获取用户请求相关请求信息以及请求头

def detail(request):
print(type(request))
# < class 'django.core.handlers.wsgi.WSGIRequest'>
from django.core.handlers.wsgi import WSGIRequest
# print(request.environ)
for k,v in request.environ.items():
print(k,v)
# GATEWAY_INTERFACE
# CGI / 1.1
# LOGONSERVER \\L-PC
# REMOTE_HOST
# REQUEST_METHOD GET
# PROGRAMFILES C:\Program Files (x86)
# PROGRAMW6432 C:\Program Files
# PATH_INFO /a/index/
# TMP C:\Users\L\AppData\Local\Temp
# HOMEDRIVE C:
# COMMONPROGRAMFILES(X86) C:\Program Files (x86)\Common Files
# SCRIPT_NAME
# MOZ_PLUGIN_PATH C:\Program Files (x86)\Foxit Software\Foxit Reader\plugins\
# REMOTE_ADDR 127.0.0.1
# wsgi.errors <_io.TextIOWrapper name='<stderr>' mode='w' encoding='UTF-8'>
# HTTP_COOKIE sessionid=dlczhr2xm0tkg8uvkvk0bmvq5aj9q87n; csrftoken=cq82rWEKolufJRrO6u4Ib4VKHapMuC4nJzhLnLMDEpDeNVhjx7AtEjqZP10DbMqu
# HTTP_CONNECTION keep-alive
# wsgi.version (1, 0)
# CONTENT_TYPE text/plain
# wsgi.file_wrapper <class 'wsgiref.util.FileWrapper'>
# CONTENT_LENGTH
# WINDIR C:\Windows
# USERDOMAIN L-PC
# SERVER_PORT 8000
# SESSIONNAME Console
# QUERY_STRING
# CSRF_COOKIE cq82rWEKolufJRrO6u4Ib4VKHapMuC4nJzhLnLMDEpDeNVhjx7AtEjqZP10DbMqu
# HTTP_ACCEPT_ENCODING gzip, deflate, sdch
# PYTHONPATH C:\Users\L\PycharmProjects\Django项目\Day_21
# ERLANG_HOME C:\Program Files\erl8.1
# COMMONPROGRAMW6432 C:\Program Files\Common Files
# HTTP_UPGRADE_INSECURE_REQUESTS 1
# NUMBER_OF_PROCESSORS 4
# ASL.LOG Destination=file
# SERVER_PROTOCOL HTTP/1.1
# PROCESSOR_LEVEL 6
# USERNAME L
# PROGRAMFILES(X86) C:\Program Files (x86)
# SYSTEMROOT C:\Windows
# ALLUSERSPROFILE C:\ProgramData
# wsgi.multiprocess False
# FP_NO_HOST_CHECK NO
# HTTP_ACCEPT_LANGUAGE zh-CN,zh;q=0.8
# PROCESSOR_REVISION 4501
# SERVER_SOFTWARE WSGIServer/0.2
# OS Windows_NT
# COMSPEC C:\Windows\system32\cmd.exe
# SYSTEMDRIVE C:
# PUBLIC C:\Users\Public
# LOCALAPPDATA C:\Users\L\AppData\Local
# HOMEPATH \Users\L
# HTTP_USER_AGENT Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2454.101 Safari/537.36
# PSMODULEPATH C:\Windows\system32\WindowsPowerShell\v1.0\Modules\
# PROGRAMDATA C:\ProgramData
# wsgi.url_scheme http
# TEMP C:\Users\L\AppData\Local\Temp
# RUN_MAIN true
# PROCESSOR_IDENTIFIER Intel64 Family 6 Model 69 Stepping 1, GenuineIntel
# wsgi.multithread True
# PROCESSOR_ARCHITECTURE x86
# COMMONPROGRAMFILES C:\Program Files (x86)\Common Files
# PYCHARM_HOSTED 1
# wsgi.input <_io.BufferedReader name=832>
# DJANGO_SETTINGS_MODULE Day_21.settings
# SERVER_NAME L-PC
# COMPUTERNAME L-PC
# USERPROFILE C:\Users\L
# HTTP_HOST 127.0.0.1:8000
# HTTP_ACCEPT text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8
# PATHEXT .COM;.EXE;.BAT;.CMD;.VBS;.VBE;.JS;.JSE;.WSF;.WSH;.MSC
# PROCESSOR_ARCHITEW6432 AMD64
# PYTHONUNBUFFERED 1
# PYTHONIOENCODING UTF-8
# APPDATA C:\Users\L\AppData\Roaming
# wsgi.run_once False print(request.environ['HTTP_HOST'])
return HttpResponse('OK')

  

 

 

Django基础-》》http://www.cnblogs.com/lianzhilei/p/6137137.html

《第十九章》

上一篇:Linux入门之路


下一篇:IIS不能对网站添加默认文档(由于权限不足而无法写入配置文件)