Hi @pybokeh
I see three issues with accepting user input to write to a database
- only connecting to the database once
- waiting for input data to be fully provided
- clearing input fields on submit
Regarding 1, this would be a good use case for the @cache
decorator, as you could cache your database connection so it’s only initialized once.
If you try to do this now you’ll probably encounter an error saying cannot cache database client
or something similar.
This should be fixed with https://github.com/streamlit/streamlit/issues/551
which is currently being worked on.
As a workaround you could do something like this
import streamlit as st
from pymongo import MongoClient
if not hasattr(st, "client"):
st.client = MongoClient('mongodb://127.0.0.1/local')
collection = st.client.local.user
name = st.text_input('name')
if name:
collection.insert_one({'name': name})
st.write(list(collection.find()))
Regarding 2, this is not currently possible but is being discussed at Have a widget not trigger an immediate update?
Regarding 3, if you reload the report after inputting data a second record will be inserted, as the widgets maintain their state, so you’ll probably want to clear the inputs after inserting.
This is not currently possible but is being discussed at https://github.com/streamlit/streamlit/issues/623