python - Django 怎么自動同步某個文件夾內的圖片至數據庫?
問題描述
接觸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()
但是會報錯
問題解答
回答1:需要配置crontab來執行定期任務。
相關文章:
1. 關docker hub上有些鏡像的tag被標記““This image has vulnerabilities””2. docker鏡像push報錯3. Docker for Mac 創建的dnsmasq容器連不上/不工作的問題4. 利用IPMI遠程安裝centos報錯!5. node.js - mongodb查找子對象的名稱為某個值的對象的方法6. html5和Flash對抗是什么情況?7. docker 下面創建的IMAGE 他們的 ID 一樣?這個是怎么回事????8. phpstudy8.1沒集成mysql-front9. javascript - 在 model里定義的 引用表模型時,model為undefined。10. 運行python程序時出現“應用程序發生異常”的內存錯誤?

網公網安備