Forums

Code samples using SQLAlchemy and the SSL Tunnel?

I am trying to connect to a Python Anywhere mySQL database while doing development and running into SSH issues. I read this - https://help.pythonanywhere.com/pages/AccessingMySQLFromOutsidePythonAnywhere/ - but can really use some code samples that use SQLAlchemy. Any guidance, please? Thanks.

What kind of errors do you get?

I did not get any code errors since I did not try and I am not quite sure how I would plug it in. Using SQLAlchemy, I only have a couple lines of code and all the DB functions magically work. I simply have:

SQLALCHEMY_DATABASE_URI = "mysql://joeg:password@joeg.mysql.pythonanywhere-services.com/joeg$database_name"

db = SQLAlchemy(app)

I am not sure how that all translates to using the SSH tunnel. Do I need to pass in all that code before each DB query etc?

If you use the "From Python code" section on that help page, you'd just put all of your SQLAlchemy code inside the "with" statement. You'd need to change the URI to reflect the different host and port number.

However, it does look like you're using Flask-SQLAlchemy, so perhaps you could give some more details on what you're trying to achieve -- are you trying to run your Flask site locally on your computer, and connect it to your MySQL instance on PythonAnywhere?

Giles - exactly. I am doing Flask development on my local system and want to use a mySQL Database on Python Anywhere. Do you have any code samples for that scenario?

For that scenario, your best bet would be to use the "Manual SSH tunnelling" from the help page and then just connect your Flask app to the local end of the tunnel.