Streamlit Module Not Found flask_mysql_connector

Hello, iā€™m new using Streamlit and while i was working on a project i found the following issue:

ModuleNotFoundError: No module named 'flask_mysql_connector'

Basically i have 2 .py files in my project. One does with the Login page and the other with some graphs i want to show.

  • Login (main.py)
  • Graphs (home.py)

The thing is i want to redirect the user to the graph once he logs in, but i am a little lost on how this should work.

For example, I tried to open the streamlit file with this line of code:
exec(open("templates/home.py", encoding="utf8").read())

but I got an error that says ā€œThe view function did not return a valid responseā€ because i dont know how to render the Home.py as a template.

I also tried to run this from anaconda using the command "streamlit run [pathTo_home.py] but it says that cant find the module ā€œflask_mysql_connectorā€.

This is the code:

Main.py:

import streamlit as st
from datetime import datetime, timedelta
import pandas as pd
#from PIL import Image
#import json
import requests
import altair as alt
from flask import Flask, render_template, redirect, url_for,request, session
from flask_mysql_connector import MySQL
import pymysql
import templates.home as homeAcciones
import subprocess

app = Flask(__name__)

app.secret_key = "120395"

app.config["MYSQL_HOST"] = "localhost"
app.config["MYSQL_USER"] = "root"
app.config["MYSQL_PASSWORD"] = "anto1203"
app.config["MYSQL_DB"] = "amsterdamdb"

db = MySQL(app)


@app.route('/', methods=['GET', 'POST'])
def index():
    if request.method == 'POST':
        if ('email_usuario_form' in request.form) and ('password_usuario_form' in request.form):
            usuarios_email_py = request.form['email_usuario_form']
            usuarios_password_py = request.form['password_usuario_form']
            cursor = db.connection.cursor(pymysql.cursors.DictCursor)
            cursor.execute("SELECT USUARIOS_EMAIL, USUARIOS_LOGIN_PASSWORD FROM amsterdamdb.usuarios WHERE "
                            "USUARIOS_EMAIL=%s AND USUARIOS_LOGIN_PASSWORD=%s", (usuarios_email_py,
                                                                                usuarios_password_py))
            info = cursor.fetchone()
            print(info)
            if info is None:
                return "Usuario y contraseƱa incorrectos"
            else:
                if info[0] == usuarios_email_py and info[1] == usuarios_password_py:
                    session['loginsuccess'] = True
                    return redirect(url_for("home"))


    return render_template("./login.html")


@app.route('/registro')
def registro():
    return render_template("register.html")


@app.route('/home')
def home():
    if session['loginsuccess'] == True:
        exec(open("templates/home.py", encoding="utf8").read())


if __name__ == '__main__':
    app.run(debug=True)
    

Home.py

from datetime import datetime, timedelta
import streamlit as st
import pandas as pd
#from PIL import Image
#import json
import requests
import altair as alt
st.sidebar.header('Ingrese parƔmetros')


def get_input():
    aux_datetime = datetime.now()
    today_date = aux_datetime.date()
    treinta_dias_date = today_date - timedelta(days=30)

    get_fecha_desde = st.sidebar.text_input("Fecha Inicial", treinta_dias_date )
    get_fecha_hasta = st.sidebar.text_input("Fecha Final", today_date)
    get_nemotecnico = st.sidebar.text_input("Identificador", "goog" )
    return get_fecha_desde, get_fecha_hasta, get_nemotecnico



def get_data(nemotecnico_empresa, fecha_desde, fecha_hasta):
    nemotecnico = nemotecnico_empresa

from_input_fecha_desde,from_input_fecha_hasta,from_input_nemotecnico = get_input()

fecha_desde = datetime.strptime(from_input_fecha_desde, '%Y-%m-%d')
fecha_hasta = datetime.strptime(from_input_fecha_hasta, '%Y-%m-%d')
nemotecnico = from_input_nemotecnico.upper()

fecha_desde_tmsp = str(round(datetime.timestamp(fecha_desde)))

fecha_hasta_tmsp = str(round(datetime.timestamp(fecha_hasta)))


if nemotecnico=="":
    r = requests.get(
        'https://finnhub.io/api/v1/stock/candle?symbol=&resolution=1&from=0&to=0&token=btagn3v48v6vivh8p9n0')
    accionesJson = r.json()
else:
    r = requests.get(
    'https://finnhub.io/api/v1/stock/candle?symbol=' + nemotecnico + '&resolution=D&from=' + fecha_desde_tmsp + '&to=' + fecha_hasta_tmsp + '&token=btagn3v48v6vivh8p9n0')
    accionesJson = r.json()

open_values = accionesJson["o"]
close_values = accionesJson["c"]
fecha_values = accionesJson["t"]
fecha_values_size = len(fecha_values)
fecha_values_int = []
fecha_values_datetime = []

for x in range(0, fecha_values_size):
    fecha_values_int.append(int(fecha_values[x]))

for i in range(0, fecha_values_size):
    valor_aux = datetime.fromtimestamp((fecha_values_int[i]))
    fecha_values_datetime.append(valor_aux.strftime("%m/%d/%Y"))

data_ordenada = {'Apertura': open_values,
                    'Cierre': close_values,
                    'Fecha': fecha_values_datetime}


chart_data = pd.DataFrame(data_ordenada)

source = chart_data

alt_chart = alt.Chart(source).transform_fold(
    ['Apertura', 'Cierre']
).mark_line().encode(
    x=alt.X('Fecha:O',axis=alt.Axis(title="Fechas")),
    y=alt.Y('value:Q',scale=alt.Scale(zero=False), axis=alt.Axis(title="Valor")),
    tooltip=['Fecha', 'Apertura', 'Cierre'],
    color='key:N'
).interactive().properties(
    width=800,
    height=500
)
st.write("", "", alt_chart)

st.header('Puntos de interƩs')
st.write(source.describe())

print(accionesJson)

Hi @Anthonny_Gueli, welcome to the Streamlit community!

Iā€™m not exactly following your questions here, but itā€™s important to realize that Streamlit isnā€™t like Flask, in that weā€™re not returning templates. So depending on whether you need the login page the way youā€™ve written it, you might be able to simplify your code by removing Flask altogether.

In terms of flask_mysql_connector not being available, this sounds like a PATH or environment issue unrelated to Streamlit.

Best,
Randy