Getting Started with Momento Topics in Python
If you need to get going quickly with Python and Momento Topics, this page contains the basic API calls you'll need. Check the Python SDK examples for complete, working code samples.
Install the Momento SDK
The Momento Python SDK is available on pypi as momento
.
To install in your Python application via pip, use:
pip install momento
Get your Momento API key
You'll need a Momento API key. You can get one from the Momento Web Console. Once you have your token, store it in an environment variable so that the Momento client can consume it:
export MOMENTO_API_KEY=<your api key here>
Note: it is best practice to put the API key into something like AWS Secret Manager or GCP Secret Manager instead of an environment variable for enhanced security, but we are using one here for demo purposes.
Set up a TopicClient
This code creates the TopicClient that you will use to interact with your pub/sub topic.
TopicClientAsync(
TopicConfigurations.Default.latest(), CredentialProvider.from_environment_variable("MOMENTO_API_KEY")
)
Publish a message to a topic
This is an example of publishing a message to a topic called "topic", then catching the return value to check if the publish was successful.
response = await topic_client.publish("cache", "my_topic", "my_value")
match response:
case TopicPublish.Success():
print("Successfully published a message")
case TopicPublish.Error() as error:
print(f"Error publishing a message: {error.message}")
Subscribe to a topic
This is an example of subscribing to a topic called "topic". When messages are published to this topic, the code here receives and prints them asynchronously.
response = await topic_client.subscribe("cache", "my_topic")
match response:
case TopicSubscribe.Error() as error:
print(f"Error subscribing to topic: {error.message}")
case TopicSubscribe.SubscriptionAsync() as subscription:
await topic_client.publish("cache", "my_topic", "my_value")
async for item in subscription:
match item:
case TopicSubscriptionItem.Text():
print(f"Received message as string: {item.value}")
return
case TopicSubscriptionItem.Binary():
print(f"Received message as bytes: {item.value!r}")
return
case TopicSubscriptionItem.Error():
print(f"Error with received message: {item.inner_exception.message}")
return
Running the code
You can find complete, working examples in the Python SDK GitHub repo examples directory.
Beyond these basic API calls check out the API reference page for more information on the full assortment of Momento API calls.