from django.http import HttpResponse import datetime
def current_datetime(request): now = datetime.datetime.now() html = "<html><body>It is now %s.</body></html>" % now return HttpResponse(html)
可读性更增强,将post 和 get请求分开用两个方法定义html
记得更改urls中的调用方式python
实例ajax
# CBV版添加班级 from django.views import View class AddClass(View): def get(self, request): return render(request, "add_class.html") def post(self, request): class_name = request.POST.get("class_name") models.Classes.objects.create(name=class_name) return redirect("/class_list/") # urls.py中 url(r'^add_class/$', views.AddClass.as_view()),
代码更加简洁,可是可读性差,urls 中的调用方式简单django
实例浏览器
def add_class(request): if request.method == "POST": class_name = request.POST.get("class_name") models.Classes.objects.create(name=class_name) return redirect("/class_list/") return render(request, "add_class.html")
经过调用 View 中的 as_view() 调用 view 再调用 dispatch 缓存
本质上执行的则是 dispatch 安全
利用 super 执行父类中的 dispatch 方法后再执行本身的服务器
重写dispatch函数能够实现 :cookie
全部类型的函数执行的时候都作一个固定操做的插入session
from django.shortcuts import render,HttpResponse from django.views import View
class LoginView(View):
defdispatch(self, request, *args, **kwargs): ... ret = super().dispatch(self, request, *args, **kwargs) return ret def get(self): ... return HttpResponse("ok")
FBV自己就是一个函数,因此和给普通的函数加装饰器无差异
示例
def wrapper(func): def inner(*args, **kwargs): start_time = time.time() ret = func(*args, **kwargs) end_time = time.time() print("used:", end_time-start_time) return ret return inner # FBV版添加班级 @wrapper def add_class(request): if request.method == "POST": class_name = request.POST.get("class_name") models.Classes.objects.create(name=class_name) return redirect("/class_list/") return render(request, "add_class.html")
类须要特殊的装饰器进行一次封装才行
from django.utils.decorators import method_decorator
@method_decorator(wrapper)
给CBV加装饰器能够有多种方式
给 类 加装饰器
from django.utils.decorators import method_decorator @method_decorator(check_login, name="get") @method_decorator(check_login, name="post") class HomeView(View): def dispatch(self, request, *args, **kwargs): return super(HomeView, self).dispatch(request, *args, **kwargs) def get(self, request): return render(request, "home.html") def post(self, request): print("Home View POST method...") return redirect("/index/")
给 post 或者 get 加装饰器
from django.utils.decorators import method_decorator class HomeView(View): def dispatch(self, request, *args, **kwargs) return super(HomeView, self).dispatch(request, *args, **kwargs) def get(self, request): return render(request, "home.html") @method_decorator(check_login) def post(self, request): print("Home View POST method...") return redirect("/index/")
给 dispatch 加装饰器
CBV中首先执行的就是dispatch,这样至关于给get和post方法都加上了装饰器
from django.utils.decorators import method_decorator class HomeView(View): @method_decorator(check_login) def dispatch(self, request, *args, **kwargs): return super(HomeView, self).dispatch(request, *args, **kwargs) def get(self, request): return render(request, "home.html") def post(self, request): print("Home View POST method...") return redirect("/index/")
经常使用的
不经常使用的特么好多
1 1.HttpRequest.get_host() 2 3 根据从HTTP_X_FORWARDED_HOST(若是打开 USE_X_FORWARDED_HOST,默认为False)和 HTTP_HOST 头部信息返回请求的原始主机。 4 若是这两个头部没有提供相应的值,则使用SERVER_NAME 和SERVER_PORT,在PEP 3333 中有详细描述。 5 6 USE_X_FORWARDED_HOST:一个布尔值,用于指定是否优先使用 X-Forwarded-Host 首部,仅在代理设置了该首部的状况下,才能够被使用。 7 8 例如:"127.0.0.1:8000" 9 10 注意:当主机位于多个代理后面时,get_host() 方法将会失败。除非使用中间件重写代理的首部。 11 12 13 14 2.HttpRequest.get_full_path() 15 16 返回 path,若是能够将加上查询字符串。 17 18 例如:"/music/bands/the_beatles/?print=true" 19 20 21 22 3.HttpRequest.get_signed_cookie(key, default=RAISE_ERROR, salt='', max_age=None) 23 24 返回签名过的Cookie 对应的值,若是签名再也不合法则返回django.core.signing.BadSignature。 25 26 若是提供 default 参数,将不会引起异常并返回 default 的值。 27 28 可选参数salt 能够用来对安全密钥强力攻击提供额外的保护。max_age 参数用于检查Cookie 对应的时间戳以确保Cookie 的时间不会超过max_age 秒。 29 30 复制代码 31 >>> request.get_signed_cookie('name') 32 'Tony' 33 >>> request.get_signed_cookie('name', salt='name-salt') 34 'Tony' # 假设在设置cookie的时候使用的是相同的salt 35 >>> request.get_signed_cookie('non-existing-cookie') 36 ... 37 KeyError: 'non-existing-cookie' # 没有相应的键时触发异常 38 >>> request.get_signed_cookie('non-existing-cookie', False) 39 False 40 >>> request.get_signed_cookie('cookie-that-was-tampered-with') 41 ... 42 BadSignature: ... 43 >>> request.get_signed_cookie('name', max_age=60) 44 ... 45 SignatureExpired: Signature age 1677.3839159 > 60 seconds 46 >>> request.get_signed_cookie('name', False, max_age=60) 47 False 48 复制代码 49 50 51 52 4.HttpRequest.is_secure() 53 54 若是请求时是安全的,则返回True;即请求通是过 HTTPS 发起的。 55 56 57 58 5.HttpRequest.is_ajax() 59 60 若是请求是经过XMLHttpRequest 发起的,则返回True,方法是检查 HTTP_X_REQUESTED_WITH 相应的首部是不是字符串'XMLHttpRequest'。 61 62 大部分现代的 JavaScript 库都会发送这个头部。若是你编写本身的 XMLHttpRequest 调用(在浏览器端),你必须手工设置这个值来让 is_ajax() 能够工做。 63 64 若是一个响应须要根据请求是不是经过AJAX 发起的,而且你正在使用某种形式的缓存例如Django 的 cache middleware, 65 你应该使用 vary_on_headers('HTTP_X_REQUESTED_WITH') 装饰你的视图以让响应可以正确地缓存。 66 67 请求相关方法
属性
1 属性: 2 django将请求报文中的请求行、头部信息、内容主体封装成 HttpRequest 类中的属性。 3 除了特殊说明的以外,其余均为只读的。 4 5 6 0.HttpRequest.scheme 7 表示请求方案的字符串(一般为http或https) 8 9 1.HttpRequest.body 10 11 一个字符串,表明请求报文的主体。在处理非 HTTP 形式的报文时很是有用,例如:二进制图片、XML,Json等。 12 13 可是,若是要处理表单数据的时候,推荐仍是使用 HttpRequest.POST 。 14 15 另外,咱们还能够用 python 的类文件方法去操做它,详情参考 HttpRequest.read() 。 16 17 18 19 2.HttpRequest.path 20 21 一个字符串,表示请求的路径组件(不含域名)。 22 23 例如:"/music/bands/the_beatles/" 24 25 26 27 3.HttpRequest.method 28 29 一个字符串,表示请求使用的HTTP 方法。必须使用大写。 30 31 例如:"GET"、"POST" 32 33 34 35 4.HttpRequest.encoding 36 37 一个字符串,表示提交的数据的编码方式(若是为 None 则表示使用 DEFAULT_CHARSET 的设置,默认为 'utf-8')。 38 这个属性是可写的,你能够修改它来修改访问表单数据使用的编码。 39 接下来对属性的任何访问(例如从 GET 或 POST 中读取数据)将使用新的 encoding 值。 40 若是你知道表单数据的编码不是 DEFAULT_CHARSET ,则使用它。 41 42 43 44 5.HttpRequest.GET 45 46 一个相似于字典的对象,包含 HTTP GET 的全部参数。详情请参考 QueryDict 对象。 47 48 49 50 6.HttpRequest.POST 51 52 一个相似于字典的对象,若是请求中包含表单数据,则将这些数据封装成 QueryDict 对象。 53 54 POST 请求能够带有空的 POST 字典 —— 若是经过 HTTP POST 方法发送一个表单,可是表单中没有任何的数据,QueryDict 对象依然会被建立。 55 所以,不该该使用 if request.POST 来检查使用的是不是POST 方法;应该使用 if request.method == "POST" 56 57 另外:若是使用 POST 上传文件的话,文件信息将包含在 FILES 属性中。 58 59 7.HttpRequest.COOKIES 60 61 一个标准的Python 字典,包含全部的cookie。键和值都为字符串。 62 63 64 65 8.HttpRequest.FILES 66 67 一个相似于字典的对象,包含全部的上传文件信息。 68 FILES 中的每一个键为<input type="file" name="" /> 中的name,值则为对应的数据。 69 70 注意,FILES 只有在请求的方法为POST 且提交的<form> 带有enctype="multipart/form-data" 的状况下才会 71 包含数据。不然,FILES 将为一个空的相似于字典的对象。 72 73 74 75 9.HttpRequest.META 76 77 一个标准的Python 字典,包含全部的HTTP 首部。具体的头部信息取决于客户端和服务器,下面是一些示例: 78 79 CONTENT_LENGTH —— 请求的正文的长度(是一个字符串)。 80 CONTENT_TYPE —— 请求的正文的MIME 类型。 81 HTTP_ACCEPT —— 响应可接收的Content-Type。 82 HTTP_ACCEPT_ENCODING —— 响应可接收的编码。 83 HTTP_ACCEPT_LANGUAGE —— 响应可接收的语言。 84 HTTP_HOST —— 客服端发送的HTTP Host 头部。 85 HTTP_REFERER —— Referring 页面。 86 HTTP_USER_AGENT —— 客户端的user-agent 字符串。 87 QUERY_STRING —— 单个字符串形式的查询字符串(未解析过的形式)。 88 REMOTE_ADDR —— 客户端的IP 地址。 89 REMOTE_HOST —— 客户端的主机名。 90 REMOTE_USER —— 服务器认证后的用户。 91 REQUEST_METHOD —— 一个字符串,例如"GET" 或"POST"。 92 SERVER_NAME —— 服务器的主机名。 93 SERVER_PORT —— 服务器的端口(是一个字符串)。 94 从上面能够看到,除 CONTENT_LENGTH 和 CONTENT_TYPE 以外,请求中的任何 HTTP 首部转换为 META 的键时, 95 都会将全部字母大写并将链接符替换为下划线最后加上 HTTP_ 前缀。 96 因此,一个叫作 X-Bender 的头部将转换成 META 中的 HTTP_X_BENDER 键。 97 98 99 10.HttpRequest.user 100 101 一个 AUTH_USER_MODEL 类型的对象,表示当前登陆的用户。 102 103 若是用户当前没有登陆,user 将设置为 django.contrib.auth.models.AnonymousUser 的一个实例。你能够经过 is_authenticated() 区分它们。 104 105 例如: 106 107 if request.user.is_authenticated(): 108 # Do something for logged-in users. 109 else: 110 # Do something for anonymous users. 111 112 113 user 只有当Django 启用 AuthenticationMiddleware 中间件时才可用。 114 115 ------------------------------------------------------------------------------------- 116 117 匿名用户 118 class models.AnonymousUser 119 120 django.contrib.auth.models.AnonymousUser 类实现了django.contrib.auth.models.User 接口,但具备下面几个不一样点: 121 122 id 永远为None。 123 username 永远为空字符串。 124 get_username() 永远返回空字符串。 125 is_staff 和 is_superuser 永远为False。 126 is_active 永远为 False。 127 groups 和 user_permissions 永远为空。 128 is_anonymous() 返回True 而不是False。 129 is_authenticated() 返回False 而不是True。 130 set_password()、check_password()、save() 和delete() 引起 NotImplementedError。 131 New in Django 1.8: 132 新增 AnonymousUser.get_username() 以更好地模拟 django.contrib.auth.models.User。 133 134 135 136 11.HttpRequest.session 137 138 一个既可读又可写的相似于字典的对象,表示当前的会话。只有当Django 启用会话的支持时才可用。 139 完整的细节参见会话的文档。 140 141 request属性相关
上传文件示例
1 Django接受上传文件代码 2 3 from django.conf.urls import url 4 from django.shortcuts import HttpResponse 5 6 7 def upload(request): 8 print("request.GET:", request.GET) 9 print("request.POST:", request.POST) 10 11 if request.FILES: 12 filename = request.FILES["file"].name 13 with open(filename, 'wb') as f: 14 for chunk in request.FILES['file'].chunks(): 15 f.write(chunk) 16 return HttpResponse('上传成功') 17 return HttpResponse("收到了!") 18 19 urlpatterns = [ 20 url(r'^upload/', upload), 21 ]
一般用来传递基本字符串信息,可指定类型
response = HttpResponse("Here's the text of the Web page.") response = HttpResponse("Text only, please.", content_type="text/plain")
属性
结果返回一个网页对象,必须带参数request,且能够加其余自定义参数(参数以字典的形式,或者直接 locals )
render 渲染的究竟是什么?
return render(request, 'myapp/index.html', {'foo': 'bar'})
重定向到一个另外一个URL
return redirect('/some/url/') return redirect('http://example.com/')
HttpResponse的子类,用来生成JSON编码的响应。
from django.http import JsonResponse response = JsonResponse({'foo': 'bar'}) print(response.content) # b'{"foo": "bar"}'
# 默认只能传递字典类型,若是要传递非字典类型须要设置一下safe关键字参数。 response = JsonResponse([1, 2, 3], safe=False)