下载远程图像并保存到Django模型 [英] Download a remote image and save it to a Django model
本文介绍了下载远程图像并保存到Django模型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
但是,我没有看到如何使用ImageField Django。
Settings.py
MEDIA_ROOT = os.path。 join(PWD,../downloads/)
#处理从MEDIA_ROOT提供的媒体的URL。确保使用
#尾部斜线。
#示例:http://example.com/media/,htp://media.example.com/
MEDIA_URL ='/ downloads /'
models.py
class image_data(models.Model):
image_id = models.IntegerField()
source_id = models.IntegerField()
image = models.ImageField(upload_to ='images',null = True,blank = true)
text_ind = models.NullBooleanField()
prob = models.FloatField()
download_img.py
def spider(site):
PWD = os.path.dirname(os $路径(__ file__))
#site =http://en.wikipedia.org/wiki/Pune
hdr = {'User-Agent':'Mozilla / 5.0'}
outfolder = os.path.join(PWD,../downloads)
#outfolder =/ home / mayank / Desktop / dreamport / downloads
printMAYANK:+
req = urllib2.Request(site,headers = hdr)
page = urllib2.urlopen(req)
soup = bs(page)
tag_image = soup.findAll(img)
count = 1;
tag_image中的图像:
printImage:%(src)s%image
filename = image [src]。split(/)[ - 1]
outpath = os.path.join(outfolder,filename)
urlretrieve('http:'+ image [src],outpath)
im = img(image_id = count,source_id = image = outpath,text_ind = None,prob = 0)
im.save()
count = count + 1
我正在一个视图中调用download_imgs.py,如
如果form.is_valid():
url = form.cleaned_data ['url']
spider(url)
解决方案
文档永远是好的地方开始
class ModelWithImage(models.Model):
image = models.ImageField(
upload_to =图片',
)
更新
所以这个脚本有效。
- 循环图像下载
- 下载图片
- 保存到临时文件
- 应用于模特
- 保存模型
。
import requests
import tempfile
从django.core导入文件
#要下载的图像列表
image_urls = [
'http://i.thegrindstone.com/ wp-content / uploads / 2013/01 / how-to-get-awesome-back.jpg',
]
for image_url in image_urls:
# url
request = requests.get(image_url,stream = True)
#请求OK?
如果request.status_code!= requests.codes.ok:
#不,错误处理,跳过文件等etc
continue
#从url,用于稍后保存
file_name = image_url.split('/')[ - 1]
#创建一个临时文件
lf = tempfile.NamedTemporaryFile()
#在request.iter_content(1024 * 8)中读取块
中的流图像:
#如果没有更多的文件,那么停止
块:
break
#将图像块写入临时文件
lf.write(块)
#创建要保存图像的模型到
image = Image()
#将临时图像保存到模型#
#保存模型,确保它有效
image.image .save(file_name,files.File(lf))
一些参考链接:
I am writing a Django app which will fetch all images of particular URL and save them in the database.
But I am not getting on how to use ImageField in Django.
Settings.py
MEDIA_ROOT = os.path.join(PWD, "../downloads/")
# URL that handles the media served from MEDIA_ROOT. Make sure to use a
# trailing slash.
# Examples: "http://example.com/media/", "htp://media.example.com/"
MEDIA_URL = '/downloads/'
models.py
class images_data(models.Model):
image_id =models.IntegerField()
source_id = models.IntegerField()
image=models.ImageField(upload_to='images',null=True, blank=True)
text_ind=models.NullBooleanField()
prob=models.FloatField()
download_img.py
def spider(site):
PWD = os.path.dirname(os.path.realpath(__file__ ))
#site="http://en.wikipedia.org/wiki/Pune"
hdr= {'User-Agent': 'Mozilla/5.0'}
outfolder=os.path.join(PWD, "../downloads")
#outfolder="/home/mayank/Desktop/dreamport/downloads"
print "MAYANK:"+outfolder
req = urllib2.Request(site,headers=hdr)
page = urllib2.urlopen(req)
soup =bs(page)
tag_image=soup.findAll("img")
count=1;
for image in tag_image:
print "Image: %(src)s" % image
filename = image["src"].split("/")[-1]
outpath = os.path.join(outfolder, filename)
urlretrieve('http:'+image["src"], outpath)
im = img(image_id=count,source_id=1,image=outpath,text_ind=None,prob=0)
im.save()
count=count+1
I am calling download_imgs.py inside one view like
if form.is_valid():
url = form.cleaned_data['url']
spider(url)
解决方案
Documentation is always good place to start
class ModelWithImage(models.Model):
image = models.ImageField(
upload_to='images',
)
UPDATED
So this script works.
- Loop over images to download
- Download image
- Save to temp file
- Apply to model
- Save model
.
import requests
import tempfile
from django.core import files
# List of images to download
image_urls = [
'http://i.thegrindstone.com/wp-content/uploads/2013/01/how-to-get-awesome-back.jpg',
]
for image_url in image_urls:
# Steam the image from the url
request = requests.get(image_url, stream=True)
# Was the request OK?
if request.status_code != requests.codes.ok:
# Nope, error handling, skip file etc etc etc
continue
# Get the filename from the url, used for saving later
file_name = image_url.split('/')[-1]
# Create a temporary file
lf = tempfile.NamedTemporaryFile()
# Read the streamed image in sections
for block in request.iter_content(1024 * 8):
# If no more file then stop
if not block:
break
# Write image block to temporary file
lf.write(block)
# Create the model you want to save the image to
image = Image()
# Save the temporary image to the model#
# This saves the model so be sure that is it valid
image.image.save(file_name, files.File(lf))
Some reference links:
- requests - "HTTP for Humans", I prefer this to urllib2
- tempfile - Save temporay file and not to disk
- Django filefield save
这篇关于下载远程图像并保存到Django模型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文