Вот мой быдлокод для загрузки файлов:
#!/usr/bin/python3
import dropbox
from datetime import datetime
import os
import subprocess
import shutil
import glob
import logging
#Get name of temporal folder - year
Year = datetime.strftime(datetime.now(), "%Y")
#Adjustment script
#=================================================
#Get token:
TOKEN = "000000000"
#User
USER = str(subprocess.check_output(['whoami']))[2:-3]
#Path of temporal folder
csvFold="/home/" + USER + "/RMS_data/UFOOrbit_files_" + Year
#Create csvFold (True or False)?
flag=False
#Folder for log-files:
Logfiles="/home/" + USER + "/RMS_data/Dropbox_logs"
#Folder with files for upload
targetPattern = "/home/" + USER + "/RMS_data/ArchivedFiles/*/*_" + Year + "*.csv"
#Format of uploaded files
form = '.csv'
#Get name of Dropbox folder
DxFold = '/' + Year
#=================================================
#Path for temporal Folder
temp_fold = csvFold + '/temp'
#Logging: https://python-scripts.com/logging-python
#Create log's folder
if os.path.exists(Logfiles):
print("Log folder for Dx exist")
else:
print("Create Dx log folder")
os.mkdir(Logfiles)
#Get name for log folder
logname = datetime.strftime(datetime.now(), "%Y.%m.%d.-%H.%M.%S") + '_YD_upload.log'
print("Log file: " + logname + " created")
#Config logger
logging.basicConfig(level=logging.INFO, filename=os.path.join(Logfiles, logname), format='%(asctime)s %(levelname)s:%(message)s')
#Create folder csvFold
if os.path.exists(csvFold):
logging.info("Folder UFOOrbit exist")
print("Folder UFOOrbit exist")
else:
os.mkdir(csvFold)
#Copy csv-files to csvFold: https://coderoad.ru/296173/
files = glob.iglob(os.path.join(targetPattern))
for file in files:
if os.path.isfile(file):
shutil.copy2(file, csvFold)
#Check exist temporal folder
if os.path.exists(temp_fold):
shutil.rmtree(temp_fold)
#Connect to Dropbox
dbx = dropbox.Dropbox(TOKEN)
#Check and refresh TOKEN
dbx.check_and_refresh_access_token()
#Create Dropbox-disk folder
#Check folder
flag1 = False
# List file items in folder
for entry in dbx.files_list_folder('').entries:
if (entry.path_display == DxFold):
flag1 = True
print('Folder Dx exist!')
logging.info('Folder Dx exist!')
'''
#https://practicaldatascience.co.uk/data-science/how-to-use-the-dropbox-api-with-python
sharedlink = dbx.sharing_get_shared_links(DxFold).links[0].url
print('URL:\n', sharedlink)
logging.info('URL:')
logging.info(sharedlink)
'''
#Create folder
if (flag1 == False):
print('Create Dx folder!')
logging.info('Create Dx folder!')
dbx.files_create_folder(DxFold)
'''
#Share cloud folder
shared_link_metadata = dbx.sharing_create_shared_link(DxFold).url
print('URL:\n', shared_link_metadata)
logging.info('URL:')
logging.info(shared_link_metadata)
'''
#Sorting files
#===============================================================================================
#Types of files
Files_on_PC = []
UploadedFiles = []
#Get list of files on PC
for i in os.walk(csvFold):
Files_on_PC.append(i)
Files_on_PC = i[2]
#Get list of files on cloud
for entry in dbx.files_list_folder(DxFold).entries:
UploadedFiles.append(entry.name)
#Get list of files for upload
Files_for_upload = list(set(Files_on_PC) - set(UploadedFiles))
print('\n====================================================================================')
print('\nOn PC:', *Files_on_PC, sep = '\n')
print('\nOn Cloud:', *UploadedFiles, sep = '\n')
print('\nDifference:', *Files_for_upload, sep = '\n')
print('====================================================================================\n')
#Create temporal folder
os.mkdir(temp_fold)
#Move files for upload to temporal folder
for file in Files_for_upload:
shutil.copy2(csvFold + '/' + file, temp_fold)
#===============================================================================================
logging.info("Upload files...")
print("Upload files...")
#Upload a small file (150 MB or less)
for path_ in glob.glob(os.path.join(temp_fold, '*'+ form)):
with open(path_, 'rb') as file:
#Get filename
filename = os.path.splitext(os.path.basename(path_))[0]
print(filename + form)
logging.info(filename + form)
#Upload files
dbx.files_upload(file.read(), DxFold + '/' + filename + form)
print('Upload sucsessfull!')
logging.info('Upload sucsessfull!')
#Delete csvFold?
if flag:
logging.info("Folder UFOOrbit_files created")
print("Folder UFOOrbit_files created")
shutil.rmtree(temp_fold)
else:
logging.info("Remove temporal folders")
print("Remove temporal folders")
shutil.rmtree(csvFold)
logging.info("Done!")
print("Done!")
Все работает в питон версии 3.8.10 Однако, при запуске на RaspberryPi 3B+, на которой стоит версия 3.4. Выскакивает сообщение об ошибке:
Traceback (most recent call last):
File "/home/pi/UploadDx/DxRMS.py", line 85, in <module>
sharedlink = dbx.sharing_get_shared_links(DxFold).links[0].url
File "/home/pi/.local/lib/python3.4/site-packages/dropbox/base.py", line 4350, in sharing_get_shared_links
None,
File "/home/pi/.local/lib/python3.4/site-packages/dropbox/dropbox_client.py", line 345, in request
returned_data_type, obj, strict=False)
File "/home/pi/.local/lib/python3.4/site-packages/stone/backends/python_rsrc/stone_serializers.py", line 978, in json_compat_obj_decode
data_type, obj)
File "/home/pi/.local/lib/python3.4/site-packages/stone/backends/python_rsrc/stone_serializers.py", line 558, in json_compat_obj_decode_helper
return self.decode_struct(data_type, obj)
File "/home/pi/.local/lib/python3.4/site-packages/stone/backends/python_rsrc/stone_serializers.py", line 607, in decode_struct
self.decode_struct_fields(ins, all_fields, obj)
File "/home/pi/.local/lib/python3.4/site-packages/stone/backends/python_rsrc/stone_serializers.py", line 626, in decode_struct_fields
v = self.json_compat_obj_decode_helper(field_data_type, obj[name])
File "/home/pi/.local/lib/python3.4/site-packages/stone/backends/python_rsrc/stone_serializers.py", line 566, in json_compat_obj_decode_helper
data_type, obj)
File "/home/pi/.local/lib/python3.4/site-packages/stone/backends/python_rsrc/stone_serializers.py", line 844, in decode_list
for item in obj]
File "/home/pi/.local/lib/python3.4/site-packages/stone/backends/python_rsrc/stone_serializers.py", line 844, in <listcomp>
for item in obj]
File "/home/pi/.local/lib/python3.4/site-packages/stone/backends/python_rsrc/stone_serializers.py", line 556, in json_compat_obj_decode_helper
return self.decode_struct_tree(data_type, obj)
File "/home/pi/.local/lib/python3.4/site-packages/stone/backends/python_rsrc/stone_serializers.py", line 797, in decode_struct_tree
return self.decode_struct(subtype, obj)
File "/home/pi/.local/lib/python3.4/site-packages/stone/backends/python_rsrc/stone_serializers.py", line 607, in decode_struct
self.decode_struct_fields(ins, all_fields, obj)
File "/home/pi/.local/lib/python3.4/site-packages/stone/backends/python_rsrc/stone_serializers.py", line 626, in decode_struct_fields
v = self.json_compat_obj_decode_helper(field_data_type, obj[name])
File "/home/pi/.local/lib/python3.4/site-packages/stone/backends/python_rsrc/stone_serializers.py", line 563, in json_compat_obj_decode_helper
return self.decode_union(data_type, obj)
File "/home/pi/.local/lib/python3.4/site-packages/stone/backends/python_rsrc/stone_serializers.py", line 662, in decode_union
return data_type.definition(six.ensure_str(tag), val)
AttributeError: 'module' object has no attribute 'ensure_str'
Я закомментировал проблемный участок кода, содержащий
dbx.sharing_create_shared_link()
но хотелось бы, чтобы он работал.
ВОПРОС. Как это устранить на текущей версии питона? Устнавливать на малину ничего нельзя - в этом корень проблемы. Подскажите кто разбирается. Заранее спасибо! Всех с праздником!