如何编写没有模型的 Django REST Api 以使用请求发送文件 [英] How to write Django REST Api without model to send a file using Requests
问题描述
我想编写一个没有模型的rest方法,以便我可以使用python请求模块发送一个csv文件.应从服务器远程访问此 csv 文件.
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.
例如——我已使用请求登录到我的项目并获取 cookie 和标头,以便我可以将其传递给以下请求方法..
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)
所以这个 url 应该是:调用那个 rest 方法.
So this url should be : call for that rest method.
views.py 文件:
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)
请注意 - 我正在使用请求模块发送一个 csv 文件.
Just to note - I am sending a csv file using requests module.
谁能帮我写下这个rest方法?
Can anyone please help me on how to write this rest method?
推荐答案
普通 django 视图
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!"})
更新
# 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())
]
然后
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)
这篇关于如何编写没有模型的 Django REST Api 以使用请求发送文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!