Python/Flask mysql cursor: Why it doesn't work? - python

from flask import Flask
from flask_mysqldb import MySQL
app = Flask(__name__)
app.config['MYSQL_HOST'] = 'localhost'
app.config['MYSQL_USER'] = 'root'
app.config['MYSQL_PASSWORD'] = 'password'
app.config['MYSQL_DB'] = 'todoapp'
app.config['MYSQL_CURSORCLASS'] = 'DictCursor'
mysql = MySQL(app)
cur = mysql.connection.cursor()
if __name__ == '__main__':
app.run()
There is error which is displayed after executing program:
cur = mysql.connection.cursor()
AttributeError: 'NoneType' object has no attribute 'cursor'.
According to documentaction it should work. I use Ubuntu 16.04, I have installed MySQL and it works properly. Could anyone explain why it doesn't work?

You are constructing cursor based on flask_mysqldb , and Flask app won't be constructed itself up until the first route is hit, which means the Flask app will be constructed inside a Flask Function, and that is when your MySQL connection also can be constructed based on your app.config params, and then your cursor can be constructed based on MySQL connection:
Flask Construction > MySQL Connection Construction > Cursor Construction.
So you have to use your cursor constructor inside a Flask Function:
Instead of:
cur = mysql.connection.cursor()
Put:
#app.route("/")
def index():
cur = mysql.connection.cursor()

I used the connect() method instead of get_db() and it works with Python 3.5.5. I had the same error when I used get_db
from flask import Flask
from flaskext.mysql import MySQL
app = Flask(__name__)
app.config['MYSQL_DATABASE_USER'] = 'root'
app.config['MYSQL_DATABASE_PASSWORD'] = 'root'
app.config['MYSQL_DATABASE_DB'] = 'test_db'
app.config['MYSQL_DATABASE_HOST'] = 'localhost'
mysql = MySQL()
mysql.init_app(app)
# cursor = mysql.get_db().cursor()
cursor = mysql.connect().cursor()
print(cursor)

The problem is in :
app.config['MYSQL_CURSORCLASS'] = 'DictCursor'
Looking at flaskext.mysql source , that feature is not yet implemented .
And since flaskext.mysql is using pymysql , you can use DictCursor from pymysql.cursors
Example :
from flaskext.mysql import MySQL
from flask import Flask
from pymysql import cursors
app=Flask(__name__)
mysql = MySQL(cursorclass=cursors.DictCursor)
mysql.init_app(app)
cursor = mysql.connect().cursor()

app.config['MYSQL_HOST'] = 'localhost'
app.config['MYSQL_DATABASE_PORT'] = 3308 #here your port

It maybe that you need to init the app for MySQL context.
from flask import Flask
from flask_mysqldb import MySQL
app = Flask(__name__)
mysql = MySQL()
mysql.config['MYSQL_HOST'] = 'localhost'
mysql.config['MYSQL_USER'] = 'root'
mysql.config['MYSQL_PASSWORD'] = 'password'
mysql.config['MYSQL_DB'] = 'todoapp'
mysql.config['MYSQL_CURSORCLASS'] = 'DictCursor'
mysql.init_app(app)
cur = mysql.connection.cursor()
if __name__ == '__main__':
app.run()

Related

flask_mysqldb - MYSQL cursor is throwing an error - cursor is not a known member of "None"

I am writing a simple auth service in python using flask and flask_mysqldb. There is an error with the cursor.
import jwt
from flask import Flask, request
from flask_mysqldb import MySQL
server = Flask(__name__)
mysql = MySQL(server)
# server configuration
server.config["MYSQL_HOST"] = os.environ.get("MYSQL_HOST")
server.config["MYSQL_USER"] = os.environ.get("MYSQL_USER")
server.config["MYSQL_PASSWORD"] = os.environ.get("MYSQL_PASSWORD")
server.config["MYSQL_DB"] = os.environ.get("MYSQL_DB")
server.config["MYSQL_PORT"] = os.environ.get("MYSQL_PORT")
# print(server.config["MYSQL_HOST"])
# print(server.config["MYSQL_PORT"])
#server.route("/login", methods=["POST"])
def login():
auth = request.authorization
if not auth:
return "missing credentials",401
#check db for username and password
cur = mysql.connection.cursor()
res = cur.execute(
"SELECT email,password FROM user WHERE email=%s, (auth.username)"
)
This works on a virtual environment. All the specified packages are correctly installed.
Please try
cur = mysql.connect.cursor()
if you use a connection it will not suggest cursor(). once you use connect.cursor() it will not show the error. Thanks

TypeError: cursor() got an unexpected keyword argument 'dictionary' using flaskext.mysql

I'm using flask framework and MySQL database connector.
I did the below:
from flaskext.mysql import MySQL
mysql = MySQL()
## app.config database configuration code
mysql.init_app(app)
conn = mysql.connect()
cursor = conn.cursor();
cursor.execute(
'SELECT * FROM customer WHERE email = (%s)', (username,)
)
user = cursor.fetchone()
I can access the user columns using index like user[8] (which I need to execute the query once and check the column number), but when I try to specify
conn = mysql.connect(dictionary=True)
I get the error
'TypeError: cursor() got an unexpected keyword argument 'dictionary''
Is there a way to get the results of the query in dictionary format when using flask-MySQL?
You can follow this answer: https://stackoverflow.com/a/41388992/3129414
Existing code modification:
use DictCursor in MySQL initialization
remove dictionary=True from cursor
use json package to convert dictionary items to json format
app.py:
import json
from flask import Flask
from flaskext.mysql import MySQL
from pymysql.cursors import DictCursor
app = Flask(__name__)
app.config['MYSQL_DATABASE_USER'] = 'root'
app.config['MYSQL_DATABASE_PASSWORD'] = '123'
app.config['MYSQL_DATABASE_DB'] = 'practice_db'
app.config['MYSQL_DATABASE_HOST'] = 'localhost'
mysql = MySQL(cursorclass=DictCursor)
mysql.init_app(app)
conn = mysql.connect()
#app.route("/", methods=['GET'])
def home():
email_address = 'dummy#example.com'
cursor = conn.cursor();
cursor.execute(
'SELECT * FROM user_table WHERE email = (%s)', (email_address,)
)
users = cursor.fetchall()
return json.dumps(users)
app.run(debug=True)
Screenshot:

Flask flaskext.mysql no attribute connection

I'm trying to establish a connection to an sql database, but I end up with
AttributeError: 'MySQL' object has no attribute 'connection'
I've read through the documentation, and it looks like this is the proper way to create a cursor:
from flask import Flask
from flaskext.mysql import MySQL
app = Flask(__name__)
app.config['MYSQL_HOST'] = 'sql3.freemysqlhosting.net'
app.config['MYSQL_USER'] = 'sql1234567'
app.config['MYSQL_PASSWORD'] = 'abcdefg'
app.config['MYSQL_DB'] = 'sql1234567'
app.config['MYSQL_PORT'] = '3306'
mysql = MySQL(app)
#app.route('/')
def index():
cur = mysql.connection.cursor()
cur.execute('''SELECT * FROM users''')
rv = cur.fetchall()
return str(rv)
if __name__ == '__main__':
app.run(debug=True)
Edit: using https://www.youtube.com/watch?v=nWO_VpI5wn8 as a tutorial and the docs are http://flask-mysqldb.readthedocs.io/en/latest/
You are importing incorrect module here.
Solution is
Instead of importing
from flaskext.mysql import MySQL
import this which is different module (Follow this)
from flask_mysqldb import MySQL
This looks like an auto import issue from some IDE. As these two modules are different, you can install these two packages as following:
pip install flask-mysqldb and
pip install flask-mysql
EDIT
If you want to use the previous module, you will have to follow this and the cursor can be used as following:
from flaskext.mysql import MySQL
mysql = MySQL()
mysql.init_app(app)
cursor = mysql.get_db().cursor()

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)

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