Cannot PUT file to Django REST API by python reque

2019-04-12 23:34发布

问题:

I am using python requests to put file to django rest api:

put:

def pretty_print(req):
    print('1,{}\n2,{}\n3,{}\n\n4,{}'.format(
        '-----------START-----------',
        req.method + ' ' + req.url,
        '\n'.join('{}: {}'.format(k, v) for k, v in req.headers.items()),
        req.body[0:10],
    ))
    print "----------END------------"


try:
    req = requests.Request('PUT',
            'https://myip/myproject/api/upload',
            headers={'content-type':'multipart/form-data'},
            files={"file": ('file1', open(filepath, "rb"))} )
    prepped = req.prepare()
    print "prepped:", prepped.headers
    #print "prepped:", prepped.body
    pretty_print( prepped )
    s = requests.Session()
    r = s.send(prepped, verify=False)
    print "response:", r.json()
except Exception as e:
    print "Exception:", e

views.py

class FileUploadView(APIView):
    parser_classes = (MultiPartParser,)

    def put(self, request):
        try:
            print "data:", request.data.dict()
            print "file:", request.FILES.dict()
            print "----------"
            data = {'files': 'testing'}
            response = Response(data)

But, I got the empty dicts.

data: {}
file: {}

And the print out of the requests:

prepped: {'Content-Length': '18364', 'content-type': 'text/plain'}
1,-----------START-----------
2,PUT https://10.32.64.4/reporting-central/api/upload
3,content-type: text/plain
Content-Length: 18364

4,--e9541743
----------END------------
/usr/local/lib/python2.7/dist-packages/requests/packages/urllib3/util/ssl_.py:318: SNIMissingWarning: An HTTPS request has been made, but the SNI (Subject Name Indication) extension to TLS is not available on this platform. This may cause the server to present an incorrect TLS certificate, which can cause validation failures. You can upgrade to a newer version of Python to solve this. For more information, see https://urllib3.readthedocs.org/en/latest/security.html#snimissingwarning.
  SNIMissingWarning
/usr/local/lib/python2.7/dist-packages/requests/packages/urllib3/util/ssl_.py:122: InsecurePlatformWarning: A true SSLContext object is not available. This prevents urllib3 from configuring SSL appropriately and may cause certain SSL connections to fail. You can upgrade to a newer version of Python to solve this. For more information, see https://urllib3.readthedocs.org/en/latest/security.html#insecureplatformwarning.
  InsecurePlatformWarning
/usr/local/lib/python2.7/dist-packages/requests/packages/urllib3/connectionpool.py:821: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.org/en/latest/security.html
  InsecureRequestWarning)
/usr/local/lib/python2.7/dist-packages/requests/packages/urllib3/connectionpool.py:821: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.org/en/latest/security.html
  InsecureRequestWarning)
response: {u'files': u'testing'}

Anything wrong? Any comments welcomed. Thanks.

UPDATE

my app url.py:

from api.views import *

urlpatterns = [
    url(r'^upload/$', FileUploadView.as_view(), name='api-upload'),
    url(r'^test/$', test, name='api-test'),
]

my project url.py:

urlpatterns = patterns('',
        url(r'^api/', include('api.urls')),
)

UPDATE2

I found that maybe my requests PUT is wrong. because I used postman to do put, which was successful. Still hope to figure out why my requests PUT not work.