Search code examples
mysqlpython-3.xdatabasefastapipythonanywhere

How to connect database with FastAPI app?


I have mysql server on python anywhere platform. I have a FastAPI app. I would like to access to my database from my FastAPI app. I know that I can reach the database directly from FastAPI app and I saw many tutorials but I am finding the set up a bit complicated and as a beginner I would like to keep it simple.

From pythonanywhere platform support I know I can reach my database from python script with ssh tunneling. I have tested the solution and it worked well.

If I hash my password not as it is in the following script, do you believe this is a suitable solution ?

This is database.py

#database.py
import MySQLdb
import sshtunnel

sshtunnel.SSH_TIMEOUT = 5.0
sshtunnel.TUNNEL_TIMEOUT = 5.0

def get_data():

    with sshtunnel.SSHTunnelForwarder(
        ('ssh.pythonanywhere.com'),
        ssh_username='username', ssh_password='hashed',
        remote_bind_address=('username.mysql.pythonanywhere-services.com', 3306)
    ) as tunnel:
        connection = MySQLdb.connect(
            user='username',
            passwd='hashed',
            host='127.0.0.1', port=tunnel.local_bind_port,
            db='username$dbName',
        )
        # Do stuff
        with connection as con:
            with con.cursor() as c:
                c.execute("SELECT * FROM table;")
                res = c.fetchall()
    
    return res


  

This is the fastapi app script main.py

#main.py
from fastapi import FastAPI
from database import get_data

app = FastAPI()

@app.get('/mesures')
def get_mesures():
    return get_data()

Again, I know this is not best solution but just would like your thoughts.


Solution

  • Ok I close this post as answered based on replies in comment.

    Assuming that the FastAPI app is hosted somewhere else, SSH tunneling is the only option to connect to your PA-hosted MySQL db. You need a paid account in order for that to work Currently FastAPI web apps would not work on PythonAnywhere, but we're working on this -- once it's ready, I guess you will be able to host the web app on PA and connect it with your db in a less "hacky" way. For now tunneling is the only option.