我想自动将我的python脚本中的文件上传到我的Dropbox帐户。无论如何我只能通过用户/传递来找到这个。我在Dropbox SDK中看到的所有内容都与具有用户互动的应用相关。我只是想做这样的事情:
https://api-content.dropbox.com/1/files_put/ /用户=我&安培;通过=嗒嗒
答案 0 :(得分:51)
重要说明:此答案已弃用,因为Dropbox现在使用v2 API 有关当前API版本解决方案,请参阅@SparkAndShine的答案
感谢@smarx的上述答案!我只想澄清其他任何试图这样做的人。
确保首先安装Dropbox模块,pip install dropbox
。
在“App Console”中使用您自己的保管箱帐户创建应用。 (https://www.dropbox.com/developers/apps)
只是为了记录我用以下内容创建了我的应用程序:
一个。应用类型为“Dropbox API APP”。
湾数据访问类型为“文件和数据存储”
℃。文件夹访问为“我的应用程序需要访问Dropbox上已有的文件”。 (即:权限类型为“Full Dropbox”。)
然后点击“生成访问令牌”按钮并剪切/粘贴到下面的python示例中代替<auth_token>
:
import dropbox
client = dropbox.client.DropboxClient(<auth_token>)
print 'linked account: ', client.account_info()
f = open('working-draft.txt', 'rb')
response = client.put_file('/magnum-opus.txt', f)
print 'uploaded: ', response
folder_metadata = client.metadata('/')
print 'metadata: ', folder_metadata
f, metadata = client.get_file_and_metadata('/magnum-opus.txt')
out = open('magnum-opus.txt', 'wb')
out.write(f.read())
out.close()
print metadata
答案 1 :(得分:45)
@Christina的答案基于Dropbox APP v1,现已弃用,将于2017年6月28日关闭。 (有关详细信息,请参阅here。)
APP v2于2015年11月推出,更简单,更一致,更全面。
以下是APP v2的源代码。
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import dropbox
class TransferData:
def __init__(self, access_token):
self.access_token = access_token
def upload_file(self, file_from, file_to):
"""upload a file to Dropbox using API v2
"""
dbx = dropbox.Dropbox(self.access_token)
with open(file_from, 'rb') as f:
dbx.files_upload(f.read(), file_to)
def main():
access_token = '******'
transferData = TransferData(access_token)
file_from = 'test.txt'
file_to = '/test_dropbox/test.txt' # The full path to upload the file to, including the file name
# API v2
transferData.upload_file(file_from, file_to)
if __name__ == '__main__':
main()
源代码托管在GitHub上,here。
答案 2 :(得分:10)
这是我使用API v2(和Python 3)的方法。我想上传文件并为其创建共享链接,我可以通过电子邮件发送给用户。它基于sparkandshine的例子。注意我认为当前的API文档有一个小错误,sparkandshine已经纠正。
import pathlib
import dropbox
import re
# the source file
folder = pathlib.Path(".") # located in this folder
filename = "test.txt" # file name
filepath = folder / filename # path object, defining the file
# target location in Dropbox
target = "/Temp/" # the target folder
targetfile = target + filename # the target path and file name
# Create a dropbox object using an API v2 key
d = dropbox.Dropbox(your_api_access_token)
# open the file and upload it
with filepath.open("rb") as f:
# upload gives you metadata about the file
# we want to overwite any previous version of the file
meta = d.files_upload(f.read(), targetfile, mode=dropbox.files.WriteMode("overwrite"))
# create a shared link
link = d.sharing_create_shared_link(targetfile)
# url which can be shared
url = link.url
# link which directly downloads by replacing ?dl=0 with ?dl=1
dl_url = re.sub(r"\?dl\=0", "?dl=1", url)
print (dl_url)
答案 3 :(得分:5)
验证对Dropbox API的调用的唯一方法是使用OAuth,这涉及用户授予您的应用的权限。我们不允许第三方应用处理用户凭据(用户名和密码)。
如果这仅适用于您的帐户,请注意您可以轻松获取自己帐户的OAuth令牌并使用该帐户。请参阅https://www.dropbox.com/developers/blog/94/generate-an-access-token-for-your-own-account。
如果这是针对其他用户的,则他们需要通过浏览器对您的应用进行一次授权,以获取OAuth令牌。一旦你有了令牌,你可以继续使用它,所以每个用户只需要这样做一次。
答案 4 :(得分:2)
很抱歉,如果我遗漏了一些东西,但你不能只为你的操作系统下载Dropbox应用程序,然后保存文件(在windows中):
C:\Users\<UserName>\Dropbox\<FileName>
我刚刚停止了一个python程序来保存文本文件,检查了我的保管箱,它保存得很好。
答案 5 :(得分:2)
import dropbox
access_token = '************************'
file_from = 'index.jpeg' //local file path
file_to = '/Siva/index.jpeg' // dropbox path
def upload_file(file_from, file_to):
dbx = dropbox.Dropbox(access_token)
f = open(file_from, 'rb')
dbx.files_upload(f.read(), file_to)
upload_file(file_from,file_to)
答案 6 :(得分:0)
对于 Dropbox Business API,下面的 Python 代码有助于将文件上传到 Dropbox。
def dropbox_file_upload(access_token,dropbox_file_path,local_file_name):
'''
The function upload file to dropbox.
Parameters:
access_token(str): Access token to authinticate dropbox
dropbox_file_path(str): dropboth file path along with file name
Eg: '/ab/Input/f_name.xlsx'
local_file_name(str): local file name with path from where file needs to be uploaded
Eg: 'f_name.xlsx' # if working directory
Returns:
Boolean:
True on successful upload
False on unsuccessful upload
'''
try:
dbx = dropbox.DropboxTeam(access_token)
# get the team member id for common user
members = dbx.team_members_list()
for i in range(0,len(members.members)):
if members.members[i].profile.name.display_name == logged_in_user:
member_id = members.members[i].profile.team_member_id
break
# connect to dropbox with member id
dbx = dropbox.DropboxTeam(access_token).as_user(member_id)
# upload local file to dropbox
f = open(local_file_name, 'rb')
dbx.files_upload(f.read(),dropbox_file_path)
return True
except Exception as e:
print(e)
return False
答案 7 :(得分:-2)
以下是使用Windows中的python在dropbox上上传livevideo的代码。 希望这会对你有所帮助。
import numpy as np
import cv2
import dropbox
import os
from glob import iglob
access_token = 'paste your access token here' #paste your access token in-between ''
client = dropbox.client.DropboxClient(access_token)
print 'linked account: ', client.account_info()
PATH = ''
cap = cv2.VideoCapture(0)
# Define the codec and create VideoWriter object
fourcc = cv2.VideoWriter_fourcc(*'XVID')
out = cv2.VideoWriter('C:\python27\output1.avi',fourcc, 20.0, (640,480))
#here output1.avi is the filename in which your video which is captured from webcam is stored. and it resides in C:\python27 as per the path is given.
while(cap.isOpened()):
ret, frame = cap.read()
if ret==True:
#frame = cv2.flip(frame,0) #if u want to flip your video
# write the (unflipped or flipped) frame
out.write(frame)
cv2.imshow('frame',frame)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
else:
break
# Release everything if job is finished
cap.release()
out.release()
cv2.destroyAllWindows()
for filename in iglob(os.path.join(PATH, 'C:/Python27/output1.avi')):
print filename
try:
f = open(filename, 'rb')
response = client.put_file('/livevideo1.avi', f)
print "uploaded:", response
f.close()
#os.remove(filename)
except Exception, e:
print 'Error %s' % e
答案 8 :(得分:-2)
以下是使用Windows中的python在您的保管箱帐户上传现有视频的代码。
希望这会对你有所帮助。
# Include the Dropbox SDK
import dropbox
# Get your app key and secret from the Dropbox developer website
app_key = 'paste your app-key here'
app_secret = 'paste your app-secret here'
flow = dropbox.client.DropboxOAuth2FlowNoRedirect(app_key, app_secret)
# Have the user sign in and authorize this token
authorize_url = flow.start()
print '1. Go to: ' + authorize_url
print '2. Click "Allow" (you might have to log in first)'
print '3. Copy the authorization code.'
code = raw_input("Enter the authorization code here: ").strip()
# This will fail if the user enters an invalid authorization code
access_token, user_id = flow.finish(code)
client = dropbox.client.DropboxClient(access_token)
print 'linked account: ', client.account_info()
f = open('give full path of the video which u want to upload on your dropbox account(ex: C:\python27\examples\video.avi)', 'rb')
response = client.put_file('/video1.avi', f) #video1.avi is the name in which your video is shown on your dropbox account. You can give any name here.
print 'uploaded: ', response
folder_metadata = client.metadata('/')
print 'metadata: ', folder_metadata
f, metadata = client.get_file_and_metadata('/video1.avi')
out = open('video1.avi', 'wb')
out.write(f.read())
out.close()
print metadata
现在上传图片,将使用相同的代码。
仅编写您要上传的图像文件名,例如:image.jpg代替视频名称。同时更改video1.avi的名称并为图片写名称,您的上传图片将在您的保管箱中显示为ex:image1.jpg。