Django中的views函数
http请求中产生两个核心对象
- http请求:HttpRequest对象
- http响应:HttpResponse对象
一. http请求:HttpRequest对象
1、通过isinstance(request,HttpRequest)得知request就是HttpRequest类的实例化对象
eg:
from django.shortcuts import HttpResponse, render, redirect from django.http import HttpRequest def year(request, year): print(isinstance(request, HttpRequest))
return HttpResponse(year)
输出True
Starting development server at http://127.0.0.1:8000/ Quit the server with CTRL-BREAK. True [05/May/2018 00:06:34] "GET /2018 HTTP/1.1" 200 4
2、 HttpRequest对象的方法和属性
属性:path,method,GET,POST,COOKIES,FILES,user,session
path:请求页面的全路径,不包括域名和post内容
eg:
def year(request, year): print(isinstance(request, HttpRequest)) print(request.path) return HttpResponse(year)
在浏览器输入http://127.0.0.1:8000/2018
[05/May/2018 00:18:02] "GET / HTTP/1.1" 404 2393 True /2018
method:判断请求方式返回GET或POST
语法:request.method
GET、POST:包含所有http GET、POST参数的类字典对象
eg:
def year(request, year): print(isinstance(request, HttpRequest)) print(request.path) print(request.GET) return HttpResponse(year)
浏览器中输入http://127.0.0.1:8000/2018?1234=444进行get请求
[05/May/2018 00:30:23] "GET /2018?1234&111 HTTP/1.1" 200 4 True /2018 <QueryDict: {u'1234': [u'444']}>
字典对象 :QueryDict: {u'1234': [u'444']其中的u代表采用Unicode编码,QueryDict就是一个字典对象,可以用所有的字典方法
COOKIES
待续
FILES
待续
user
待续
session
待续
方法:get_full_path()
get_full_path():返回除域名外全部路径
二、http响应:HttpResponse对象
HttpResponse对象必须由我们自己创建。每个view请求处理方法必须返回一个HttpResponse对象
HttpResponse对象上扩展的常用方法:
render()、render_to_response()、redirect()、locals()
1、render()和render_to_response()
两者均可实现页面渲染,render必须传入request参数,后者不需要
建议用前者,后者有时会有bug
2、redirect()
语法:redirect("路径")
实现页面的跳转
eg
register.html注册文件,用post实现表单提交功能
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <p>login</p> <form action="/blog/register/" method="post"> <p>姓名:<input type="text" name="username"></p> <p>密码:<input type="text" name="pwd"></p> <p><input type="submit"></p> </form> </body> </html>
register函数
def register(request): if request.method == 'POST': if request.POST.get('username') == 'bbu': return redirect('/blog/login/') return HttpResponse('welcome') return render(request, 'register.html')
当注册者的username为bbu时,跳转到login页面
分析: 在浏览器中输入http://127.0.0.1:8000/blog/register/时,浏览器以get的方式向服务端进行请求,经过路由解析后,render函数将register.html响应给浏览器,此时在交互界面输入相应数据,提交,register.html在以post的方式将表单post到服务端,经过判断请求方式为post且username为bbu,进而执行redirect函数,实现跳转。
3、locals()
将函数中所有的变量传给模板
eg
访问index.html,使页面显示当前时间
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>HELLO</title> </head> <body> <h1>{{ time_now }}</h1> </body> </html>
{{ time }}是django对前端文件进行渲染的方式,time为相应的变量值
1、不利用locals()
def time_show(request): t = time.asctime() return render(request, 'index.html', {'time_now': t})
这样做也可以实现将t变量的值传给前端index.html文件的time,将{{ time_now }}渲染为当前的时间,这样做的缺点是,如果需要渲染的变量过多将会非常麻烦
2、利用locals()
def time_show(request): time_now = time.asctime() return render(request, 'index.html', locals())
这样做函数中变量名必须和前端的变量名相同