您的位置:首页技术文章
文章详情页

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

浏览:68日期:2022-08-23 17:39:36

问题描述

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

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

目前定义的models:

models.py

from __future__ import unicode_literalsfrom django.db import modelsfrom django.conf import settingsfrom django.utils.encoding import python_2_unicode_compatible# Create your models here.@python_2_unicode_compatibleclass 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 osfrom gallery.models import Image import djangodjango.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()

但是会报错python - Django 怎么自动同步某个文件夹内的图片至数据库?

问题解答

回答1:

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

标签: Python 编程
相关文章: