【问题标题】:send, receive, save local image file with requests / django rest framework使用 requests / django rest framework 发送、接收、保存本地图像文件
【发布时间】:2017-03-21 01:42:26
【问题描述】:

我想从服务器/客户端(使用 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)

我已经尝试了一段时间了。您的帮助将不胜感激!谢谢!

【问题讨论】:

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


    【解决方案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
    

    接收方需要运行一个服务器(用于开发的内置 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()

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-05-07
      • 2021-05-12
      • 2018-08-26
      • 2017-01-19
      • 1970-01-01
      • 1970-01-01
      • 2017-07-23
      相关资源
      最近更新 更多