[英]send, receive, save local image file with requests / django rest framework
我想从服务器/客户端(带有请求lib )中发送(例如,requests.post)图像文件,并使用django rest framework应用接收/保存这些文件。 我该怎么做呢?
其次,我想知道一般如何从request.post发送的QueryDict中提取部分。 更具体的说:如何从这组数据中解析并保存_io-Object?
# sending app
file = "path/to/image.jpg"
data = open(file, 'rb')
files = {
'json': (None, crawlingResultConnectionsJson, 'application/json'),
'file': (os.path.basename(file), open(file, 'rb'), 'application/octet-stream')
}
url = "http://127.0.0.1:8000/result/" # receiving/saving django rest framework app
r = requests.post(url, files=files)
我已经尝试了很长时间。 您的帮助将不胜感激! 谢谢!
我找到了完全适合我需要的解决方案。 因为我只发现了发送或接收部分的贡献,所以我将尝试将所有内容放在这里。
由于具有更大的灵活性,我的方法是在单独的请求中传输json和图像。 以下两个应用程序是完全独立的。
发送方的操作如下(无需服务器的应用程序):
from django.core.serializers.json import DjangoJSONEncoder
import requests # http://docs.python-requests.org/en/master/
import datetime # in case...
import json
### send image stuff ###
urlImages = "http://127.0.0.1:8000/receive-images/"
file = "C:\\path\\to\\filename.jpg" # "\\" windows machine...
# this will probably run in a loop or so to process a bunch of images
with open(file, 'rb') as f:
filename = "filename.jpg"
files = {'file': (filename, f)}
r = requests.post(urlImages, files=files)
print(r) # some logging here
### send data stuff ###
data = data # python data - lists, dicts, whatever
json = json.dumps(data, cls=DjangoJSONEncoder) # DjangoJSONEncoder handles datetime fields
urlData = "http://127.0.0.1:8000/receive-data/"
headers = {'content-type': 'application/json'}
r = requests.post(urlData, json, headers=headers)
print(r) # some logging here
接收方需要运行一台服务器(用于开发的内置django服务器,在生产环境中使用WSGInterface进行apache安装),并且已安装以下代码: http : //www.django-rest-framework.org/
最后,我们有两个视图来处理请求:
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status
from .api_controller import ApiController
from django.core.files.storage import default_storage
class ReceiveImages(APIView): # make sure to nail down corresponding url-confs
def post(self, request, format=None):
file = request.data.get('file')
filename = str(file)
with default_storage.open('images/' + filename, 'wb+') as destination:
for chunk in file.chunks():
destination.write(chunk)
return Response("ok", status=status.HTTP_200_OK)
class ReceiveData(APIView): # make sure to nail down corresponding url-confs
def post(self, request, format=None):
json = request.data
ApiController().createDataIfNotExists(json)
# As my json is quite complex,
# I've sourced out the DB-interactions to a controller-like class (coming
# from PHP symfony :)) with heavy use of the great
# MyModel.objects.get_or_create() method. Also the strptime() method is used
# to convert the datetime fields. This could also go here...
return Response("ok", status=status.HTTP_200_OK)
针对https://stackoverflow.com/a/30195605/6522103使用chunk()
如果您不同意或认为可以改进,请发表评论! 谢谢!!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.