Django uses request to get the parameters sent by the browser

jacklove
Release: 2018-06-11 22:25:40
Original
3554 people have browsed it

Getting data (four ways)

1. url: 需要正则去匹配
    url(r'^index/(num)/$', view.index)
    匹配到的参数会自动传入对应的视图函数

    也可以给匹配到的参数起名字?P<num>
    url(r&#39;^index/(?P<num1>\d*)(?P<num2>\w*)$&#39;,)

    使用url传参的时候,要么都使用位置参数,要么都使用给参数起名字的方式

    也可以通过request.path获取到url然后获取相应的参数.
    如访问127.0.0.1:8000/index/
    则request.path = &#39;/index/&#39;2. ?号后面的键值对(又叫查询字符串): 
    如 index/?num=55&num2=66&num=77
    request.GET.get(&#39;num&#39;) # 获取的是77
    request.GET.getlist(&#39;num&#39;) # 获取num的所有值
    request.GET.get(&#39;num2&#39;) 

3. 请求体
    request.POST.get() 获取表单数据

    request.body 获取非表单数据,如json
    request.body返回的是一个byte的对象
        b&#39;{"key":"value"}&#39;,可以通过下面方式获取值
    data = eval(request.body.decode()).get(&#39;key&#39;)
    data1 = json.loads(request.body).get(&#39;key&#39;)    #如果request.body没有数据上面两条语句都会报错4. 报文头
    request.META 获取请求头信息,
    django会自动把获取到的请求头全部转化为大写,并在前面加上HTTP,如:
    请求头: User-Agent:***** 
    获取方式: request.META.get(&#39;HTTP_USER_AGENT&#39;)
Copy after login
  • Code sample (getting request data)

# 获取正则匹配到的数据,num1未位置参数,num2为命名参数,def index(request,num2=None, num1=None):
    print(num2)    # 构造响应数据
    reNT&#39;)
    sp = HttpResponse(&#39;hello world&#39;)

    # 获取请求头
    header = request.META.get(&#39;HTTP_USER_AGE)
    # 获取地址
    path = request.path    # 获取 ? 后面的数据(获取查询字符串数据)
    para = request.GET

    # 获取json数据
    json_data = request.body
    data = eval(request.body.decode()).get(&#39;asd&#39;)
    data1 = json.loads(request.body).get(&#39;asd&#39;)
    # 获取表单数据
    form_data = request.POST    # 获取请求方法
    method = request.method    # 获取文件
    file_obj = request.FILES.get(&#39;image&#39;)

    return resp
Copy after login

This This article explains in detail how Django uses request to obtain the parameters sent by the browser. For more information, please pay attention to the PHP Chinese website.

Related recommendations:

The problem of passing values ​​​​from the parent component to the child component echarts in vue

Javascript strict mode detailed explanation

Related code analysis of php to implement login function

The above is the detailed content of Django uses request to get the parameters sent by the browser. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template