[英]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.