I don't want my code to compile all the time

Below is a snippet of my code:

after logging in I need to provide 5 values ​​and ask to calculate
but the code compiles every time I add the first value

import streamlit as st
import sqlite3

# Função para autenticar o usuário
# @st.cache_date
def authenticate_user(username, password):
    conn = sqlite3.connect('database.db')
    c = conn.cursor()

    c.execute("SELECT password FROM users WHERE username=?", (username,))
    stored_password = c.fetchone()

    conn.close()

    if stored_password and stored_password[0] == password:
        return True
    else:
        return False

# Função para criar um novo usuário
def create_user(username, password):
    conn = sqlite3.connect('database.db')
    c = conn.cursor()

    try:
        c.execute("INSERT INTO users (username, password) VALUES (?, ?)", (username, password))
        conn.commit()
        conn.close()
        return True
    except sqlite3.IntegrityError:
        # Se o nome de usuário já existe
        conn.close()
        return False

# Título do aplicativo
st.title("Faça o login abaixo")

# Variável para controlar a página ativa
page = st.radio("Escolha uma opção:", ["Login", "Criar Novo Usuário"])

# Interface de entrada de dados do usuário
if page == "Login":
    username = st.text_input("Nome de Usuário")
    password = st.text_input("Senha", type="password")

    if st.button("Login"):
        if authenticate_user(username, password):
            st.success("Login bem-sucedido!")

            # Crie 5 campos de input para os valores
            values = []
            for i in range(5):
                values.append(st.number_input(f"Insira o valor #{i+1}", step=1))

            # Use um botão para calcular a soma
            if st.button("Calcular Soma"):
                # Calcule a soma dos valores
                soma = sum(values)
                # Exiba o resultado
                st.write(f"A soma dos valores é: {soma}")

        else:
            st.error("Credenciais inválidas. Tente novamente.")

elif page == "Criar Novo Usuário":
    new_username = st.text_input("Novo Nome de Usuário")
    new_password = st.text_input("Nova Senha", type="password")

    if st.button("Criando usuário"):
        if new_username and new_password:
            if create_user(new_username, new_password):
                st.success("Usuário criado com sucesso!")
            else:
                st.error("Nome de usuário já existe. Escolha outro nome de usuário.")

Summary

Share a clear and concise description of the issue. Aim for 2-3 sentences.

Steps to reproduce

Code snippet:

add code here

If applicable, please provide the steps we should take to reproduce the error or specified behavior.

Expected behavior:

Explain what you expect to happen when you run the code above.

Actual behavior:

Explain the undesired behavior or error you see when you run the code above.
If you’re seeing an error message, share the full contents of the error message here.

Debug info

  • Streamlit version: (get it with $ streamlit version)
  • Python version: (get it with $ python --version)
  • Using Conda? PipEnv? PyEnv? Pex?
  • OS version:
  • Browser version:

Requirements file

Using Conda? PipEnv? PyEnv? Pex? Share the contents of your requirements file here.
Not sure what a requirements file is? Check out this doc and add a requirements file to your app.

Links

  • Link to your GitHub repo:
  • Link to your deployed app:

Additional information

If needed, add any other context about the problem here.

Maybe session state can help - Session State - Streamlit Docs

Hi @pastoril

On every action on your Streamlit app, the code will re-execute.

If using buttons, using an if button will execute the code on the if statement, but if you perform any other actions that button event is no longer present. Given this behavior, using a callback function and session state to make your app stateful is recommended. Callback functions will execute prior to the rest of the script and then your script will re-run as normal. This allows you to set a session state value before the script execution and change the behavior of your app to its intended.

if st.button("Login"):
    #your login code

instead use

def login(user:str, pwd:str)->None:
    #Place your logic for login here

st.button("Login", on_click=login, args=[username,password]):

Hope this helps.

–Carlos

1 Like

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