I have this code which is receiving a call from pubnub, it takes in text and I want to store that text in a mysql database
class MySubscribeCallback(SubscribeCallback):
def message(self, pubnub, message):
messageArray = message.dict
print(messageArray['message']['sender'])
cursor = db.connection.cursor(MySQLdb.cursors.DictCursor)
I keep receiving this error when trying to run my code
cursor = db.connection.cursor(MySQLdb.cursors.DictCursor)
AttributeError: 'NoneType' object has no attribute 'cursor'
Any ideas on where the problem is?
Your code must looks like that :
from flask import Flask
from flask_mysqldb import MySQL
app = Flask(__name__)
db = MySQL(app)
# Your class/method where db.connection.cursor() is called
if __name__ == '__main__':
app.run() # or app.run(debug=True)
Follow these steps below:
You will need to install mysql connector using the command below
python -m pip install mysql-connector-python
The below code is a simple connection you can use after installing the package
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="yourusername",
password="yourpassword"
)
print(mydb)
Related
I am getting AttributeError: module 'fdb' has no attribute 'connect' only when I run the python script in IIS.
If I cd to c:\inetpub\wwwroot\ and run py app.py it works fine (http://localhost:5000 returns a result)
But if I try http://localhost I get http 500 error saying Attribute Error:module fdb has no attribute 'connect'
My simple test code is:
from flask import *
import fdb
app = Flask(__name__)
#app.route("/")
def home():
con = fdb.connect(
host='localhost',
database='c:/firebird_databases/testdb1.fdb',
user='sysdba', password='masterkey',
charset='UTF8' # specify a character set for the connection
)
mycursor = con.cursor()
sqlstmt = "select email_address, password from partners;"
mycursor.execute(sqlstmt)
for (email_address, password) in mycursor:
strings_are = email_address + ' ' + password
return strings_are
How do I save a psycopg2 connection on a flask server once I execute a query? I am trying to save connection from a different python file on flask. I am using this code:-
from flask import current_app
cursor = connection.cursor() # Connection with Database
cursor.execute(self.query)
connection.commit()
current_app.config['pool'].putconn(connection)
It gives me this error.
'Flask' object is not subscriptable
I use this in the flask init file to create a connection Pool:-
app.config['pool'] = psycopg2.pool.SimpleConnectionPool(
1, 10,
host = config["HOST"],
database = config["DATABASE"],
user = config["USER"],
password = config["PASSWORD"]
)
This is the get_db function. It works well.
from flask import current_app
def get_db(self):
return current_app.config['pool'].getconn()
I am new to flask and i am writing a basic program for login. Everytime I ammend i end with error mentioned above. below is my code for reference. Can someone please correct me.
#app.route('/')
def index():
return render_template('form_ex.html')
#app.route('/',methods = ['POST'])
def Authenticate():
login = request.form['u']
password = request.form['p']
cursor = mysql.get_db().cursor()
cursor.execute("SELECT * FROM UserLogin WHERE login=%s and password=%s")
data= cursor.fetchone()
if data is None:
return("Username or password incorrect")
else:
return("You are logged in")
By the looks of the code you didn't initialise the MySQL DB, taken from this link the answer is below: Using MySQL in Flask
Firstly you need to install Flask-MySQL package. Using pip for example:
pip install flask-mysql
Next you need to add some configuration and initialize MySQL:
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)
Now you can get connection and cursor objects and execute raw queries:
conn = mysql.connect()
cursor =conn.cursor()
cursor.execute("SELECT * from User")
data = cursor.fetchone()
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've set up an Application on OpenShift like this:
I am using Flask with python on the server-side.
Note: I just need to connect Python to MySQL, Flask is irrelevant.
My Hello World program works fine:
flaskapp.py
from flask import Flask
app = Flask(__name__)
#app.route('/')
def hello_world():
return "Hello World!"
if __name__ == '__main__':
app.run()
In the requirements.txt the following dependency was added: Flask==0.10.1
I'm wondering is it necessary to add the MySQL dependency, like this: MySQLdb==5.5?
I've tried importing and using MySQL in flaskapp.py like this:
from flask import Flask
import mysql # I tried MySQLdb as well
app = Flask(__name__)
#app.route('/')
def hello_world():
output = ''
db = mysql.connect(host="mysql://$OPENSHIFT_MYSQL_DB_HOST:$OPENSHIFT_MYSQL_DB_PORT/", # your host, usually localhost
user="adminIChJ87N",
passwd="mypassword",
db="python")
cur = db.cursor()
cur.execute("SELECT * FROM MyTable")
for row in cur.fetchall():
output+=row[0]
db.close()
return output
if __name__ == '__main__':
app.run()
How exactly do I use this MySQL database with Python? There seems to be no code on Openshift's website
The name of the package for MySQLdb is mysqlclient (if you want it to work with Python3, otherwise it is a fork of MySQL-python). So this is what you need to put in the dependencies. Run pip install mysqlclient to try it.