首页 > 解决方案 > 使用 python 3 将图像从 Raspberry pi 上传到 Dropbox

问题描述

这个项目是为天空拍照,然后要遮住云彩,所以会有两张照片,一张是原始的,另一张是蒙版的。

我只想将相机 pi 拍摄的每张照片上传到 Dropbox。

这是主要代码:

import os
import sys
from datetime import datetime
from makebinary import makebinary
import dropbox


# enable switching to picamera from commandline call (pass in 'picamera')
if len(sys.argv) == 1:
    capture_method = 'gphoto'
else:
    capture_method = sys.argv[1]

basedir = '/home/pi/Pictures'
# The radius in pixels of the fisheye lens area, set to None if no fisheye lens
fisheye_radius = None

# capture an image with the specified method
if capture_method.lower() == 'gphoto':
    import subprocess
    out = subprocess.check_output(['gphoto2', '--capture-image-and-download'])
    for line in out.split('\n'):
        if 'Saving file as' in line:
            file = line.split(' ')[3]
            break
    else:
        raise Exception('GPhoto image capture and save unsuccessful.')
elif capture_method.lower() == 'picamera':
    from picamera import PiCamera
    from time import sleep

    # open the camera and take the latest image
    file = 'latest.jpg'
    camera = PiCamera()
    camera.start_preview()
    sleep(2)             # wait for the camera to initialise
    camera.capture(file) # capture and save an image to 'file'
else:
    raise Exception("Invalid capture method {}. Use 'gphoto' or 'picamera'."
                    .format(capture_method))

# capture the timestamp
now = datetime.now()
# create the relevant folders if they don't already exist
os.makedirs(basedir + now.strftime("%Y/%m/%d"), exist_ok=True)

# move the new image to within its relevant folder with a timestamped filename
new_file = basedir + now.strftime("%Y/%m/%d/%Y-%m-%d-%H-%M-%S.jpg")
os.rename(file, new_file)

# process as desired (compute cloud coverage and mask image)
makebinary(new_file, fisheye_radius)

到目前为止,我已经尝试过这段代码:

with open(new_file, 'rb') as f:
    dbx = dropbox.Dropbox('Token)
    dbx.files_upload(f.read(),'/image.jpg')
f.close()

但是我只是将一张图片上传到 Dropbox 中,当我再次尝试再次运行代码时,我收到了这个错误,这基本上意味着它已经在 Dropbox 中了。但我真正想要的是每次运行主代码时都上传新图片。

这是错误:

Traceback (most recent call last):
  File "/home/pi/DIY-sky-imager/capture_image.py", line 56, in <module>
    dbx.files_upload(f.read(),'/image.jpg')
  File "/usr/local/lib/python3.7/dist-packages/dropbox/base.py", line 2762, in files_upload
    f,
  File "/usr/local/lib/python3.7/dist-packages/dropbox/dropbox.py", line 340, in request
    user_message_locale)
dropbox.exceptions.ApiError: ApiError('65464abaadc57d6d7862377638810', UploadError('path', UploadWriteFailed(reason=WriteError('conflict', WriteConflictError('file', None)), upload_session_id='AAAABR7Z7FHkkk9vyiuyw')))

标签: pythonraspberry-piclouddropbox

解决方案


使用Dropbox Python SDK 中files_upload方法path时,您可以通过提供给参数的值指定要上传的位置。

上传到 Dropbox 时出现path/conflict/file 错误表示上传失败,因为 "There's a file in the way"

查看您的代码,在这种情况下这似乎是预期的,因为您总是指定 value '/image.jpg',所以在第一次成功调用后,那里已经有一个文件。

相反,您应该更改代码以path对每个不同的文件使用不同的代码。


推荐阅读