Custom Connections Problem with secrets.toml file

Summary

I am little bit confused, how can I extract the secrets.toml file’s key:value pair into my custom connection class. I need some help how can I achieve that thing.

Steps to reproduce

Code snippet:

secrets.toml

[connections]
host = "mongodb://127.0.0.1:27017"

connection.py

from streamlit.connections import ExperimentalBaseConnection
import pymongo 
import streamlit as st

class MongoDBConnection(ExperimentalBaseConnection[pymongo.MongoClient]):
    def _connect(self, **kwargs) -> pymongo.MongoClient:
        if 'host' in kwargs:
            host = kwargs.pop('host')
        else:
            host = self._secrets['connections']
        return pymongo.MongoClient(host=host, **kwargs)

main.py

from connect import MongoDBConnection
import streamlit as st

conn = st.experimental_connection(name="mongodb", type=MongoDBConnection)

print(conn)

After installing “pip install streamlit” Just create these files in your local envirionment
and test it to reproduce the error

Expected behavior:

It should show the value of “host”

Actual behavior:

Debug info

  • Streamlit version: (get it with $ streamlit version)
  • Python version: (get it with $ python --version)
  • Using PyEnv
  • OS version: Windows 11 Home Single Language 22H2
  • Browser version: Not required

The path should be at the root of your app repo:

.streamlit/secrets.toml

The self._secrets entry automatically looks for something called [connections.<connection_name>] in .streamlit/secrets.toml, so if you add an entry like this:

[connections.mongodb]
host = "mongodb://127.0.0.1:27017"

Then this code will work

class MongoDBConnection(ExperimentalBaseConnection[pymongo.MongoClient]):
    def _connect(self, **kwargs) -> pymongo.MongoClient:
        if 'host' in kwargs:
            host = kwargs.pop('host')
        else:
            host = self._secrets['host'] # Note that this is host, not connections or connections.host
        return pymongo.MongoClient(host=host, **kwargs)

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.