python - 将从 url 获取的二进制数据保存到 Django FileField 中

标签 python django python-2.7 django-1.7

是否有任何方法可以将从外部 url(在我的例子中是一个 excel 文件)获取的二进制数据保存到 Django FileField 中,并根据 django 项目设置将文件上传到目标?

class FileData(models.Model):
    excel_file = models.FileField(upload_to='excel_file_path')


import requests
url = 'https://www.example.getfile.com/file_id=234'
r = requests.get(url)
# How to store the binary data response to FileField?

感谢您的帮助。如果我的案例需要更多信息,也请告诉我。

最佳答案

您可以使用django.core.files.uploadedfile.SimpleUploadedFile将您的内容保存为模型实例的文件字段。

>>> import requests
>>> from django.core.files.uploadedfile import SimpleUploadedFile

>>> response = requests.get("https://www.example.getfile.com/file_id=234")

>>> excel_file = SimpleUploadedFile("excel.xls", response.content, content_type="application/vnd.ms-excel")
>>> file_data = FileData(excel_file=excel_file)
>>> file_data.save()

关于python - 将从 url 获取的二进制数据保存到 Django FileField 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31444923/

相关文章:

python - 捕获谷歌应用引擎日志输出

python - python 装饰器是否严格执行装饰器模式?

python - 在 NumPy 数组中为每个唯一元素选择一个随机索引,并考虑引用数组中缺失的元素

python - 如何使用 Celery 从 Python 代码动态添加/停止 worker

python - 如何删除列表中的重叠部分?

python - 是否可以在 Wagtail 页面中使用 prefetch_related 来检索相关的(父页面、子页面)?

带有多对多内联的 Django 模型表单集

python - OpenCV 2.4.9 VideoCapture() 在 Enthought Python 2.7 环境中无法读取视频文件

Python:将元组转换为二维数组

excel - 在 Excel 的列中搜索字母字符