How to upload media files from a server use gRPC

I’m trying to build a post microservice that allows a user to be able to create a new post with text content and media files. This service is using gRPC and written by pyhon. When a user creates a new post, I want to save the media files in firebase storage and the text content in firebase realtime database. My code is able to connect and upload post content to the realtime database successfully, but the part about uploading media files to firebase storage is not working as expected. I can’t see the image after the update

Here is code from server

def CreatePost(self, request, context):
    try:
        error_message = self.decode_token(request.token, request.username)
        if error_message:
            app.logger.warning(f'CreatePost: {error_message}')

        post_id = str(int(datetime.timestamp(datetime.now())))

        post_data = {
            'text': request.text,
            'timestamp': str(datetime.now()),
            'username': request.username,
            'media': [{'type': m.type, 'data': m.data} for m in request.media]
        }

        db.reference('posts').child(post_id).set(post_data)

        # Save media in Firebase Storage
        storage_client = storage.Client()
        bucket = storage_client.bucket(BUCKET_NAME)
        blob_name = f'media/{post_id}/{request.media[0].decode}'
        blob = bucket.blob(blob_name)
        blob.upload_from_string(request.media[0])

        app.logger.debug(f'CreatePost: Post created successfully (ID: {post_id})')

        return post_service_pb2.Response(message="Post created successfully")

    except ValueError as e:
        app.logger.error(f'CreatePost: Failed to create post: {str(e)}')
        return post_service_pb2.Response(message=f'Failed to create post: {str(e)}')
    except Exception as e:
        app.logger.exception(f'CreatePost: An unexpected error occurred: {str(e)}')
        return post_service_pb2.Response(message=f'An unexpected error occurred: {str(e)}')

here is code I use to test script create new post

def test_create_post(stub, token, username):
    request = CreatePostRequest(
        token=token,
        username=username,
        text="This is a test post.",
        media=[b"image1.jpg", b"video1.mp4"]
    )
    response = stub.CreatePost(request)
    print(response.message)

Could someone please help me to address the problem? Thanks a lot

a solution to update new code from server and test script to be able to update media file to firebase storage successfully

Leave a Comment