How to copy a file box URL rooted in folder directory? - python

I need to create an script that helps me pick the URL from a Box file that has a path in my computer.
I've the Box desktop application installed.
Like: C:\Users\Thiago.Oliveira\Box\
I've created this script:
# Providing the folder path
origin = r'C:\\Users\\Thiago.Oliveira\\Box\\XXXXXXX.xlsx'
target = f'C:\\Users\\Thiago.Oliveira\\Box\\XXXXXXX{datetime.date.today()}.xlsx'
# Fetching the list of all the files
shutil.copy(origin, target)
print("Files are copied successfully")
This helps me out to copy and rename the file for this box folder. But I also want to pick up the URL from the newly created file so I can send it over in an e-mail.
I haven't found anything that would help me with this.
Is this possible?

Yes, you can, see the example below.
This example is using the box python sdk, and this is a JWT auth application script.
After uploading the file, the box sdk returns a file object, which has many properties.
I'm not sure what you mean by "pick up the URL", it could be the direct download URL of the file or a shared link.
The example is for the direct download URL.
To get the destination FOLDER_ID, you can look at the browser URL when you open the folder on the box.com app.
e.g.:image of demo folder url in browser
from datetime import date
import os
from boxsdk import JWTAuth, Client
def main():
auth = JWTAuth.from_settings_file(".jwt.config.json")
auth.authenticate_instance()
client = Client(auth)
folder_id = "163422716106"
user = client.user().get()
print(f"User: {user.id}:{user.name}")
folder = client.folder(folder_id).get()
print(f"Folder: {folder.id}:{folder.name}")
with open("./main.py", "rb") as file:
basename = os.path.basename(file.name)
file_name = os.path.splitext(basename)[0]
file_ext = os.path.splitext(basename)[1]
file_time = date.today().strftime("%Y%m%d")
box_file_name = file_name + "_" + file_time + file_ext
print(f"Uploading {box_file_name} to {folder.name}")
box_file = folder.upload_stream(file, box_file_name)
box_file.get()
print(f"File: {box_file.id}:{box_file.name}")
print(f"Download URL: {box_file.get_download_url()}")
if __name__ == "__main__":
main()
print("Done")
Resulting in:
User: 20344589936:UI-Elements-Sample
Folder: 163422716106:Box UI Elements Demo
Uploading main_20230203.py to Box UI Elements Demo
File: 1130939599686:main_20230203.py
Download URL: https://public.boxcloud.com/d/1/b1!5CgJ...fLc./download

Related

run download link and unzip to a folder in python with a url that stores a variable

How could a script in python be made that, through a value entered by the user through the console in an input, is replaced in a specific url of a repository to be able to download a .zip and when it is downloaded automatically, a folder is created where it is entered and would unpack, for example:
Given two random github urls:
https://github.com/exercism/python/archive/refs/heads/bobahop-patch-1.zip
https://github.com/exercism/python/archive/refs/heads/bobahop-patch-2.zip
The user could enter "patch-1" or "patch-2" by console and this value would be replaced in the url and in turn the link would be executed and the .zip it contains would be downloaded to the repository. Simultaneously, a folder with any name would be created (the value entered by the user in the console, for example) and the downloaded .zip would be moved to that folder and once there it would be decompressed.
Python has
standard module urllib to get/download data from web page urllib.request.urlretrieve()
standard moduel os to create folder os.makedirs() and move/rename file os.rename()
standard module zipfile to compress/uncompress .zip file
import os
import urllib.request
import zipfile
#user_input = input("What to download: ")
user_input = 'patch-1'
pattern = 'https://github.com/exercism/python/archive/refs/heads/bobahop-{}.zip'
url = pattern.format(user_input)
filename = f"{user_input}.zip"
print('From:', url)
print(' To:', filename)
urllib.request.urlretrieve(url, filename)
# ---
destination_folder = user_input
print('Create folder:', destination_folder)
os.makedirs(destination_folder, exist_ok=True)
# ---
print('Uncompress')
zip_file = zipfile.ZipFile(filename)
zip_file.extractall(destination_folder)
# ---
print("Move .zip to folder")
old_name = filename
new_name = os.path.join(destination_folder, filename)
os.rename(old_name, new_name)

Can i have two different sets of app configurations?

I have made a flask server REST API that does an upload to a specific folder.
The upload must comply to a specific file extension, and must be in a specific folder.
So i made these two app.configs:
app.config['UPLOAD_EXTENSIONS'] = ['.stp', '.step']
app.config['UPLOAD_PATH'] = 'uploads'
However, i want to make a new route, for a new upload of a specific file extension to another folder.
So can i have two sets of app.config['UPLOAD_EXTENSIONS'] and app.config['UPLOAD_PATH']?
One set will be for extension1 in folder1 and the other set for extension2 in folder2.
Try using the extension Flask-Uploads .
Or, proceeding from the file format, form a subdirectory in your UPLOAD_PATH.
import os
def select_directory(filename: str) -> str:
file_format = filename.split('.')[1]
your_path1 = 'path1'
your_path2 = 'path2'
if file_format in ('your format1', 'your format2'):
full_path = os.path.join(app.config['UPLOAD_FOLDER'], your_path1, filename)
else:
full_path = os.path.join(app.config['UPLOAD_FOLDER'], your_path2, filename)
return full_path

How to Download a directory on Google Drive using Python?

service = self.auth()
items = self.listFilesInFolder(downLoadFolderKey)
for item in items:
file_id = (item.get('id'))
file_name = (item.get('name'))
request = service.files().get_media(fileId=file_id)
fh = io.BytesIO()
downloader = MediaIoBaseDownload(fh, request)
done = False
while done is False:
status, done = downloader.next_chunk()
print ("Download %d%%." % int(status.progress() * 100) + file_name)
filepath = fileDownPath + file_name
with io.open(filepath, 'wb') as f:
fh.seek(0)
f.write(fh.read())
I am using Google Drive API v3.
I am trying to download a full directory. But the problem is the directory itself contains folders and when I try to run this bit of code. This error happens.
<HttpError 403 when requesting https://www.googleapis.com/drive/v3/files/1ssF0XD8pi6oh6DXB1prIJPWKMz9dggm2?alt=media returned "Only files with binary content can be downloaded. Use Export with Google Docs files.">
The error I figure is due to it trying to download the folders, within the directory. But how do I download the full directory?
P.S The directory changes so I cannot hard code file IDs and then download the files.
I believe your situation and goal as follows.
By items = self.listFilesInFolder(downLoadFolderKey), you have already been able to retrieve all file and folder list including the subfolders under the specific folder.
items include the mimeType for each files and folders.
In your issue, when the folder is used in the loop, the error occurs.
You want to remove this error.
For this, how about this answer?
Modification point:
When the mimeType is included in items of items = self.listFilesInFolder(downLoadFolderKey), the folder can be checked by the mimeType. The mimeType of folder is application/vnd.google-apps.folder.
From your script, I think that when the Google Docs file (Spreadsheet, Document, Slides and so on) is downloaded with the method of "Files: get", the same error occurs.
In order to download the Google Docs files, it is required to use the method of "Files: export".
When above point is reflected to your script, how about the following modification?
Modified script:
From:
request = service.files().get_media(fileId=file_id)
To:
file_mimeType = (item.get('mimeType'))
if file_mimeType == 'application/vnd.google-apps.folder':
continue
request = service.files().export_media(fileId=file_id, mimeType='application/pdf') if 'application/vnd.google-apps' in file_mimeType else service.files().get_media(fileId=file_id)
In this modification, at first, please confirm whether the file mimeType to items of items = self.listFilesInFolder(downLoadFolderKey) is included, again. By this, the folder can be skipped and also, Google Docs files and the files except for Google Docs can be downloaded using the value of mimeType.
In this modification, as a sample modification, Google Docs files are downloaded as the PDF file. If you want to change the output mimeType, please modify mimeType='application/pdf'.
References:
G Suite and Drive MIME Types
Files: get
Files: export

How to get the parent folder of a google docs resource?

Using Python gdata in my Goggle App Engine Application I am trying to copy a google docs resource and put the copy in the same folder as the source file. The CopyResource method that I use put the copy at the root level.
Would you know how to query Google Docs to have the list of folders/collections in which a file is?
import gdata.docs.service
import gdata.docs.client
...
doc_service = gdata.docs.client.DocsClient()
doc_service.ClientLogin('username', 'abc123', 'my app name')
try:
doc = doc_service.GetResourceById(resourceId)
newdoc = doc_service.CopyResource(doc, filename)
# newdoc is copied at the root level of Google Drive
# need to move it where the source file is located.
newdocid = newdoc.id.text.decode('utf-8').split('%3A')[1]
# would like here to have my newly copied document
# moved to the same directory as the source one.
# assuming the source is only in one folder.
except gdata.client.RequestError, inst:
logging.info('Copy Error: %s', inst.body)

How to repeat a set of tasks for each file stored in a folder using Selenium + Python?

I'm working on an Automation Project where I have to upload a file from the local folder, do some tasks and then repeat the same set of tasks by choosing the next file from the local folder. I have about 20 files stored in the local folder. I have successfully completed the work for a single file, but I don't know how to do it for multiple files by choosing them one by one in a sequence. It's my first project in Python, I'm stuck. The code:
def file_upload(self):
upload_btn = driver.find_element_by_xpath("//") # The Upload Button
upload_btn.send_keys('File location in the local folder')
def job1(self):
#set of actions
def job2(self):
#set of actions
if __name__ == '__main__':
file_upload()
job1()
job2()
You would first need to iterate over the files in a directory, for which I'd go for os.listdir(). Then, you need to upload a specific file by sending the absolute path to a file to the "upload" input. Then, it depends on the website and your use case - do you need to do anything extra before uploading the next file, do you stay on the same page or need to navigate back to the "upload" page?
To summarize, you would have something like:
import os
def file_upload(filename):
upload_btn = driver.find_element_by_xpath("//") # The Upload Button
upload_btn.send_keys(filename)
directory_path = '/path/to/your/directory'
for filename in os.listdir(directory_path):
file_upload(os.path.join(directory_path, filename))
# get back to the "upload" page here?
you can import glob and create a loop for each file
import glob
def file_upload(self):
path_of_directory="your path to the files to upload"
for filename in glob.glob(path_of_directory):
upload_btn = driver.find_element_by_xpath("//") # The Upload Button
upload_btn.send_keys(filename)
def job1(self):
#set of actions
def job2(self):
#set of actions
if __name__ == '__main__':
file_upload()
job1()
job2()
edit:
def file_upload(self):
upload_btn = driver.find_element_by_xpath("//") # The Upload Button
upload_btn.send_keys('File location in the local folder')
def job1(self):
#set of actions
def job2(self):
#set of actions
if __name__ == '__main__':
path_of_directory="your path to the files to upload"
for filename in glob.glob(path_of_directory):
file_upload()
job1()
job2()

Categories

Resources