使用requests / django rest框架发送,接收,保存本地图像文件

时间:2016-11-07 16:22:59

标签: python django django-rest-framework python-requests

我想从服务器/客户端(使用requests lib)发送http(例如requests.post)图像文件,并使用django rest框架应用程序接收/保存这些文件。我该怎么做?

其次,我想知道如何从一般的requests.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)

我已经尝试了一段时间了。非常感谢您的帮助!谢谢!

1 个答案:

答案 0 :(得分:1)

我找到了一个完全符合我需求的解决方案。由于我只发现了发送或接收部分的贡献,我将尝试将所有内容放在一起。

由于更灵活,我的方法是在分离的请求中传输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

接收方需要运行服务器(dev的内置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()

如果您不同意或认为可以改进,请(!)评论/回答。谢谢!