http://www.igeekhome.com/python/1/?i=1&p=new,只匹配「/python/1/」部分
url(r'^([0-9]+)/$', views.detail, name='detail'),
url(r'^(?P<id>[0-9]+)/$', views.detail, name='detail'),
from django.conf.urls import include, url urlpatterns = [ url(r'^', include('booktest.urls', namespace='booktest')), ]
請求http://www.igeekhome.com/booktest/1/ 在urls.py中的配置: url(r'^booktest/', include('booktest.urls', namespace='booktest')), 在booktest應用urls.py中的配置 url(r'^(/[0-9]+)/$', views.detail, name='detail'), 匹配部分是:/booktest/1/ 匹配過程:在urls.py中與「booktest/」成功,再用「1/」與booktest應用的urls匹配
新建views1.py #coding:utf-8 from django.http import HttpResponse def index(request): return HttpResponse("你好") 在urls.py中修改配置 from . import views1 url(r'^$', views1.index, name='index'),
<!DOCTYPE html> <html> <head> <title></title> </head> <body> 找不到了 <hr/> {{request_path}} </body> </html>
DEBUG = False ALLOWED_HOSTS = ['*', ]
http://127.0.0.1:8000/test/
dict.get('鍵',default) 或簡寫爲 dict['鍵']
dict.getlist('鍵',default)
def getTest1(request): return render(request,'booktest/getTest1.html') def getTest2(request): return render(request,'booktest/getTest2.html') def getTest3(request): return render(request,'booktest/getTest3.html')
url(r'^getTest1/$', views.getTest1), url(r'^getTest2/$', views.getTest2), url(r'^getTest3/$', views.getTest3),
<html> <head> <title>Title</title> </head> <body> 連接1:一個鍵傳遞一個值 <a href="/getTest2/?a=1&b=2">gettest2</a><br> 連接2:一個鍵傳遞多個值 <a href="/getTest3/?a=1&a=2&b=3">gettest3</a> </body> </html>
def getTest2(request): a=request.GET['a'] b=request.GET['b'] context={'a':a,'b':b} return render(request,'booktest/getTest2.html',context)
<html> <head> <title>Title</title> </head> <body> a:{{ a }}<br> b:{{ b }} </body> </html>
def getTest3(request): a=request.GET.getlist('a') b=request.GET['b'] context={'a':a,'b':b} return render(request,'booktest/getTest3.html',context)
<html> <head> <title>Title</title> </head> <body> a:{% for item in a %} {{ item }} {% endfor %} <br> b:{{ b }} </body> </html>
def postTest1(request): return render(request,'booktest/postTest1.html')
配置urlhtml
url(r'^postTest1$',views.postTest1)
建立模板postTest1.htmlpython
<html> <head> <title>Title</title> </head> <body> <form method="post" action="/postTest2/"> 姓名:<input type="text" name="uname"/><br> 密碼:<input type="password" name="upwd"/><br> 性別:<input type="radio" name="ugender" value="1"/>男 <input type="radio" name="ugender" value="0"/>女<br> 愛好:<input type="checkbox" name="uhobby" value="胸口碎大石"/>胸口碎大石 <input type="checkbox" name="uhobby" value="跳樓"/>跳樓 <input type="checkbox" name="uhobby" value="喝酒"/>喝酒 <input type="checkbox" name="uhobby" value="登山"/>登山<br> <input type="submit" value="提交"/> </form> </body> </html>
建立視圖postTest2接收請求的數據程序員
def postTest2(request): uname=request.POST['uname'] upwd=request.POST['upwd'] ugender=request.POST['ugender'] uhobby=request.POST.getlist('uhobby') context={'uname':uname,'upwd':upwd,'ugender':ugender,'uhobby':uhobby} return render(request,'booktest/postTest2.html',context)
配置urlajax
url(r'^postTest2$',views.postTest2)
建立模板postTest2.html正則表達式
<html> <head> <title>Title</title> </head> <body> {{ uname }}<br> {{ upwd }}<br> {{ ugender }}<br> {{ uhobby }} </body> </html>
注意 : 使用表單提交,註釋掉settings.py中的中間件csrfredis
#coding=utf-8 from django.http import HttpResponse def index(request): return HttpResponse('你好')
from django.http import HttpResponse from django.template import RequestContext, loader def index(request): t1 = loader.get_template('polls/index.html') context = RequestContext(request, {'h1': 'hello'}) return HttpResponse(t1.render(context))
from django.http import HttpResponse from datetime import * def index(request): response = HttpResponse() if request.COOKIES.has_key('h1'): response.write('<h1>' + request.COOKIES['h1'] + '</h1>') response.set_cookie('h1', '你好', 120) # response.set_cookie('h1', '你好', None, datetime(2016, 10, 31)) return response
# 在views1.py中 from django.http import HttpResponse,HttpResponseRedirect from django.http import JsonResponse def index(request): # 推薦使用反向解析 # return HttpResponseRedirect(reverse('booktest:index2', args=(1,))) return HttpResponseRedirect('js/') def index2(request, api): return HttpResponse('重定向') # 返回json數據 return JsonResponse({'list': api}) # 在應用的urls.py中增長一個url對象 url(r'^js/$', views1.index2, name='index2'),
from django.shortcuts import render def index(request): return render(request, 'booktest/index.html', {'h1': 'hello'})
from django.shortcuts import redirect from django.core.urlresolvers import reverse def index(request): return redirect(reverse('booktest:index2'))
from django.shortcuts import * def detail(request, id): try: book = get_object_or_404(BookInfo, pk=id) except BookInfo.MultipleObjectsReturned: book = None return render(request, 'booktest/detail.html', {'book': book})
將settings.py中的DEBUG改成False數據庫
將請求地址輸入2和100查看效果django
from django.shortcuts import * def index(request): # list = get_list_or_404(BookInfo, pk__lt=1) list = get_list_or_404(BookInfo, pk__lt=6) return render(request, 'booktest/index.html', {'list': list}) # 將settings.py中的DEBUG改成False
啓用sessionjson
# 向INSTALLED_APPS列表中添加: 'django.contrib.sessions', # 向MIDDLEWARE_CLASSES列表中添加: 'django.contrib.sessions.middleware.SessionMiddleware',
使用sessionapi
在views.py文件中建立視圖
from django.shortcuts import render, redirect from django.core.urlresolvers import reverse def index(request): uname = request.session.get('uname') return render(request, 'booktest/index.html', {'uname': uname}) def login(request): return render(request, 'booktest/login.html') def login_handle(request): request.session['uname'] = request.POST['uname'] return redirect(reverse('booktest:index')) def logout(request): # request.session['uname'] = None # del request.session['uname'] # request.session.clear() request.session.flush() return redirect(reverse('booktest:index'))
配置url
# 主url: from django.conf.urls import include, url urlpatterns = [ url(r'^', include('booktest.urls', namespace='booktest')) ] # 應用url: from django.conf.urls import url from . import views urlpatterns = [ url(r'^$', views.index, name='index'), url(r'login/$', views.login, name='login'), url(r'login_handle/$', views.login_handle, name='login_handle'), url(r'logout/$', views.logout, name='logout') ]
建立模板index.html
<!DOCTYPE html> <html> <head> <title>首頁</title> </head> <body> 你好:{{uname}} <hr/> <a href="{%url 'booktest:login'%}">登陸</a> <hr/> <a href="{%url 'booktest:logout'%}">退出</a> </body> </html>
建立模板login.html
<!DOCTYPE html> <html> <head> <title>登陸</title> </head> <body> <form method="post" action="/login_handle/"> <input type="text" name="uname"/> <input type="submit" value="登陸"/> </form> </body> </html>
def login_handle(request): request.session['uname'] = request.POST['uname'] # request.session.set_expiry(10) # request.session.set_expiry(timedelta(days=5)) # request.session.set_expiry(0) # request.session.set_expiry(None) return redirect(reverse('booktest:index'))
# 使用存儲會話的方式,可使用settings.py的SESSION_ENGINE項指定 # 基於數據庫的會話:這是django默認的會話存儲方式,須要添加django.contrib.sessions到的INSTALLED_APPS設置中,
# 運行manage.py migrate在數據庫中安裝會話表,可顯示指定爲 SESSION_ENGINE='django.contrib.sessions.backends.db' # 基於緩存的會話:只存在本地內在中,若是丟失則不能找回,比數據庫的方式讀寫更快 SESSION_ENGINE='django.contrib.sessions.backends.cache' # 能夠將緩存和數據庫同時使用:優先從本地緩存中獲取,若是沒有則從數據庫中獲取 SESSION_ENGINE='django.contrib.sessions.backends.cached_db'
# 會話還支持文件、純cookie、Memcached、Redis等方式存儲,下面演# 示使用redis存儲 # 安裝包 pip install django-redis-sessions # 修改settings中的配置,增長以下項 SESSION_ENGINE = 'redis_sessions.session' SESSION_REDIS_HOST = 'localhost' SESSION_REDIS_PORT = 6379 SESSION_REDIS_DB = 0 SESSION_REDIS_PASSWORD = '' SESSION_REDIS_PREFIX = 'session'
redis-cli:使用客戶端鏈接服務器
keys *:查看全部的鍵
get name:獲取指定鍵的值
del name:刪除指定名稱的鍵