현재 사용자가 파일을 업로드 할 수있는 앱이 있으며 웹 서버에 파일을 저장합니다. 고객은 이제 파일 저장 요구에 제 3 자 클라우드 호스팅 서비스를 사용하기로 결정했습니다. 회사는 자신의 서버에서 CRUD 작업을 수행하기 위해 자체 API를 가지고 있으므로 API를 테스트하는 스크립트를 작성하고 파일을 base64로 인코딩 된 JSON 페이로드로 API에 보냅니다. 스크립트는 정상적으로 작동하지만 지금은 어떻게이 기능을 장고에 구현해야하는지 정확히 파악하고 있습니다.서버에 업로드하는 대신 JSON을 통해 파일 보내기 Django
json_testing.py
import base64
import json
import requests
import magic
filename = 'test.txt'
# Open file and read file and encode it as a base64 string
with open(filename, "rb") as test_file:
encoded_string = base64.b64encode(test_file.read())
# Get MIME type using magic module
mime = magic.Magic(mime=True)
mime_type = mime.from_file(filename)
# Concatenate MIME type and encoded string with string data
# Use .decode() on byte data for mime_type and encoded string
file_string = 'data:%s;base64,%s' % (mime_type.decode(), encoded_string.decode())
payload = {
"client_id": 1,
"file": file_string
}
headers = {
"token": "AuthTokenGoesHere",
"content-type": "application/json",
}
request = requests.post('https://api.website.com/api/files/', json=payload, headers=headers)
print(request.json())
models.py
def upload_location(instance, filename):
return '%s/documents/%s' % (instance.user.username, filename)
class Document(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL)
category = models.ForeignKey(Category, on_delete=models.CASCADE)
file = models.FileField(upload_to=upload_location)
def __str__(self):
return self.filename()
def filename(self):
return os.path.basename(self.file.name)
이 사용자 대신 웹 서버에 어딘가에 파일을 저장하는, 파일을 업로드 할 때, 반복하는, 내가 base64로 원하는
파일을 인코딩하여 JSON 페이로드로 파일을 보낼 수 있습니다. 이것에 접근하는 가장 좋은 방법은 무엇이 될지에 대한 아이디어가 있습니까?
나는 이해할 수 없다. 이미 적절한 요청을하는 법을 알고 있습니다. 문제가 어디에 있습니까? – freakish
@freakish. 물리적으로 웹 서버에 파일을 저장하는 대신 파일을 인코딩하고 페이로드로 보내고 파일을 삭제하기 만하면됩니다. 파일을 업로드 한 다음 인코딩을 수행하고 JSON 페이로드로 보낸 다음 파일을 삭제해야합니까? 웹 서버에 파일을 저장하지 않고 메모리에 파일을 인코딩 할 수있는 방법이 있는지 궁금합니다. – nastyn8
그냥 dhango app에서 스크립트를 호출하는 대신 u를 사용하는 대신 스크립트를 사용합니다. .. –