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