Cannot connect to cleardb from flask app running on heroku - python

I'm learning flask etc. and created a simple app locally. Everything worked fine with a local mysql database in xammp. I exported this and imported into clearDB on heroku and deployed my app. The app runs, but whenever I try to access a page relying on the database in the logs I see this error.
pymysql.err.OperationalError: (2003, "Can't connect to MySQL server on 'localhost' ([Errno 111] Connection refused)")
I ran the app locally, but using the clearDB database, and it was able to retrieve the data no problem. Everything is configured in the file to access based on the URL details from heroku.
Code is below. I'm sure there are a ton of other issues, but as I say I'm learning and got all this from a tutorial.
#instaniation
app = Flask(__name__)
app.secret_key= 'secret123'
#config
app.config['MYSQL_HOST'] = 'us-cdbr-iron-east-02.cleardb.net'
app.config['MYSQL_USER'] = 'redacted'
app.config['MYSQL_PASSWORD'] = 'redacted'
app.config['MYSQL_DB'] = 'heroku_0c6326c59d8b6e9'
app.config['MYSQL_CURSORCLASS'] = 'DictCursor' #a cursor is a connection to let us run methods for queries. We set is as a dictionary
#init MySQL
mysql = MySQL(app,cursorclass=DictCursor)
#url endpoint
#app.route('/')
#function for starting app
def index():
#can directly return HTML
return render_template('index.html')
#app.route('/about')
def about():
return render_template('about.html')
#many articles
#app.route('/articles')
def articles():
#create Cursor
cur = mysql.get_db().cursor() #to execute commands
cur.execute("USE myflaskapp")
#get articles
result = cur.execute("SELECT * FROM articles")
#should retrieve all as a dictionary
articles = cur.fetchall()
if result > 0:
return render_template('articles.HTML', articles=articles)
else:
msg= 'No Articles Found'
return render_template('articles.HTML', msg=msg)
cur.close()

As you can see from the error: pymysql.err.OperationalError: (2003, "Can't connect to MySQL server on 'localhost' ([Errno 111] Connection refused)") MySQL tried to connect to localhost server, which mean, its doesnt load your config variables.
If you are using flask extension from https://flask-mysql.readthedocs.io/en/latest/# to load MySQL then you are probably forgot to init your application (pip install flask-mysql)
mysql.init_app(app)
The head of you code should now look like this
And watch for the config variables names, the extension using slightly different convention
from flask import Flask
from flaskext.mysql import MySQL
#instaniation
app = Flask(__name__)
app.secret_key= 'secret'
#config
app.config['MYSQL_DATABASE_USER'] = 'user'
app.config['MYSQL_DATABASE_PASSWORD'] = 'password'
app.config['MYSQL_DATABASE_DB'] = 'db'
app.config['MYSQL_DATABASE_HOST'] = 'host'
#init MySQL
mysql = MySQL()
mysql.init_app(app)

Related

Setting Up Flask DB2 connection

I am trying to connect my flask application to a DB2 database,but somehow I am unable to do. here is what I am trying to do,
I am using flask extension flask_db2 for this purpose and below is how I am trying to connect
from flask import Flask
from flask_db2 import DB2
app = Flask(__name__)
#app.route('/')
def index()
cur = db.connection.cursor("DATABASE=name;HOSTNAME=host;PORT=60000;PROTOCOL=TCPIP;UID=username;PWD=password)
from flask import Flask
from flask_db2 import DB2
app = Flask(__name__)
app.config['DB2_DATABASE'] = 'sample'
app.config['DB2_HOSTNAME'] = 'localhost'
app.config['DB2_PORT'] = 50000
app.config['DB2_PROTOCOL'] = 'TCPIP'
app.config['DB2_USER'] = 'db2inst1'
app.config['DB2_PASSWORD'] = 'db2inst1'
db = DB2(app) #You forgot that
#app.route('/')
def index():
cur = db.connection.cursor()
cur.execute(...)
First: You forgot to have an object to use the flask db2 module.
The DB2(app) is a constructor for your Flask extension and will bind your application to this module.
where as
db = DB2(app)
Initialises your db object with help of your extension's constructor which you can further use for your Database operations.
Secondly: use app configs to play with DB2 credentials. (This step should be done before you bind the app)
Third: You can execute your query like this
cur.execute("SELECT id FROM users") #something like that
I hope I have clarified :D just drop message. Ill try helping more.

How to use multiple Mongodb in flask

I have two mysql database one is localhost and another is in server now, am going to create simple app in python using flask for that application i would like to connect the both mysql DB (local and server).
Any one please suggest how to connect multiple DB into flask.
app = Flask(__name__)
client = MongoClient()
client = MongoClient('localhost', 27017)
db = client.sampleDB1
Sample code if possible.
Thanks
I had the same issue, finally figured it out.
Instead of using
client = MongoClient()
client = MongoClient('localhost', 27017)
db = client.sampleDB1
Delete all that and try this:
mongo1 = PyMongo(app, uri = 'mongodb://localhost:27017/Database1')
mongo2 = PyMongo(app, uri = 'mongodb://localhost:27017/Database2')
Then, when you want to call a particular database you can use:
#app.route('/routenamedb1', methods=['GET'])
def get_data_from_Database1():
Database1 = mongo1.db.CollectionName ##Notice I use mongo1,
#If I wanted to access database2 I would use mongo2
#Walk through the Database for DC to
for s in Database1.find():
#Modifying code
return data
#This technique can be used to connect to multiple databases or database servers:
app = Flask(__name__)
# connect to MongoDB with the defaults
mongo1 = PyMongo(app)
# connect to another MongoDB database on the same host
app.config['MONGO2_DBNAME'] = 'dbname_two'
mongo2 = PyMongo(app, config_prefix='MONGO2')
# connect to another MongoDB server altogether
app.config['MONGO3_HOST'] = 'another.host.example.com'
app.config['MONGO3_PORT'] = 27017
app.config['MONGO3_DBNAME'] = 'dbname_three'
mongo3 = PyMongo(app, config_prefix='MONGO3')
create model.py and separate instances of 2 databases inside it, then in app.py:
app = Flask(__name__)
app.config['MODEL'] = model.my1st_database()
app.config['MODEL2'] = model.my2nd_database()
works for me :)

MySQL 5.7 and connection attribute

I have looked everywhere and well researched into different solutions. I have come closer to the solution by reducing the number of errors. Here is my piece of code that's giving me a headache
from flask import Flask, render_template, json, request
from flaskext.mysql import MySQL
from werkzeug import generate_password_hash,check_password_hash
mysql = MySQL()
app = Flask(__name__)
app.config['MYSQL_HOST'] = 'localhost'
app.config['MYSQL_USER'] = 'root'
app.config['MYSQL_PASSWORD'] = 'root'
app.config['MYSQL_DB'] = 'BucketList'
mysql.init_app(app)
cur = mysql.connection.cursor()
I have been running the app.py file and keep getting the following error:
AttributeError: 'MySQL' object has no attribute 'connection'.
I am using MySQL 5.7 and attempting to create my first web app using a tutorial that's dated back in time. The above piece of code is after editing it closer to relevant standards.
The part of your code in which you instantiate the MySQl() object is incorrect. Instead of:
mysql = MySQL()
app = Flask(__name__)
It should be
app = Flask(__name__)
mysql = MySQL(app)

Flask-MySQL gives "closing a closed connection" error the second time a view runs

I am using Flask-MySQL to connect to my database in a view. The view works the first time I go to it, but when I go to it the second time it always crashes with the error:
ProgrammingError: closing a closed connection
Why am I getting this error? How do I connect successfully the second time?
from flask import Flask, render_template, request
from flaskext.mysql import MySQL
app = Flask(__name__)
#app.route('/hello/', methods=['POST'])
def hello():
app.config['MYSQL_DATABASE_USER'] = 'root'
app.config['MYSQL_DATABASE_PASSWORD'] = 'xxx'
app.config['MYSQL_DATABASE_DB'] = 'pies'
app.config['MYSQL_DATABASE_HOST'] = 'localhost'
query = request.form['yourname']
mysql = MySQL(app)
conn = mysql.connect()
with conn as cursor:
try:
cursor.execute(query)
name = str(cursor.fetchone())
except:
name = "SQL is wrong"
conn.close()
return render_template('form_action.html', name=name)
if __name__ == '__main__':
app.run(debug=True)
You should not be initializing the extension during every request. Create it during app setup, then use it during the requests. Setting configuration should also be done during app setup.
The extension adds a teardown function that executes after every request and closes the connection, which is stored as a threadlocal. Since on the second request you've registered the extension multiple times, it is trying to close the connection multiple times.
There's no need to call connect, the extension adds a before request function that does that. Use get_db to get the connection for the request. Since the extension closes this connection for you, don't call close either.
from flask import Flask
from flaskext.mysql import MySQL
MYSQL_DATABASE_USER = 'root'
MYSQL_DATABASE_PASSWORD = 'xxx'
MYSQL_DATABASE_DB = 'pies'
MYSQL_DATABASE_HOST = 'localhost'
app = Flask(__name__)
app.config.from_object(__name__)
mysql = MySQL(app)
#app.route('/hello/')
def hello():
conn = mysql.get_db()
# ...
Note that Flask-MySQL is using a very old extension pattern that is no longer supported by Flask. It also depends on an unsupported mysql package that does not support Python 3. Consider using Flask-MySQLdb instead.

How do I connect as sysdba for oracle db using SQLALchemy

I am using sqlalchemy with flask
and I want to connect to oracle DB as sysdba
SQLALCHEMY_DATABASE_URI ='oracle+cx_oracle://sys:abc#DBNAME[mode=SYSDBA]'
This doesnt work and gives me a
from flask import Flask
from flask.ext.sqlalchemy import SQLAlchemy
app = Flask(__name__)
app.config.from_object('config')
db = SQLAlchemy(app)
from app import views,models
and I use this db object later. But I am not able to figure out how to write the
SQLALCHEMY_DATABASE_URI to login as sysdba
I also tried
CONN = cx_Oracle.connect('sys/abc', dsn='DBNAME', mode = cx_Oracle.SYSDBA)
SQLALCHEMY_DATABASE_URI = CONN
But that also doesnt work.
I get ORA-12154: TNS: could not resolve the connect identifier specified” .. also If I remove mode=SYSDBA I get ORA-28009 connection as SYS should be as SYSDBA
Your dsn parameter is wrong. You must also separate the user and password parameters. Try this (it's working for me):
dsn_tns = cx_Oracle.makedsn('host', port, 'sid')
CONN = cx_Oracle.connect('sys', 'abc', dsn_tns, mode=cx_Oracle.SYSDBA)
For more info see cx_Oracle.connect constructor.

Categories