[Python] Flask SQLAlchemy MySQL Connection Issue – Connectivity & Connection String Issue

Discussão em 'Python' iniciado por Stack, Março 9, 2025.

  1. Stack

    Stack Membro Participativo

    I'm developing a Flask application using Flask-SQLAlchemy and MySQL, but I'm facing issues with both database connectivity and correctly forming the connection string.

    Setup Details:

    • Backend: Flask
    • ORM: SQLAlchemy
    • Database: MySQL (local 9.2.0 and docker compose version 8)
    • Driver: mysql+pymysql

    Connection String I'm Using:

    class Config:
    SQLALCHEMY_DATABASE_URI = (
    f"mysql+pymysql://{os.getenv('MYSQL_USER')}:{os.getenv('MYSQL_PASSWORD')}"
    f"@{os.getenv('MYSQL_HOST')}:{os.getenv('MYSQL_PORT')}/{os.getenv('MYSQL_DB')}"
    )
    SQLALCHEMY_TRACK_MODIFICATIONS = False
    SECRET_KEY = os.getenv("SECRET_KEY")


    Error Message:

    • I get one of the following errors when running my Flask app while running API locally:

    Traceback (most recent call last): File "/Users/aravindkoniki/Documents/Workspace/Git Respositories/github/CloudScaler/api/auth_service/wsgi.py", line 4, in app = create_app() File "/Users/aravindkoniki/Documents/Workspace/Git Respositories/github/CloudScaler/api/auth_service/app/init.py", line 12, in create_app db.init_app(app) File "/Users/aravindkoniki/Documents/Workspace/Git Respositories/github/CloudScaler/api/auth_service/venv/lib/python3.9/site-packages/flask_sqlalchemy/extension.py", line 373, in init_app self._apply_driver_defaults(options, app) File "/Users/aravindkoniki/Documents/Workspace/Git Respositories/github/CloudScaler/api/auth_service/venv/lib/python3.9/site-packages/flask_sqlalchemy/extension.py", line 607, in _apply_driver_defaults url = sa.engine.make_url(options["url"]) File "/Users/aravindkoniki/Documents/Workspace/Git Respositories/github/CloudScaler/api/auth_service/venv/lib/python3.9/site-packages/sqlalchemy/engine/url.py", line 856, in make_url return _parse_url(name_or_url) File "/Users/aravindkoniki/Documents/Workspace/Git Respositories/github/CloudScaler/api/auth_service/venv/lib/python3.9/site-packages/sqlalchemy/engine/url.py", line 917, in _parse_url components["port"] = int(components["port"]) ValueError: invalid literal for int() with base 10: 'None'
    ​
    • Connection refused while running from docker compose file

    Troubleshooting Done So Far:


    • Verified MySQL is running and accessible from the machine.


    • Confirmed credentials and database exist.


    • Tested direct connection via MySQL CLI:

      mysql -u user -p -h host -P 3306 -D db_name

    Continue reading...

Compartilhe esta Página