O processo é bem simples, porém é necessário antes configurar algumas coisas no Google Cloud e gerar as credenciais necessárias, para este processo pode seguir este tutorial. Lembre-se também de criar uma variável de ambiente com o nome GOOGLE_APPLICATION_CREDENTIALS apontando para o caminho do json, no Linux basta fazer:
export GOOGLE_APPLICATION_CREDENTIALS=/caminho/para/arquivo.json
Depois disso é possível executar o código abaixo (é claro, o bucket e o arquivo indicado deve existir):
from datetime import timezone, datetime from typing import BinaryIO from google.cloud import storage def upload_file( data: BinaryIO, bucket: str, file_path: str, link_lifetime: int = 3600 ) -> str: """ Função que realiza o upload do arquivo """ storage_client = storage.Client() bucket = storage_client.bucket(bucket) blob = bucket.blob(file_path) blob.upload_from_file(data) # Faz o upload do arquivo binário e cria um objeto associado ao arquivo lifetime = int( datetime.now(tz=timezone.utc).timestamp() ) + link_lifetime # Gera um link para o arquivo com tempo de expiração url = blob.generate_signed_url(lifetime) return def main(): bucket = 'meu-pequeno-bucket' # Bucket name in GCS file_name = 'arquivo_legal.pdf' # Filename with open(file_name, 'rb') as f: url = upload_file( data=f, bucket=bucket, file_path=file_name, ) print(f'URL for file: {url}') if __name__ == "__main__": main()