Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
420 views
in Technique[技术] by (71.8m points)

Django 怎么自动同步某个文件夹内的图片至数据库?

接触Django时间不长,不是很懂Django。希望有大神帮助。

最近在做一个小项目,其中有一个步骤是:
某个程序会不断地生成一些图片,存放在路径C:UsersadminPictures下,现在想让程序自动地、随时把这些图片同步到Django APP 的数据库,而不是通过Django 的 Admin面板手工上传图片,请问应该怎么做呢?

目前定义的models:

models.py

from __future__ import unicode_literals

from django.db import models
from django.conf import settings
from django.utils.encoding import python_2_unicode_compatible

# Create your models here.

@python_2_unicode_compatible
class Image(models.Model):
    title = models.CharField(max_length=250, blank=True)
    original = models.ImageField(upload_to=settings.IMAGE_PREFIX, default='/tmp/none.jpg')
    
    def __str__(self):
        return self.title

尝试着写了一个脚本:

import os
from gallery.models import Image    
import django

django.setup()
path = r"C:UsersadminPictures"

for filename in os.listdir(path):
    filePath = os.path.join(path, filename)
    thisFile = open(filePath, 'rb')
    new_img = Image(original=thisFile, title=filename)
    new_img.save()

但是会报错
Cmd下运行结果


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

需要配置crontab来执行定期任务。


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...