Django之请求数据格式

Django默认解析格式application/x-www-form-urlencoded   

要求:a.  application/x-www-form-urlencoded

   b.  数据格式还必须是:a=1&b=1

本文做的是通过不同请求数据格式和不同发请求的方式,在后台取到途径(感兴趣的朋友可以读下Django的request,response这双模块)

json/multipart/form-data当然还有其它请求数据的格式,这是常用的几个,text-plain没用过

举例说明:

路由: 

1 from django.contrib import admin
2 from django.urls import path
3 from app01 import views
4 
5 urlpatterns = [
6     path('admin/', admin.site.urls),
7     path('user/', views.user),
8     path('file_put/', views.file_put),
9 ]

视图:

 1 from django.shortcuts import render, HttpResponse
 2 from django.http import request
 3 import os
 4 from contenttype.settings import BASE_DIR
 5 
 6 
 7 def user(request):
 8     import json
 9     # ret = json.loads(request.body.decode('utf8'))
10     # print(ret["user"])
11     return render(request, 'index.html')
12 
13 
14 def file_put(request):
15     print(request.FILES)
16     file_obj = request.FILES.get('file_obj')
17     path = file_obj.name
18 
19     path = os.path.join(BASE_DIR, 'media', 'image', path)
20     with open(path, 'wb') as f:
21         for line in file_obj:
22             f.write(line)
23         f.close()
24 
25     return render(request, 'file_put.html')

 模板

  index.html

 1 <!DOCTYPE html>
 2 <html lang="en">
 3 <head>
 4     <meta charset="UTF-8">
 5     <title>index</title>
 6 </head>
 7 <body>
 8 <form action="/user/" method="post" enctype="application/x-www-form-urlencoded">
 9     {% csrf_token %}
10     <p>用户名<input id='user' type="text" name="user"></p>
11     <input type="submit" value="提交">
12     <a onclick="Ajax();">urlencoded ajax提交</a>
13     <a onclick="Ajax1();">json ajax提交</a>
14     <hr>
15     <script src="/static/jquery-3.3.1.min.js"></script>
16     <script src="/static/jquery.cookie.js"></script>
17     <script>
18         function Ajax() {
19             var csrf = $('input[name="csrfmiddlewaretoken"]').val();
20             var user = $('#user').val();
21             $.ajax({
22                 url: '/user/',
23                 type: 'POST',
24                 data:{
25                     'user':user,
26                     'csrfmiddlewaretoken': csrf
27                 },
28                 success:function (arg) {
29                     console.log(arg)
30                 }
31             })
32         }
33         function Ajax1() {
34             var token = $.cookie('csrftoken');
35             var user = $('#user').val();
36             $.ajax({
37                 url: '/user/',
38                 type: 'POST',
39                 headers:{
40                     "X-CSRFToken":token
41                 },
42                 contentType: "json",
43                 data:JSON.stringify({
44                     "user":user
45                 }),
46                 success:function (arg) {
47                     console.log(arg)
48                 }
49             })
50         }
51     </script>
52 </form>
53 </body>
54 </html>

file_put.html

 1 <!DOCTYPE html>
 2 <html lang="en">
 3 <head>
 4     <meta charset="UTF-8">
 5     <title></title>
 6 </head>
 7 <body>
 8     <h3>文件上传</h3>
 9 
10     <form action="/file_put/" method="post" enctype="multipart/form-data">
11         {% csrf_token %}
12         姓名<input type="text" name="user">
13         文件名<input type="file" name="file_obj" id="file">
14         <input type="submit" value="提交">
15     </form>
16     <hr>
17     <h3>ajax文件上传</h3>
18     <div>
19         文件名<input type="file" name="file_obj" id="file">
20         姓名<input type="text" name="user" id="user">
21         <input type="button" class="filebtn" value="按钮">
22     </div>
23     <script src="/static/jquery-3.3.1.min.js"></script>
24     <script>
25         $('.filebtn').click(function () {
26             var formdata = new FormData();
27             formdata.append("file_obj", $('#file')[0].files[0]);
28             formdata.append("user", $('#user').val());
29             $.ajax({
30                 url:'/file_put/',
31                 type:'post',
32                 processData:false,//不处理数据内部直接处理
33                 contentType:false,//不设置内容类型 内部直接处理
34                 data:formdata,
35                 success:function (args) {
36                     console.log(args)
37                 }
38             })
39         })
40     </script>
41 </body>
42 </html> 

总结:

  在上传文件的时候,在ajax中必须加上processData字段,contentType字段

  在发json数据的时候,注意数据的格式

  在后台获取前台发的数据request要根据发的方式

HttpRequest类

源码中常用方法

封装到对象中的数据:

self.GET = QueryDict(mutable=True)
self.POST = QueryDict(mutable=True)
self.COOKIES = {}
self.META = {}
self.FILES = MultiValueDict()

self.path = ''
self.path_info = ''
self.method = None
self.resolver_match = None
self._post_parse_error = False
self.content_type = None
self.content_params = None

get_host

get_port

get_full_path

get_full_path_info

get_signed_cookie

encoding

body

猜你喜欢

转载自www.cnblogs.com/Alexephor/p/11308330.html