zoukankan      html  css  js  c++  java
  • WSGIRequest对象 和querydict对象

    WSGIRequest对象

    • 服务器接收到http协议的请求后,会根据http请求携带的参数以及报文信息创建一个WSGIRequest对象,并且作为视图函数的第一个参数传给视图函数,就是我们经常写的request参数。(wsgirequest是继承于httprequest)
    • 我们可以查看对象的完整路径   print(type(request))

          <class 'django.core.handlers.wsgi.WSGIRequest'>

     常用属性及含义

    1. method:查看当前请求的http方法。(print(request.method))
    2. path:请求服务器的完整“路径”,但不包含域名和参数        (print(request.path))
    3. GET:是一个queryset对象,包含所有以?xx=xxx的形式   如:【172.0.0.0.8000/index/?name=123
    4. POST:也是一个queryset对象,包含以POST方式上传的参数    (name=request.POST.get('name'))
    5. META:存储的客户端发送上来的所有header信息

     常用方法及含义

    1. is_secure():是否采用https协议。【返回值为布尔值】
    2. is_ajax():是否采用djax发送的请求。原理就是判断请求头中是否存在X-Requested-With:XMLHttpRequest。【返回布尔值】
    3. get_host():服务器的域名。如果在访问的时候还有端口号,那么会加上端口号。【www.baidu.com:9000】
    4. get_full_path():返回完整的path。如果有查询字符串,还会加上查询字符串。print(request.get_full_path())【/login/?username=123&password=123】
    5. get_raw_uri():获取完整的url        print(request.get_raw_uri())  【http://127.0.0.1:8000//login/?uesrname=xxx&password=111】

    QueryDict对象

    • request.GETrequest.POST都是QueryDict对象

    两个方法及其含义:

    1. get方法:用来获取指定key的值,如果没有这个key,那么会返回None。
    2. getlist方法:如果浏览器上传上来的key对应的值有多个,那么就需要通过这个方法获取。

    示例代码:

    from django.shortcuts import render
    from django.http import HttpResponse,JsonResponse
    from django.http.request import QueryDict
    from django.views.decorators.http import require_http_methods
    import json
    # Create your views here.
    def index(request):
        print(request.GET.get('p',default=1))  #当查询字符串不是p=xx时都会默认打印1return HttpResponse('success')
    
    @require_http_methods(['GET','POST'])    #下面后用到GET和POST两种方法
    def add_article(request):              
        if request.method == 'GET': 
            return render(request,'articel.html')
        else:
            title=request.POST.get('title')       #获取所添加的标题
    content
    =request.POST.get('content') #获取添加的内容 tags =request.POST.getlist('tags') #如果前面给了两个tags,用get的话只能得到后面添加得那个,这时就用到了getlist,它可以将前面得两个以列表得形式都获取到 print('title;',title) print('content;',content) print('tags;',tags) return HttpResponse('success')

     

  • 相关阅读:
    mysql之存储过程
    Artificial Intelligence in Finance
    7 Exciting Uses of Machine Learning in FinTech
    Machine Learning in Finance – Present and Future Applications
    AI AND THE BOTTOM LINE: 15 EXAMPLES OF ARTIFICIAL INTELLIGENCE IN FINANCE
    5 Ways AI is Transforming the Finance Industry
    图学Kubernetes
    Free Professional Resume Examples and Writing Tips
    npm和yarn的淘宝镜像添加
    世界最具影响力的十大管理大师
  • 原文地址:https://www.cnblogs.com/nihao2/p/12260511.html
Copyright © 2011-2022 走看看