Skip to content

🎥 Make videos programmatically with React

`@remotion/lambda-python`: Add `AsyncRemotionClient` for asynchronous rendering

Jonny Burger490315b807ba
diff --git a/packages/docs/docs/lambda/python.mdx b/packages/docs/docs/lambda/python.mdx
index aadaaf1599..2707176493 100644
--- a/packages/docs/docs/lambda/python.mdx
+++ b/packages/docs/docs/lambda/python.mdx
@@ -82,6 +82,51 @@ if render_response:
print("Render done!", progress_response.outputFile)
```
+## Asynchronous rendering<AvailableFrom v="4.0.535" />
+
+Use `AsyncRemotionClient` in `asyncio` applications to make requests without blocking the event loop. It accepts the same constructor options as `RemotionClient`, returns the same response objects, and raises the same exceptions.
+
+Await `render_media_on_lambda()`, `render_still_on_lambda()`, `get_render_progress()`, and `cancel_render_on_lambda()`:
+
+```python title="render_media_async.py"
+import asyncio
+import os
+from remotion_lambda import AsyncRemotionClient, RenderMediaParams
+
+
+async def main():
+ client = AsyncRemotionClient(
+ region=os.environ['REMOTION_APP_REGION'],
+ serve_url=os.environ['REMOTION_APP_SERVE_URL'],
+ function_name=os.environ['REMOTION_APP_FUNCTION_NAME'],
+ )
+
+ response = await client.render_media_on_lambda(
+ RenderMediaParams(composition="react-svg")
+ )
+ if response is None:
+ return
+
+ while True:
+ progress = await client.get_render_progress(
+ render_id=response.render_id,
+ bucket_name=response.bucket_name,
+ )
+ if progress is None:
+ return
+ if progress.fatalErrorEncountered:
+ raise RuntimeError(progress.errors)
+ if progress.done:
+ print("Render done!", progress.outputFile)
+ return
+ await asyncio.sleep(1)
+
+
+asyncio.run(main())
+```
+
+Cancelling an awaited request does not stop the AWS request or the render. To cancel a render, start it with `enable_cancellation=True` and await `cancel_render_on_lambda()` with its render ID and bucket name.
+
## Configuring the AWS clients
### config?<AvailableFrom v="4.0.380" />
diff --git a/packages/lambda-python/remotion_lambda/__init__.py b/packages/lambda-python/remotion_lambda/__init__.py
index c4123d092b..49b271259d 100644
--- a/packages/lambda-python/remotion_lambda/__init__.py
+++ b/packages/lambda-python/remotion_lambda/__init__.py
@@ -21,4 +21,5 @@ from .models import (
Webhook,
)
from .remotionclient import RemotionClient
+from .asyncremotionclient import AsyncRemotionClient
from .version import VERSION
diff --git a/packages/lambda-python/remotion_lambda/asyncremotionclient.py b/packages/lambda-python/remotion_lambda/asyncremotionclient.py
new file mode 100644
index 0000000000..3296fd9176
--- /dev/null
+++ b/packages/lambda-python/remotion_lambda/asyncremotionclient.py
@@ -0,0 +1,111 @@
+# pylint: disable=too-many-arguments, too-many-positional-arguments
+"""Awaitable client for rendering with Remotion Lambda."""
+import asyncio
+from typing import Optional, Union
+
+from boto3.session import Session
+from botocore.config import Config
+
+from .models import (
+ CustomCredentials,
+ RenderMediaParams,
+ RenderMediaProgress,
+ RenderMediaResponse,
+ RenderStillParams,
+ RenderStillResponse,
+ RenderType,
+)
+from .remotionclient import RemotionClient
+
+
+class AsyncRemotionClient:
+ """Run RemotionClient operations without blocking the asyncio event loop."""
+
+ def __init__(
+ self,
+ region: str,
+ serve_url: str,
+ function_name: str,
+ access_key: Optional[str] = None,
+ secret_key: Optional[str] = None,
+ force_path_style: bool = False,
+ session: Optional[Session] = None,
+ config: Optional[Config] = None,
+ ):
+ """Accept the same configuration and credentials as RemotionClient."""
+ self._client = RemotionClient(
+ region=region,
+ serve_url=serve_url,
+ function_name=function_name,
+ access_key=access_key,
+ secret_key=secret_key,
+ force_path_style=force_path_style,
+ session=session,
+ config=config,
+ )
+
+ async def construct_render_request(
+ self,
+ render_params: Union[RenderMediaParams, RenderStillParams],
+ render_type: RenderType,
+ ) -> str:
+ """Construct a render request, including any required S3 uploads."""
+ return await asyncio.get_event_loop().run_in_executor(
+ None, self._client.construct_render_request, render_params, render_type
+ )
+
+ async def construct_render_progress_request(
+ self,
+ render_id: str,
+ bucket_name: str,
+ log_level: str = "info",
+ s3_output_provider: Optional[CustomCredentials] = None,
+ ) -> str:
+ """Construct a render progress request in JSON format."""
+ return await asyncio.get_event_loop().run_in_executor(
+ None,
+ self._client.construct_render_progress_request,
+ render_id,
+ bucket_name,
+ log_level,
+ s3_output_provider,
+ )
+
+ async def render_media_on_lambda(
+ self, render_params: RenderMediaParams
+ ) -> Optional[RenderMediaResponse]:
+ """Start a media render and return its render ID and bucket name."""
+ return await asyncio.get_event_loop().run_in_executor(
+ None, self._client.render_media_on_lambda, render_params
+ )
+
+ async def render_still_on_lambda(
+ self, render_params: RenderStillParams
+ ) -> Optional[RenderStillResponse]:
+ """Render a still and return its output information."""
+ return await asyncio.get_event_loop().run_in_executor(
+ None, self._client.render_still_on_lambda, render_params
+ )
+
+ async def get_render_progress(
+ self,
+ render_id: str,
+ bucket_name: str,
+ log_level: str = "info",
+ s3_output_provider: Optional[CustomCredentials] = None,
+ ) -> Optional[RenderMediaProgress]:
+ """Get the progress of a media render."""
+ return await asyncio.get_event_loop().run_in_executor(
+ None,
+ self._client.get_render_progress,
+ render_id,
+ bucket_name,
+ log_level,
+ s3_output_provider,
+ )
+
+ async def cancel_render_on_lambda(self, render_id: str, bucket_name: str) -> None:
+ """Cancel a render started with enable_cancellation=True."""
+ await asyncio.get_event_loop().run_in_executor(
+ None, self._client.cancel_render_on_lambda, render_id, bucket_name
+ )
diff --git a/packages/lambda-python/remotion_lambda/remotionclient.py b/packages/lambda-python/remotion_lambda/remotionclient.py
index 9ba127cb1d..3af885a09e 100644
--- a/packages/lambda-python/remotion_lambda/remotionclient.py
+++ b/packages/lambda-python/remotion_lambda/remotionclient.py
@@ -6,6 +6,7 @@ import json
import hashlib
import time
from math import ceil
+from threading import Lock
from typing import Optional, Union, List, Dict, Any
from enum import Enum
import warnings
@@ -213,6 +214,7 @@ class RemotionClient:
self.function_name = function_name.strip()
self.force_path_style = force_path_style
self.config = config or Config() # Provide default empty config
+ self._session_lock = Lock()
def _generate_hash(self, payload: str) -> str: # Added type hints
"""Generate a hash for the payload."""
@@ -257,7 +259,9 @@ class RemotionClient:
if current_config:
client_kwargs['config'] = current_config
- return self.session.client(service_name, **client_kwargs) # type: ignore[call-overload]
+ # boto3 sessions cannot create clients concurrently across threads.
+ with self._session_lock:
+ return self.session.client(service_name, **client_kwargs) # type: ignore[call-overload]
def _create_s3_client(self) -> Any: # Returns an S3 client type
"""Creates and returns a boto3 S3 client."""