Skip to main content

Does anyone have some sample code to upload a file with Python SDKGEN? (nothing fancy, just an small file, so I don’t need multipart uploads, etc).  I see the following in the docs :

parent_client.uploads.upload_file(
UploadFileAttributes(
name=get_uuid(), parent=UploadFileAttributesParentField(id="0")
),
generate_byte_stream(1024 * 1024),
)

This seems overly complex and I’m not sure how to implement it. Do I really need the generate_bye_steam line? why? And am I supposed to import the UploadFileAttributes and UploadFileAttributesParentField functions and call them? Yuck. In the old SDK I just did this:

new_file = box_client.folder(OUTPUT_FOLDERID).upload(file_name)

I spent an inordinate amount of time digging through the github repo and found `UploadFileAttributesParentField` and `UploadFileAttributes` in a `managers` module.

Once you have these functions imported you can use them in something like this:

 

import io
from box_sdk_gen.managers import UploadFileAttributes, UploadFileAttributesParentField
# other box_sdk_gen imports you may need...

def box_authentication():
# code to authenticate

class BoxAPI:
def __init__(self):
self.client = box_authentication()

# all your other functionality

def upload_file(self, content, folder_id, filename):
     buffer = io.BytesIO()
# code to write your content to the buffer, for example a DataFrame
content.to_csv(buffer, index=False)

uploaded_file = self.client.uploads.upload_file(
UploadFileAttributes(
name=filename,
parent=UploadFileAttributesParentField(id=folder_id)
),
buffer
)
return uploaded_file.entriest0].id

I’ve gotten this to work succesfully but something about diving into the libraries and parsing the response in this way (`uploaded_file.entriese0].id` seems very kludgy and documentation is non-existent beyond what you posted so I’m not sure if there is a “better” way or not?


Reply