How to write Django REST Api without model to send

2019-06-11 19:50发布

问题:

I want to write a rest method without model so that I can send a csv file using python requests module. This csv file should be remotely accessed from the server.

For example - I have logged in to my project using requests and get the cookies and headers so that I can pass it to the following requests method..

files = {'file': open('test.csv', 'rb')}
response = requests.post(url, files=files, headers=api_headers,
                      cookies=api_cookies)

So this url should be : call for that rest method.

views.py file :

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

    def post(self, request, format=None):
        csvfile = request.data['file']
        #reader = csv.DictReader(csvfile)
        #for r in reader:
            #print(r)
        return Response(status=204)

Just to note - I am sending a csv file using requests module.

Can anyone please help me on how to write this rest method?

回答1:

Normal django view

def myview(request):
    f = request.FILES['file']
    with open('some/folder/name.txt', 'wb+') as destination: 
        #f.name or f.filename (dont know which one)will get filename.So you can replace it name.txt
        for chunk in f.chunks():
            destination.write(chunk)
    return JsonResponse({"message": "Uploaded!"})

UPDATE

# views.py
class FileUploadView(views.APIView):
    parser_classes = (FileUploadParser,)

    def post(self, request, filename, format=None):
        file_obj = request.data['file']
        # ...
        # do some stuff with uploaded file
        # ...
        return Response(status=200)

# urls.py
urlpatterns = [
    # ...
    url(r'^upload/(?P<filename>[^/]+)$', FileUploadView.as_view())
]

Then

url = 'http://127.0.0.1:8000/upload/test.csv' #filename should be in url
files = {'file': open('test.csv', 'rb')}
response = requests.post(url, files=files, headers=api_headers,
                      cookies=api_cookies)


回答2:

This would do the trick for you. http://www.django-rest-framework.org/api-guide/parsers/#fileuploadparser

# views.py
class FileUploadView(views.APIView):
    parser_classes = (FileUploadParser,)

    def post(self, request, filename, format=None):
        file_obj = request.data['file']
        # ...
        # do some stuff with uploaded file
        # ...
        return Response(status=204)

# urls.py
urlpatterns = [
    # ...
    url(r'^upload/(?P<filename>[^/]+)$', FileUploadView.as_view())
]

# test with this curl
curl -X POST -S -H -F "file=@something.jpg;type=image/jpg" 127.0.0.1:8000/upload/myfile/