1

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?

11
  • REST Api doesn't mean it need a Model. You can do normal views to accept the file. Commented Apr 10, 2017 at 9:58
  • so you want to upload a file using api and you would do some processing or what ever on the file in the View ? Commented Apr 10, 2017 at 9:58
  • @rrmerugu yes correct. Commented Apr 10, 2017 at 10:00
  • @itzmeontv Can you please give me an example? Commented Apr 10, 2017 at 10:01
  • Yup. it have direct doc django-rest-framework.org/api-guide/parsers/#fileuploadparser or you are not using drf ? Commented Apr 10, 2017 at 10:02

2 Answers 2

4

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)
Sign up to request clarification or add additional context in comments.

Comments

3

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 "[email protected];type=image/jpg" 127.0.0.1:8000/upload/myfile/

11 Comments

I have created above function - and when I try to send a file using requests - files = {'file': open('test.pdf', 'rb')}, response = requests.post('127.0.0.1:8000/upload/', files=files, headers=api_headers,cookies=api_cookies). It gives me an 400 error:Bad request.Please check and help.
@SnehaShinde Then why did you accept that. Instead of def put, use post
@Sneha Can u post the log error if any from the console
@itzmeontv Sorry for that,I thought it will work.Anyway I tried replacing put with 'post'.but still it's giving the same error.Am I defining the url correctly - '127.0.0.1:8000/upload/' to the requests?
@SnehaShinde try with post(self, request, format=None) if you are not sending filename in url
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.