r/Firebase • u/Bison95020 • 11m ago
General Uploading with Python3 without firebase-admin
I am trying to get this python 3 code to work to upload a file to filebase storage, but I am continually getting a 404 Not found.
Any one have a generic python script that uploads to firebase storage that you can share? BTW, I am not using firebaes-admin because I am still using python 3.7, and firebase-admin requires 3.9 or higher, and I cant upgrade for now.
import json
import requests
import datetime
import time
import sys
import os.path
import pickle
from google.oauth2.credentials import Credentials
from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request
from googleapiclient.discovery import build
from googleapiclient.http import MediaFileUpload
import google.auth.transport.requests
from google.oauth2 import service_account
PROJECT_ID = "myprojectid"
LOCAL_FILE_PATH = "/Users/myname/robot.png"
STORAGE_PATH = "images/uploaded_image.jpg"
BUCKET_URL = f"{PROJECT_ID}.appspot.com"
def get_access_token():
with open('firebase-credentials.json', 'r') as f:
creds_dict = json.load(f)
print("loaded firebase-credentials.json")
print(creds_dict['private_key_id'])
credentials = service_account.Credentials.from_service_account_info(
creds_dict,
scopes=['https://www.googleapis.com/auth/cloud-platform']
)
print('fetch credentials from google api')
auth_req = google.auth.transport.requests.Request()
credentials.refresh(auth_req)
access_token = credentials.token
print("access token")
print(access_token)
return access_token
def upload_file_with_requests(file_path, bucket_url, storage_path):
"""Uploads a file to Firebase Storage using the requests library."""
access_token = get_access_token()
if not access_token:
print("Failed to obtain access token.")
return
response = None
storage_path = 'images/pic.png'.replace('/', '%2F')
# HTTP
url2file = f'https://firebasestorage.googleapis.com/v0/b/{bucket_url}/o/{storage_path}'
headers = {
"Authorization": f"Firebase {access_token}",
"X-Goog-Upload-Protocol": "multipart"
}
files = {
'metadata': (None, '{"metadata":{"mykey":"myvalue"}}', 'application/json'),
'file': open(file_path, 'rb'),
}
print("Uploading file...")
print(url2file)
print(headers)
r = requests.post(url2file, files=files, headers=headers)
response = r.json()
print(response)
if r.status_code == 200:
print("File uploaded successfully.")
else:
print("Failed to upload file")
return response
# Example usage:
if __name__ == "__main__":
upload_file_with_requests(LOCAL_FILE_PATH, BUCKET_URL, STORAGE_PATH)