简体   繁体   English

发送,接收,保存带有请求的本地图像文件/ Django Rest Framework

[英]send, receive, save local image file with requests / django rest framework

I'd like to http-send (eg requests.post) image files from servers/clients (with the requests lib ) and receive/save these files with a django rest framework app. 我想从服务器/客户端(带有请求lib )中发送(例如,requests.post)图像文件,并使用django rest framework应用接收/保存这些文件。 How do I do this? 我该怎么做呢?

Secondly I'd like to know how to extract parts from a QueryDict sent by requests.post in general. 其次,我想知道一般如何从request.post发送的QueryDict中提取部分。 And more specific: How do I parse and save the _io-Object from this set of data? 更具体的说:如何从这组数据中解析并保存_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)

I've tried quite a while now. 我已经尝试了很长时间。 Your help would be much appreciated! 您的帮助将不胜感激! Thanks! 谢谢!

I came to a solution that perfectly fits my needs. 我找到了完全适合我需要的解决方案。 As I only found contributions for either the sending OR the receiving part, I'll try to put everything together here. 因为我只发现了发送或接收部分的贡献,所以我将尝试将所有内容放在这里。

Due to more flexibility my approach is to transfer json and images in seperated requests. 由于具有更大的灵活性,我的方法是在单独的请求中传输json和图像。 The two following apps are completely independent. 以下两个应用程序是完全独立的。

The sending side does as follows (app with no server needed): 发送方的操作如下(无需服务器的应用程序):

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

The receiving side needs to run a server (built-in django server for dev, apache with the WSGInterface in production) and it has this chum installed: http://www.django-rest-framework.org/ 接收方需要运行一台服务器(用于开发的内置django服务器,在生产环境中使用WSGInterface进行apache安装),并且已安装以下代码: http : //www.django-rest-framework.org/

Finally we have two views to handle the requests: 最后,我们有两个视图来处理请求:

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)

using chunk() in respect to https://stackoverflow.com/a/30195605/6522103 针对https://stackoverflow.com/a/30195605/6522103使用chunk()

Please (!) comment/answer if you don't agree or think that this could be improved. 如果您不同意或认为可以改进,请发表评论! Thanks!! 谢谢!!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM