Setting Up Flask DB2 connection - python

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.

Related

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 to fix circular import in Flask project using blueprints MySQL w/o SQLAlchemy?

So I have main .py file where Flask app object is created and configured, and MySQL is initialized. Then I want to register some blueprint.
from flask import Flask
from flaskext.mysql import MySQL
app = Flask(__name__)
mysql = MySQL()
app.config['MYSQL_DATABASE_USER'] = 'root'
app.config['MYSQL_DATABASE_PASSWORD'] = 'root'
app.config['MYSQL_DATABASE_DB'] = 'EmpData'
app.config['MYSQL_DATABASE_HOST'] = 'localhost'
mysql.init_app(app)
from views1 import views1_blprnt
app.register_blueprint(views1_blprnt)
But in views1.py I need MySQL object to get connection and cursor objects to execute queries. And, of course, when I try to import it I get the ImportError. I've read some similar questions and workarounds, but all of them were using SQLAlchemy. Does someone have any ideas how to resolve it?
Thank you for your help and sorry for my english.
A fairly typical pattern here is to use a third module where you initialize mysql and any other resources you want to share among your blueprints.
I've noticed that people tend to call it extensions.py. So you might do something like this in extension.py:
from flaskext.mysql import MySQL
mysql = MySQL()
And in your main.py, something like this:
from extensions import mysql
app.config['MYSQL_DATABASE_USER'] = 'root'
app.config['MYSQL_DATABASE_PASSWORD'] = 'root'
app.config['MYSQL_DATABASE_DB'] = 'EmpData'
app.config['MYSQL_DATABASE_HOST'] = 'localhost'
mysql.init_app(app)
You'd access the initialized mysql instance from all your blueprints like so:
from extensions import mysql
mysql....
There are other solutions, but this is what I see done most often. It's what I usually do as well.

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