I'm trying to write a Flask miniapp to connect with a MySQL database. To connect with the database, I use flask-mysql, calling it as this way
from flask import Flask, render_template, redirect
from flaskext.mysql import MySQL
SECRET_KEY='5f352379324c22463451387a0aec5d2f'
app = Flask(__name__)
app.secret_key = SECRET_KEY
mydb = MySQL(app, prefix="mydb", host='172.17.0.2', user='testusr', password='test', db='testDB')
(...)
if __name__ == "__main__":
app.run(host='0.0.0.0', port=5000)
But, when I run the application, it shows this error
pymysql.err.OperationalError: (1044, "Access denied for user 'testusr'#'%' to database 'testDB'")
If I run it from a Docker container, I get a similar error, replacing "%" with "localhost" (in this case, it's not able to connect, due to the database is out of the container)
pymysql.err.OperationalError: (2003, "Can't connect to MySQL server on 'localhost' ([Errno 99] Cannot assign requested address)")
172.17.0.1 - - [23/Jun/2021 18:00:29] "GET / HTTP/1.1" 500 -
I tried to initialize flask-mysql using other this way, with the same error
app.config['MYSQL_HOST'] = '172.17.0.2'
app.config['MYSQL_USER'] = 'testusr'
app.config['MYSQL_PASSWORD'] = 'test'
app.config['MYSQL_DB'] = 'testDB'
mydb = MySQL(app)
Where can be the error?
Solved changing the connector from flask-mysql to mysql-connector
import mysql.connector
SECRET_KEY='5f352379324c22463451387a0aec5d2f'
app = Flask(__name__)
app.secret_key = SECRET_KEY
mydb = mysql.connector.connect(
host="172.17.0.2",
user="testusr",
password="test",
database="testDB"
)
Related
I use the below code for connecting to MYSQL DATABASE using flask and pyodbc package. AS I try to run a flask project.
app.py
from dotenv import load_dotenv
from flask_migrate import Migrate
from flask_cors import CORS
from api import create_app, init_db
from api.common.models.models import db
import os
load_dotenv()
app_name = os.environ.get('FLASK_APP') or ''
app = create_app()
# security
cors_allowed_origins = os.environ.get('CORS_ALLOWED_ORIGINS', [])
CORS(app) # , origins=cors_allowed_origins
# sqlalchemy
app.config['SQLALCHEMY_DATABASE_URI'] = "mssql+pyodbc://USERNAME:PASSWORD#./DBNAME?driver=ODBC+Driver+17+for+SQL+Server"
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = FALSE
db = init_db(app)
migrate = Migrate(app, db)
#app.route('/')
def home():
str = 'Hello World {0}'.format(app_name)
return str
if __name__=='__main__':
app.run()
I get the following error:
sqlalchemy.exc.OperationalError: (pyodbc.OperationalError) ('HYT00', '[HYT00] [Microsoft][ODBC Driver 17 for SQL Server]Login timeout expired (0) (SQLDriverConnect)')
Your issue is with the connection string, you are trying to connect to MySql but the connection string is to connect to MSSQL:
"mssql+pyodbc://USERNAME:PASSWORD#./DBNAME?driver=ODBC+Driver+17+for+SQL+Server"
But for MYSQL is one of the following:
# default
app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql://scott:tiger#localhost/foo'
# mysqlclient (a maintained fork of MySQL-Python)
app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql+mysqldb://scott:tiger#localhost/foo'
# PyMySQL
app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql+pymysql://scott:tiger#localhost/foo'
Check the official documentation:
Database Urls
I cannot connect to my pythoneverywhere.com database from my local project.
The error is:
mysql.connector.errors.InterfaceError: 2013: Lost connection to MySQL server during query
Thank you in advance!
from flask import Flask, request, url_for, redirect
from flask_restful import Resource, Api
import pymysql as MySQLdb
from flaskext.mysql import MySQL
import mysql.connector
import sshtunnel
app = Flask(__name__)
api = Api(app)
sshtunnel.SSH_TIMEOUT = 5.0
sshtunnel.TUNNEL_TIMEOUT = 5.0
with sshtunnel.SSHTunnelForwarder(
('ssh.pythonanywhere.com'),
ssh_username='XXX', ssh_password='XXX',
remote_bind_address=('bianca.mysql.pythonanywhere-services.com', 3306)
) as tunnel:
connection = mysql.connector.connect(
user='XXX', password='XXX',
host='127.0.0.1', port=tunnel.local_bind_port,
database='bianca$moviesdb',
)
connection.close()
# print('after SSH connection')
conn = MySQLdb.connect("bianca.mysql.pythonanywhere-services.com", "XXX", "XXX", "bianca$moviesdb")
c = conn.cursor()
c.execute("SELECT * FROM reviews")
rows = c.fetchall()
for eachRow in rows:
print(eachRow)
if __name__ == '__main__':
app.run(port=5002)
Many things could be happening here: Timeout errors, packet sizes, etc. Also check your firewall settings.
https://dev.mysql.com/doc/refman/5.7/en/error-lost-connection.html
I am new to using python to connect to a mysql DB and I am getting the following error:
OperationalError: (pymysql.err.OperationalError) (1045, u"Access denied for user 'xxxxxxadmin'#'xx.xx.xx.xx' (using password: YES)") (Background on this error at: http://sqlalche.me/e/e3q8)
xx.xxx.216.44 - - [02/Apr/2018 17:27:49] "GET /testconnect HTTP/1.1" 500 -
This is most of the connect script in my python file:
#!/usr/bin/python3
from flask import Flask, request
from flask_restful import Resource, Api
from sqlalchemy import create_engine
from json import dumps
from flask.ext.jsonpify import jsonify
db_connect = create_engine("mysql+pymysql://xxxxxxxadmin:password#,mymaindb.xxxxxxxx.us-east-2.rds.amazonaws.com:3306/myDBname")
app = Flask(__name__)
api = Api(app)
class TestConnect(Resource):
def get(self):
conn = db_connect.connect() # connect to database
query = conn.execute("select * from Players") # This line performs query and returns json result
return {'employees': [i[0] for i in query.cursor.fetchall()]} # Fetches first column that is Employee ID
api.add_resource(TestConnect, '/testconnect') # Route_1
if __name__ == '__main__':
app.run(host='0.0.0.0', debug = False)
Other background:
But when I try to connect to the same mysql database using the exact same credentials via the command line on the server running the python script I am able to get in.
Not sure how to test more to get a better error result that will help me figure this issue out.
UPDATE
So I was able to connect to my DB via mysql workbench with the connection strings and information I have in the python script. Does this mean my python script is doing something wrong?
Why not use:
mysql+pymysql://xxxxxxxadmin:password#mymaindb.xxxxxxxx.us-east-2.rds.amazonaws.com:3306/myDBname
instead of
mysql+pymysql://xxxxxxxadmin:password#**,**mymaindb.xxxxxxxx.us-east-2.rds.amazonaws.com:3306/myDBname
Not sure why you're connection string has a comma. Might just be a typo?
On that note, I usually build the connection URL before passing it to create_engine just to make it easier to manage in the future incase I have to pull the actual values from the environmental variables:
HOST = "mymaindb.xxxxxxxx.us-east-2.rds.amazonaws.com"
PORT = 3306
USERNAME = "xxxxxxxadmin"
PASSWORD = "password"
DBNAME = "myDBname"
CONNECTION_URL = 'mysql+pymysql://%s:%s#%s:%s/%s' % (
USERNAME,
PASSWORD,
HOST,
PORT,
DBNAME
)
I am using falsk SQLAlchemy with MYSQL with all default configuration(pool size and timeout)
I don't understand why do I get out of DB connections from the MYSQL DB?
My server is not that heavy loaded.
Can someone please explain how the flask sql alchemy get and release DB connections?
If I have a pool thread of 20 on my apache mod_wsgi server that means by theory that i can have 20 db connection opens all the time and that's it no?
How flask sql alchemy handle close and restore those connections.
Thanks
try this code
import sqlalchemy
dbhost = 'localhost' #host name
dbuser = 'root' #mysql username
dbpass = 'admin' #mysql password
dbname = 'mytable' #database name
engine = sqlalchemy.create_engine('mysql://'+dbuser+':'+dbpass+'#'+dbhost ) # connect to server
DB_URI = 'mysql://' + dbuser + ':' + dbpass + '#' + dbhost + '/' +dbname
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI']=DB_URI
db = SQLAlchemy(app)
I am trying to connect flask app mysql connection with AWS RDS over ssl , It works when I am try to use mysql client like this
mysql -u user -h myrds.rds.amazonaws.com -p --ssl-ca=rds-combined-ca-bundle.pem
I am able to login but when I am try with flask app
SQLALCHEMY_DATABASE_URI = 'mysql://user:Password#myrds.rds.amazonaws.com.rds.amazonaws.com/miro_dev?ssl_cert=rds-combined-ca-bundle.pem'
it send me error
sqlalchemy.exc.OperationalError: (_mysql_exceptions.OperationalError) (2026, 'SSL connection error: Unable to get private key')
I was able to get this work by adding
?sslmode=verify-ca&sslrootcert=rds-combined-ca-bundle.pem
to the connection string.
This came from the postgresql docs here along with the aws docs.
You can change the sslmode to require if you do not care about verifying the rds. I downloaded the pem file from here.
I think that in your case the connection string is correct, you just need to use ssl_ca option and not ssl_cert:
SQLALCHEMY_DATABASE_URI = 'mysql://user:password#myrds.rds.amazonaws.com.rds.amazonaws.com/miro_dev?ssl_ca=rds-combined-ca-bundle.pem'
I do this:
...
ssl_args = {'ssl': {'ca': 'YOUR_SSL_CERT_PATH'}}
db_url = 'mysql://{}:{}#{}/{}'.format(username, password, server, database)
engine = create_engine(db_url, connect_args=ssl_args, echo=False)
cnx = engine.connect()
df = pd.read_sql_table('table_name', cnx)
And I'd suggest to not input a path like follows:
~/...
but:
/home/YOUR_USER/...