view视图响应方法

from django.shortcuts import render, HttpResponse, redirect


# Create your views here.


def index(request):  # http相关请求信息--封装--HttpRequest对象-传参-->request
    # request 方法
    if request.method == 'GET':
        print('---------------------GET---------------------')
        print('GET:', request.GET)  # get请求提交的数据
        print('META:', request.META)  # 所有的HTTP请求首部相关信息, 具体的头部信息取决于客户端和服务端
        print('path:', request.path)  # /index/
        print('path_info:', request.path_info)  # /index/返回用户访问的url,不包含域名
        print('full_path:', request.get_full_path())  # /index/?username=Sunny&password=123
        print('body:', request.body)
        return render(request, 'index.html')

    else:
        # index.html中,表单form action="", action为空表示从当前路下提交数据, method="get",method,请求方式:get or post

        print('---------------------POST---------------------')
        print('method:', request.method)  # 请求方法:get还是post
        print('body:',
              request.body)  # 请求体, byte类型, request.POST数据就是从body中取到的.b'username=sunny&password=1234'(socket发送的byte类型对象)
        print('path:', request.path)
        print('path_info:', request.path_info)  # 返回用户访问的url,不包含域名
        print('full_path:', request.get_full_path())
        print('META:', request.META)  # 所有的HTTP请求首部相关信息, 具体的头部信息取决于客户端和服务端
        print('POST:',
              request.POST)  # 包含所有HTTP POST参数(request.body中的数据封装)的类字典对象,<QueryDict: {'username': ['sunny'], 'password': ['1234']}>

        return HttpResponse('Post 请求已响应')


# ################ HTTP协议是基于请求响应的协议,一请求对应一响应 ################
# HTTP协议 -- 应用层协议,下层传输层 -- TCP协议(一收一发),基于流,稳定
# django和浏览器都封装了socket

# views视图处理的是对于浏览器请求的响应
# 1.浏览器get请求:/login/
#   服务器响应: login.html
# 2.浏览器post请求: {'username':'sunny', 'password':'1234'}
#   服务器响应: status code:302 not found(重定向状态码), location: /home/
# 3.浏览器get请求: /home/ 本质:浏览器接收到重定向状态码,内部做了location.herf='http:127.0.0.1/home/  (location.href='http://www.baidu.com') 重定向请求
#   服务器响应:接收到重定向的请求,响应home.html
def login(request):
    if request.method == 'GET':
        return render(request, 'login.html')  # 响应html页面
    else:
        username = request.POST.get('username')
        password = request.POST.get('password')
        if username == 'sunny' and password == '1234':
            return redirect('/home/')  # 重定向页面, 参数为路径,需要在urls中定义
            # return render(request, 'home.html')
        else:
            return HttpResponse('Wrong user name or password!Please Retry!')  # 响应消息


# 首页
def home(request):
    return render(request, 'home.html')

响应对象的三个方法:

  • HttpResponse: 响应消息

  • render: 响应页面

  • redirect: 响应重定向信息

    render, redirect本质是调用的HttpResponse,因为响应的不管是页面还是消息都是字符串

重定向的2个状态码

  • 301: 永久重定向, 原来的资源完全不用,原来的网站完全不存在

  • 302: 临时重定向, 原来的资源还在,网站还在

    html:

    <head>
    <meta name='keywords' content='nga, ngacn...'>
    <head>
    搜索引擎通过搜索html keyworks关键字(nga, ngacn等), 就能找到网站.因为百度通过爬虫收录了所有上线网站的html页面
    
原文地址:https://www.cnblogs.com/relaxlee/p/12843143.html