Django——路由系统,视图(接收文件等)
Django请求生命周期
-> URL对应关系(匹配) -> 视图函数 -> 返回用户字符串
-> URL对应关系(匹配) -> 视图函数 -> 打开一个HTML文件,读取内容(其实也是字符串)
路由系统(URL)
1、FBV形式(参见上一篇博客)、CBV形式
url(r'^index/', views.index), #FBV形式,function base view url(r'^home/', views.Home.as_view()), #CBV形式,class base view
views.py
Django.view.View里的
urls.py
1 urls.py 2 3 from app01 import views 4 urlpatterns = [ 5 url(r'^admin/', admin.site.urls), 6 url(r'^home', views.Home.as_view()), 7 ] 8 9 10 views.py 11 12 from django.shortcuts import render 13 from django.views import View 14 class Home(View): 15 def dispatch(self, request, *args, **kwargs): 16 print("start") #可以在这里面做一些操作 17 result = super(Home,self).dispatch(request, *args, **kwargs) 18 print("end") 19 return result 20 21 def get(self,request): 22 print(request.method) 23 return render(request,"login.html") 24 def post(self,request): 25 print(request.method) 26 return render(request, "login.html") 27 28 29 login.html 30 31 <!DOCTYPE html> 32 <html lang="en"> 33 <head> 34 <meta charset="UTF-8"> 35 <title>Title</title> 36 </head> 37 <body> 38 <form action="/home" method="post" enctype="multipart/form-data"> 39 <p><input type="text" name="user" placeholder="用户名" /></p> 40 <p><input type="password" name="pwd" placeholder="密码" /></p> 41 <p> 42 男:<input type="radio" name="gender" value="1" /> 43 女:<input type="radio" name="gender" value="2" /> 44 张扬:<input type="radio" name="gender" value="3" /> 45 </p> 46 <p> 47 男:<input type="checkbox" name="fav" value="1" /> 48 女:<input type="checkbox" name="fav" value="2" /> 49 张扬:<input type="checkbox" name="fav" value="3" /> 50 </p> 51 <p> 52 <select name="city"> 53 <option value="bj">北京</option> 54 <option value="sh">上海</option> 55 <option value="tj">天津</option> 56 </select> 57 </p> 58 <p> 59 <input type="file" name="fff"> 60 </p> 61 62 <p><input type="submit" value="提交"></p> 63 </form> 64 </body> 65 </html>
2、正则匹配
url(r'^detail-(\d+).html', views.detail), #正则匹配 url(r'^detail-(?P<nid>\d+)-(?P<uid>\d+).html', views.detail) #正则表达式分组,***
views端对应的两种写法
url(r'^detail-(\d+)-(\d+).html', views.detail) #http://127.0.0.1:8000/login/1-3.html def func(request,nid,uid): print(nid,uid) return ... >>1,3 def func(request, *args,**kwargs): args=(1,3) #元组形式 url(r'^detail-(?P<nid>\d+)-(?P<uid>\d+).html', views.detail) #这种方式,是将nid,uid的数据绑定了 #http://127.0.0.1:8000/login/1-3.html def func(request,nid,uid): #so这块的nid和uid的顺序无所吊谓 print(nid,uid) return ... >>1,3 def func(request, *args,**kwargs): kwargs = {'nid': 1, 'uid': 3} #字典形式
3、为URL路由关系进行命名(name='abc') *** 以后可以根据此名称生成自己想要的URL(生成自定义的URL) ***
小Tips:
request.path_info:当前的URL
request.get_full_path():获取完整地址(有参数)
url(r'^abc/', views.index, name='i1') #与urls.py里的域名相绑定
#方式1,模板语言
<from action="{% url 'i1' %}" method="post"> #url里面啥样,这里就啥样
...
</form>
#方式二,Django内置方法
from django.urls import reverse
def index(request,*args,**kwargs):
v = reverse('i1')
return render(request,'home.html',{'turn':v})
html端
<from action={{ turn }} method = "post">
...
</from>
url(r'^bcd/(\d+)/(\d+)/', views.index, name='i2'), #生成想让他跳转的页面
#方式1,模板语言
<from action="{% url 'i1' 1 3 %}" method="post"> #生成==>http://127.0.0.1:8000/1/3
...
</form>
#方式二,Django内置方法
from django.urls import reverse
def index(request,*args,**kwargs):
v = reverse('i1',args=(90,92,)) #这是个元组,一定要打逗号
return render(request,'home.html',{'turn':v})
html端
<from action={{ turn }} method = "post">
...
</from>
访问方式:http://127.0.0.1:8000/89/86
url(r'^efg/(?P<pid>\d+)/(?P<nid>\d+)/', views.index, name='i3'), #同理,生成想让他跳转的页面
#方式1,模板语言
<from action="{% url "i3" pid=1 nid=9 %}" method="post"> #生成http://127.0.0.1:8000/1/9
...
</form>
#方式二,Django内置方法
from django.urls import reverse
def index(request,*args,**kwargs):
v = reverse('i3', kwargs={'pid': 1, "nid": 9}) #字典格式
return render(request,'home.html',{'turn':v})
html端
<from action={{ turn }} method = "post">
...
</from>
访问方式:http://127.0.0.1:8000/89/86 #一样
4.多级路由
project/urls.py from django.conf.urls import url,include from django.contrib import admin urlpatterns = [ url(r'^cmdb/', include("app01.urls")), url(r'^monitor/', include("app02.urls")), ] app01/urls.py from django.conf.urls import url,include from django.contrib import admin from app01 import views urlpatterns = [ url(r'^login/', views.login), ] app02/urls.py from django.conf.urls import url,include from django.contrib import admin from app02 import views urlpatterns = [ url(r'^login/', views.login), ] 访问方式:http://127.0.0.1:8000/cmdb/login http://127.0.0.1:8000/monitor/login
5、默认值,命名空间
默认值 url(r'^index/', views.index, {'name': 'root'}), def index(request,name): #向函数传递默认值 print(name) return HttpResponse('OK') 命名空间 #听说从来都没用过 #最外层url /crm1/ include('app01.urls',namespace='m1') /crm2/ include('app01.urls',namespace='m') app01.urls /index/ name = 'n1' reverser('m1:n1') #自动生成域名views
视图(views)
之前学的request基本操作
def func(request): request.POST.get(xxx,None) request.GET request.FILES request.getlist request.method request.path_info #获取当前url return render,HttpResponse,redirect #返回的三种方式new
request.environ
from django.core.handlers.wsgi import WSGIRequest #要引入这个模块 def index(request): for k,v in request.environ.items(): # request.environ封装了所有的用户请求信息 print(k,v) print(request.environ['HTTP_USER_AGENT']) # HTTP_USER_AGENT ==> 获取请求头(可以控制用什么**端登录) return HttpResponse('OK')muban
装饰器
-FBV
def auth(func): def inner(request,*args,**kwargs): v = request.COOKIES.get('username111') if not v: return redirect('/login/') return func(request, *args,**kwargs) return inner @auth def index(request): # 获取当前已经登录的用户 v = requst.COOKIES.get('username111') return render(request,'index.html',{'current_user': v})
-CBV
from django import views from django.utils.decorators import method_decorator @method_decorator(auth,name='dispatch') class Order(views.View): # @method_decorator(auth) #也可以在dispatch上写装饰器 # def dispatch(self, request, *args, **kwargs): # return super(Order,self).dispatch(request, *args, **kwargs) def get(self,reqeust): v = reqeust.COOKIES.get('username111') return render(reqeust,'index.html',{'current_user': v}) def post(self,reqeust): v = reqeust.COOKIES.get('username111') return render(reqeust,'index.html',{'current_user': v}) def order(reqeust): # 获取当前已经登录的用户 v = reqeust.COOKIES.get('username111') return render(reqeust,'index.html',{'current_user': v})
接受文件+多选的内容
1 views.py 2 3 def login(request): 4 if request.method == "POST": 5 u = request.POST.get('user') 6 p = request.POST.get('pwd') 7 print(u,p) 8 g = request.POST.get('gender') 9 print(g) 10 f = request.POST.getlist('fav') 11 print(f) 12 obj = request.FILES.get('fff') 13 f = open(obj.name,'wb') 14 for i in obj.chunks(): 15 f.write(i) 16 f.close() 17 18 return render(request,'login.html') 19 20 home.htm 21 22 <!DOCTYPE html> 23 <html lang="en"> 24 <head> 25 <meta charset="UTF-8"> 26 <title>Title</title> 27 </head> 28 <body> 29 <form action="/home" method="post" enctype="multipart/form-data"> //这就是那所谓的特殊的操作 30 <p><input type="text" name="user" placeholder="用户名" /></p> 31 <p><input type="password" name="pwd" placeholder="密码" /></p> 32 <p> 33 男:<input type="radio" name="gender" value="1" /> 34 女:<input type="radio" name="gender" value="2" /> 35 </p> 36 <p> 37 男:<input type="checkbox" name="fav" value="1" /> 38 女:<input type="checkbox" name="fav" value="2" /> 39 </p> 40 <p> 41 <select name="city"> 42 <option value="bj">北京</option> 43 <option value="sh">上海</option> 44 <option value="tj">天津</option> 45 </select> 46 </p> 47 <p> 48 <input type="file" name="fff"> 49 </p> 50 51 <p><input type="submit" value="提交"></p> 52 </form> 53 </body> 54 </html>