【发布时间】:2013-04-16 22:38:40
【问题描述】:
我正在编写一个 Django 应用程序,它将获取特定 URL 的所有图像并将它们保存在数据库中。
但我不知道如何在 Django 中使用 ImageField。
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
我在一个视图中调用 download_imgs.py,例如
if form.is_valid():
url = form.cleaned_data['url']
spider(url)
【问题讨论】:
-
您要将图像保存为数据库中的 blob 还是图像路径
-
@mossplix - 无论哪种方式......但是如果我将图像保存为路径,那么我也希望在我的服务器上使用图像
-
@PauloBu - 我多次阅读该文件。但不知道如何继续
-
你是如何获取图片的?
标签: python django django-models