尝试使用django存储爬取的文件

本文介绍了如何使用Django的ORM Model管理和保存从网络下载的文件资源,包括图片、音频等,通过两种方法:一是先保存到本地再关联;二是直接使用ContentFile处理二进制数组。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

从网上直接爬取资源后,如果资源是文件,比如图片、音频等,返回的数据是二进制数组,如果我们要保存,一般都是直接新开一个和资源类型相同的文件,并将得到的二进制数据直接写进文件。

如果我们需要让django的ORM Model 来管理我们下载的资源,那么model中需要有FileField这个字段,并且我们需要将要保存的文件和这个字段关联起来。

def _upload_to(instance, filename):
    pass

class NetSourceFile(models.Model):
    name = models.CharField(max_length=180)
    original_url = models.CharField(max_length=200)
    local_url = models.FileField(upload_to=_upload_to, max_length=200)

    def __str__(self):
        return "{}".format(self.name)

如上所示,下载的资源我们需要和local_url这个字段关联起来,在网上找了一大堆资料后,目前找到两种方式进行关联:

一种是先将文件保存到本地,在用打开本地文件的方式来进行关联关联,这种方式易懂,也简单粗暴。

import requests


url = 'http://xxxx.png'
source = requests.get(url)
if not source.status_code == 200 or not source.content:
    return

with open('temp.png', 'wb') as f:
    f.write(source.content)

reoppen = open('your_temp_path/xxx.png', 'rb')
django_file = File(reopen)
instance = NetSourceFile(
    name=file_name,
    original_url=url,
    local_url=django_file,
)
instance.save()

        
        

另一种是使用ContentFile,不用存临时文件,直接将二进制数组作为参数放在ContentFile里面

import requests
from django.core.files.base import ContentFile


url = 'http://xxxx.png'
source = requests.get(url)
if not source.status_code == 200 or not source.content:
    return

file_name ='xxx.png'
upload_file = ContentFile(source.content, name=file_name)
instance = NetSourceFile(
    name=file_name,
    original_url=url,
    local_url=upload_file,
)
instance.save()

        
        
以上是目前找到的两种保存方式,如果还有其它方式的,欢迎分享。

参考资源: https://docs.djangoproject.com/en/2.1/ref/files/file/#the-file-class

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值