Bunny.net is a well-known CDN and storage among developers. It provides you with a lot of handy features like, for example, auto image resizing. It's fast and reliable. Here is my python snippet on how to upload a file to the storage.
You can use just requests, but I prefer unofficial Python library. So let's install it first.
pip install bunnycdnpython
Here is the entire code. I will describe it in details below.
from BunnyCDN.Storage import Storage
def upload_file(client, filename, storage_path, local_upload_file_path=None):
return client.PutFile(
filename,
storage_path=storage_path,
local_upload_file_path=local_upload_file_path
)
# Configuration from the BunnyNet dashboard
# 'api_key'. It's your password from bunny.net storage API. Read section below.
# 'zone_name'. Name of your storage zone
# 'zone_region'. Region name. You can find it in bunny.net page "FTP & API Access" > Hostname.
# For example in "ny.storage.bunnycdn.com" "ny" is your zone_region.
bunny_storage_config = {
"api_key": "",
"zone_name": "",
"zone_region": ""
}
bunny_storage_client = Storage(
bunny_storage_config["api_key"],
bunny_storage_config["zone_name"],
bunny_storage_config["zone_region"]
)
# Let's upload image to the Storage
upload_file(
bunny_storage_client,
"article-og-image.jpeg",
"/articles/bunny-net-file-upload/article-og-image.jpeg",
"/home/abstractkitchen/images/"
)
As you can see, the function upload_file takes four arguments:
Here is another approach to organizing your code. I like it more. You can then add more wrappers to work with Bunny.net.
from BunnyCDN.Storage import Storage
class BunnyStorage:
def __init__(self, api_key, zone_name, zone_region):
self.storage = Storage(api_key, zone_name, zone_region)
def upload_file(self, filename, storage_path, local_upload_file_path=None):
return self.storage.PutFile(
filename,
storage_path=storage_path,
local_upload_file_path=local_upload_file_path
)
Then you can use it anywhere in your code just like that.
bunny_storage_client = BunnyStorage("api-key", "zone-name", "zone-region")
bunny_storage_client.upload_file(
"article-og-image.jpeg",
"/articles/bunny-net-file-upload/article-og-image.jpeg",
"/home/abstractkitchen/images/")
1. Login to your bunny.net account.
2. Go to Edge Storage page.
3. Open your storage zone page.
4. On the left sidebar click «FTP & API Access». You'll see something like this.
Here «Password» is your api_key. «ny» is zone_region.
Handy links: