http请求中产生两个核心对象:
http请求:HttpRequest对象http响应:HttpResponse对象
所在位置:django.http
之前我们用到的参数request就是HttpRequest 检测方法:isinstance(request,HttpRequest)
1.HttpRequest对象的属性和方法:
# path: 请求页面的全路径,不包括域名
#
# method: 请求中使用的HTTP方法的字符串表示。全大写表示。例如
#
# if req.method=="GET":
#
# do_something()
#
# elseif req.method=="POST":
#
# do_something_else()
#
# GET: 包含所有HTTP GET参数的类字典对象
#
# POST: 包含所有HTTP POST参数的类字典对象
#
# 服务器收到空的POST请求的情况也是可能发生的,也就是说,表单form通过
# HTTP POST方法提交请求,但是表单中可能没有数据,因此不能使用
# if req.POST来判断是否使用了HTTP POST 方法;应该使用 if req.method=="POST"
#
#
#
# COOKIES: 包含所有cookies的标准Python字典对象;keys和values都是字符串。
#
# FILES: 包含所有上传文件的类字典对象;FILES中的每一个Key都是<input type="file" name="" />标签中 name属性的值,FILES中的每一个value同时也是一个标准的python字典对象,包含下面三个Keys:
#
# filename: 上传文件名,用字符串表示
# content_type: 上传文件的Content Type
# content: 上传文件的原始内容
#
#
# user: 是一个django.contrib.auth.models.User对象,代表当前登陆的用户。如果访问用户当前
# 没有登陆,user将被初始化为django.contrib.auth.models.AnonymousUser的实例。你
# 可以通过user的is_authenticated()方法来辨别用户是否登陆:
# if req.user.is_authenticated();只有激活Django中的AuthenticationMiddleware
# 时该属性才可用
#
# session: 唯一可读写的属性,代表当前会话的字典对象;自己有激活Django中的session支持时该属性才可用。
#方法
get_full_path(), 比如:http://127.0.0.1:8000/index33/?name=123 ,req.get_full_path()得到的结果就是/index33/?name=123
req.path:/index33
2.HttpResponse对象:
对于HttpRequest对象来说,是由django自动创建的,但是,HttpResponse对象就必须我们自己创建。每个view请求处理方法必须返回一个HttpResponse对象。
HttpResponse类在django.http.HttpResponse
在HttpResponse对象上扩展的常用方法:页面渲染: render()(推荐)<br> render_to_response(),
页面跳转: redirect("路径")
locals(): 可以直接将函数中所有的变量传给模板
------------------------url.py
urlpatterns = [
path('login',views.login),
path('welcome',views.welcome)
]
-----------------------------views.py
def login(request):
if request.method=="POST":
user=request.POST.get('user')
pwd=request.POST.get('pwd')
if user=='alex' and pwd=='123':
return redirect('/welcome') #直接写路径,不需要request
#return render(request,'welcome.html',locals())
else:
return HttpResponse('Wrong password')
return render(request,'login.html')
def welcome(request):
user='alex'
return render(request,'welcome.html',locals())
-------------------------------login.html
<form action="/login" method="post">
<p>用户名<input type="text" name="user"></p>
<p>密码<input type="text" name="pwd"></p>
<p><input type="submit"></p>
</form>
-----------------------------welcome.html
<h1>hello {{ user }}</h1>
#总结: render和redirect的区别:
# 1 if render的页面需要模板语言渲染,需要的将数据库的数据加载到html,那么所有的这一部分
# 除了写在welcome的视图函数中,必须还要写在login中,代码重复,没有解耦.
# 2 the most important: url没有跳转到/welcome,而是还在/login/,所以当刷新后
# 又得重新登录.