pythonanywhere / help_pages

The help pages for help.pythonanywhere.com
43 stars 86 forks source link

Please update documentation error on mysql python code snippet (Connect From Outside) #80

Closed antnun closed 3 years ago

antnun commented 3 years ago

Change the mysql import with pymysql on the following article

https://help.pythonanywhere.com/pages/AccessingMySQLFromOutsidePythonAnywhere

Section From Python code

Some users (me included) have been experiencing errors DB frozen errors while trying access the DB via SSH Tunnel using that code.

Articles with Examples on this Topic

My working example after changing that:

import pymysql as sqlConnector
import sshtunnel

sshtunnel.SSH_TIMEOUT = 5.0
sshtunnel.TUNNEL_TIMEOUT = 5.0

dbHostName='zzzzzz.mysql.pythonanywhere-services.com'
dbName='myDB$tendlc_db'
dbUserName='myDBuser'
dbUserPassword='xxxxxx!'
sshHostName='ssh.pythonanywhere.com'
pyUserName='myLogin'
pyPassWord='myPWD'

#Perform Connection test and Sample Query
def dbtest(): 
    dbapi_config.refresh()
    with sshtunnel.SSHTunnelForwarder(
        (sshHostName),
        ssh_username=pyUserName, ssh_password=pyPassWord,
        remote_bind_address=(dbHostName, 3306)
    ) as tunnel:
        print ("SSH TUNNEL ESTABLISHED")
        connection = sqlConnector.connect(
            user=dbUserName, password=dbUserPassword,
            host='127.0.0.1', port=tunnel.local_bind_port,
            database=dbName,
        )
        print("CONNECTED")
        tst_query="SHOW TABLES"
        execute_query(conn=connection,query=tst_query)
        connection.close()

#This Helper function o execute query I am not the author but someone else's I cant find on my files
def execute_query(conn, query):
    cur = conn.cursor()
    cur.execute(query)
    print(cur.description)
    print()
    for row in cur:
        print(row)
antnun commented 3 years ago

BTW: if you share some tips on how to propose the fix via GITHUB as a pull request on the actual documentation file (not that skilled, on it) happy to do so..... I ave it a try, let's see how it goes.

gpjt commented 3 years ago

I'm not sure that pymysql is the right solution in the general case -- the package I'd normally recommend is mysqlclient. I've updated the page to use that one (and to include some installation instructions for it).