Flask-MySQL allows you to access MySQL directly from your flask application.
To install it :
pip install Flask-MySQL
To suggest a feature or report a bug : https://github.com/cyberdelia/flask-mysql/issues
Flask extension for python-mysql
Home Page: https://flask-mysql.readthedocs.org
License: MIT License
Flask-MySQL allows you to access MySQL directly from your flask application.
To install it :
pip install Flask-MySQL
To suggest a feature or report a bug : https://github.com/cyberdelia/flask-mysql/issues
Is this a proper use of this extension? I need to access two databases from same function/route. It seems to work with a non-default port only if I add the app.config['MYSQL_DATABASE_PORT'] = 3366
line. It ignores the port specified in connection DSN.
from flaskext.mysql import MySQL
app = Flask(__name__)
app.config['MYSQL_DATABASE_PORT'] = 3366
mysql = MySQL(app, host='localhost', port='3366', user='root', passwd='xxxx', db='recall_qa')
mysql2 = MySQL(app, host='localhost', port='3366', user='root', passwd='xxxx', db='recall_v_qa')
@app.route('/')
def hello_world():
conn = mysql.connect()
cursor = conn.cursor()
cursor.execute('select count(*) from events')
data = cursor.fetchall()
conn2 = mysql2.connect()
cursor2 = conn2.cursor()
cursor2.execute('select count(*) from language_translations')
data2 = cursor2.fetchall()
return jsonify(data, data2)
i tried adding as app.config['MYSQL_CURSOR'] = 'DictCursor' & app.config['MYSQL_DATABASE_CURSOR'] = 'DictCursor' but did not work please help confused.
i am getting that error,how may i go about please
Is there any documentation that lists all the methods with an explanation?
Is there at least MySQL class code with some comments? I cant find anything :(.
Only found this: https://flask-mysql.readthedocs.io/en/stable/ which only helps for the start.
Best regrads
error: Microsoft Visual C++ 10.0 is required. Get it with "Microsoft Windows SDK 7.1": www.microsoft.com/download/details.aspx?id=8279
but i already have install several versions of it ...
22a23
self.app.config.setdefault('MYSQL_DATABASE_CHARSET', 'utf8')
37a39,40
if self.app.config['MYSQL_DATABASE_CHARSET']:
kwargs['charset'] = self.app.config['MYSQL_DATABASE_CHARSET']
suggest adding these lines.
flask-mysql depends on MySQL-python package that does not work with python 3.
Is it possible to switch dependency from mysql-python to other database driver like PyMySQL with full python 3 support?
At the moment, I don't see any configuration variable that would allow me to add certificate. On my flask app I am getting error pymysql.err.InternalError: (3159, 'Connections using insecure transport are prohibited while --require_secure_transport=ON.') if I am forcing secure connections to the database. Can you please add using secure connections to the library?
Now, I need
if self.app.config['MYSQL_CURSORCLASS']:
self.connect_args['cursorclass'] = self.app.config['MYSQL_CURSORCLASS']
But the above code is not in v1.5.1
Thanks
Insert Query is retuning true, but data is not getting inserted into the table. Its showing error when i gave commit.
I'd like to use MySQLdb's DictCursor but there doesn't seem to be any way to pass arbitrary keywords to the internal MySQLdb.connect() call - just the connection and charset settings. Is that true?
i try to do a proyect but.....pum!!! this the error that always appear
AttributeError
AttributeError: 'function' object has no attribute 'commit'
if anybody know the solucion please tell me
I have tried to install flask-mysql both by pip
and by downloading the github repo and then doing python setup.py install
.
Both the time I get the error as follows:
gcc.exe: error: /Zl: No such file or directory
error: Setup script exited with error: command 'G:\\Packaged_Software_bundles\\WinPython-64bit-2.7.10.3\\python-2.7.10.amd64\\Scripts\\gcc.exe' failed
with exit status 1
Hello,
We're trying to build an API using flask-mysql. When flask has DEBUG=True we're getting the error below.
AssertionError
AssertionError: A setup function was called after the first request was handled. This usually indicates a bug in the application where a module was not imported and decorators or other functionality was called too late.
To fix this make sure to import all your view modules, database models and everything related at a central place before the application starts serving requests.
Once we remove the DEBUG flask option the application is able to communicate with the MYSQL database just fine.
from flask_mysql import MySQL
: Any
Expected module namePylance
Expected "import"
I am continue resolving that problem
MYSQL_DATABASE_CURSORCLASS = 'DictCursor'
and MYSQL_CURSORCLASS = 'DictCursor'
doesn't work
/usr/lib64/python2.7/site-packages/flask/exthook.py:71: ExtDeprecationWarning: Importing flask.ext.mysql is deprecated, use flask_mysql instead.
.format(x=modname), ExtDeprecationWarning
I am using Python 2.7.5
I installed flask-mysql and so on... I already have a few database stored proc working and using in my .py files..... All this works on my RPI 3. but, now, I am deploying the application to the Centos 7 and Apache Server 2.4.
the /var/log/httpd/error_log says:
[Mon Nov 14 10:55:37.688313 2016] [:error] [pid 23145] .format(x=modname), ExtDeprecationWarning
[Mon Nov 14 10:55:37.696461 2016] [:error] [pid 23145] /usr/lib64/python2.7/site-packages/flask/exthook.py:106: ExtDeprecationWarning: Detected extension named flaskext.mysql, please rename it to flask_mysql. The old form is deprecated.
[Mon Nov 14 10:55:37.696477 2016] [:error] [pid 23145] .format(x=modname), ExtDeprecationWarning
current situation:
my apache server is running. but, error.
[root@localhost httpd]# curl http://localhost
<title>404 Not Found</title>The requested URL was not found on the server. If you entered the URL manually please check your spelling and try again.
in my wsgi file (in /var/www/html/myapplication folder, I have a myapplication.wsgi)
Hi guys
When using following code, I get an TypeError:
connection=mysql.connect(use_unicode=True, charset='utf8')
pymysql has this functionality, and it would be really handy to get this in flask-mysql as well.
I'll see if I can submit a patch for it. If there is any clues on for to work this out, I'll would appreciate to know them :)
is it hard to implement such need ?
I'm using Mac OS X, and Flask with pypy..
The error traces back to this:
file.write('Author: %s\n' % self.get_contact() )
UnicodeEncodeError: 'ascii' codec can't encode character u'\xe9' in position 14: ordinal not in range(128)
not installing in my virtualenv,, but when i put sudo ahead then it will install but not in my virtualenv ??how to install it in virtualenv
HI, I tried to install flask-mysql in windows 7, but I got this
Installing collected packages: MySQL-python, flask-mysql
Running setup.py install for MySQL-python
Complete output from command C:\Python34\python.exe -c "import setuptools, tokenize;file='C:\Users\alotfi\AppData\Local\Temp\pip-build-nwlewwl5\MySQL-python\setup.py';exec(compile(getattr(tokenize, 'open', open)(file).read().replace('\r\n', '\n'), file, 'exec'))" install --record C:\Users\alotfi\AppData\Local\Temp\pip-rbf1ujnn-record\install-record.txt --single-version-externally-managed --compile:
running install
running build
running build_py
creating build
creating build\lib.win-amd64-3.4
copying mysql_exceptions.py -> build\lib.win-amd64-3.4
creating build\lib.win-amd64-3.4\MySQLdb
copying MySQLdb__init_.py -> build\lib.win-amd64-3.4\MySQLdb
copying MySQLdb\converters.py -> build\lib.win-amd64-3.4\MySQLdb
copying MySQLdb\connections.py -> build\lib.win-amd64-3.4\MySQLdb
copying MySQLdb\cursors.py -> build\lib.win-amd64-3.4\MySQLdb
copying MySQLdb\release.py -> build\lib.win-amd64-3.4\MySQLdb
copying MySQLdb\times.py -> build\lib.win-amd64-3.4\MySQLdb
creating build\lib.win-amd64-3.4\MySQLdb\constants
copying MySQLdb\constants__init__.py -> build\lib.win-amd64-3.4\MySQLdb\constants
copying MySQLdb\constants\CR.py -> build\lib.win-amd64-3.4\MySQLdb\constants
copying MySQLdb\constants\FIELD_TYPE.py -> build\lib.win-amd64-3.4\MySQLdb\constants
copying MySQLdb\constants\ER.py -> build\lib.win-amd64-3.4\MySQLdb\constants
copying MySQLdb\constants\FLAG.py -> build\lib.win-amd64-3.4\MySQLdb\constants
copying MySQLdb\constants\REFRESH.py -> build\lib.win-amd64-3.4\MySQLdb\constants
copying MySQLdb\constants\CLIENT.py -> build\lib.win-amd64-3.4\MySQLdb\constants
running build_ext
building '_mysql' extension
Traceback (most recent call last):
File "", line 1, in
File "C:\Users\alotfi\AppData\Local\Temp\pip-build-nwlewwl5\MySQL-python\setup.py", line 21, in
setuptools.setup(**metadata)
File "C:\Python34\lib\distutils\core.py", line 148, in setup
dist.run_commands()
File "C:\Python34\lib\distutils\dist.py", line 955, in run_commands
self.run_command(cmd)
File "C:\Python34\lib\distutils\dist.py", line 974, in run_command
cmd_obj.run()
File "C:\Python34\lib\site-packages\setuptools\command\install.py", line 61, in run
return orig.install.run(self)
File "C:\Python34\lib\distutils\command\install.py", line 539, in run
self.run_command('build')
File "C:\Python34\lib\distutils\cmd.py", line 313, in run_command
self.distribution.run_command(command)
File "C:\Python34\lib\distutils\dist.py", line 974, in run_command
cmd_obj.run()
File "C:\Python34\lib\distutils\command\build.py", line 126, in run
self.run_command(cmd_name)
File "C:\Python34\lib\distutils\cmd.py", line 313, in run_command
self.distribution.run_command(command)
File "C:\Python34\lib\distutils\dist.py", line 974, in run_command
cmd_obj.run()
File "C:\Python34\lib\site-packages\setuptools\command\build_ext.py", line 50, in run
_build_ext.run(self)
File "C:\Python34\lib\distutils\command\build_ext.py", line 339, in run
self.build_extensions()
File "C:\Python34\lib\distutils\command\build_ext.py", line 448, in build_extensions
self.build_extension(ext)
File "C:\Python34\lib\site-packages\setuptools\command\build_ext.py", line 183, in build_extension
_build_ext.build_extension(self, ext)
File "C:\Python34\lib\distutils\command\build_ext.py", line 503, in build_extension
depends=ext.depends)
File "C:\Python34\lib\distutils\msvc9compiler.py", line 460, in compile
self.initialize()
File "C:\Python34\lib\distutils\msvc9compiler.py", line 371, in initialize
vc_env = query_vcvarsall(VERSION, plat_spec)
File "C:\Python34\lib\site-packages\setuptools\msvc9_support.py", line 52, in query_vcvarsall
return unpatched['query_vcvarsall'](version, *args, **kwargs)
File "C:\Python34\lib\distutils\msvc9compiler.py", line 287, in query_vcvarsall
raise ValueError(str(list(result.keys())))
ValueError: ['path']
----------------------------------------
Command "C:\Python34\python.exe -c "import setuptools, tokenize;file='C:\Users\alotfi\AppData\Local\Temp\pip-build-nwlewwl5\MySQL-python\setup.py';exec(compile(getattr(tokenize, 'open', open)(file).read().replace('\r\n', '\n'), file, 'exec'))" install --record C:\Users\alotfi\AppData\Local\Temp\pip-rbf1ujnn-record\install-record.txt --single-version-externally-managed --compile" failed with error code 1 in C:\Users\alotfi\AppData\Local\Temp\pip-build-nwlewwl5\MySQL-python
Hello I'm deploying my application on heroku using ClearDB MySQL.
This platform provides the connection string to the database on an environment variable named CLEARDB_DATABASE_URL
that contains a value like that
mysql://username:password@host/databasename?reconnect=true
Is it possible to use directly this string in order to connect my Flask application to this MySQL database without creating a script that parse this string ?
I know that I can specify the configuration like that
from flask import Flask
from flaskext.mysql import MySQL
app = Flask(__name__)
app.config['MYSQL_DATABASE_USER'] = 'username'
app.config['MYSQL_DATABASE_PASSWORD'] = 'password'
app.config['MYSQL_DATABASE_DB'] = 'databasename'
app.config['MYSQL_DATABASE_HOST'] = 'host'
mysql = MySQL()
mysql.init_app(app)
but it will be better for me to be able to specify the configuration like that
from flask import Flask
from flaskext.mysql import MySQL
import os
app = Flask(__name__)
app.config['CONNECTION_STRING'] = os.environ['CLEARDB_DATABASE_URL']
mysql = MySQL()
mysql.init_app(app)
Is it possible to do something like that?
Well I was wondering if it's possible to obtain column names after executing a query just like the way I obtain results from a cursor after executing a query, ie
cursor.execute('certain sql statement')
cursor.fetchall() this is for obtaining all results
cursor.getcolumns() this is what am asking if it's possible to do
For example I just want to be able to get Reg_No, First_Name, Last_Name and Course from a certain query executed and give results as shown in a picture below.
If I don't have the MySQL database credentials during initialization, how do I configure/connect to the db at a later point?
running mysql.init_app(app) at runtime fails with error.
i wan to use flask mysql db in visual std code but can not importing. i have installed flask-mysql on ubuntu 18.04.
how can i import flask mysql
Hi, sorry if this is obvious but I'm new to flask. Is there a correct way to get access to the mysql variable off the stack if the caller isn't in the same file?
For reference, my use case is I have some models inheriting from a base_object and want to perform DB operations in that file without having to pass the mysql instance down as an argument to a bunch of functions. Much appreciated!
What is the difference between connect()
and get_db()
?
Does get_db()
work with g
and close connection when app context tear down?
# -*- coding: UTF-8 -*- from __future__ import absolute_import import MySQLdb from flask import _request_ctx_stack """ from flask.ext import MySQL from MySQLdb.cursors import DictCursor from flask import Flask app = Flask(__name__) sql = MySQL(autocommit = True, cursorclass = DictCursor) sql.init_app(app) @app.route('/') def index(): cur = sql.get_db().cursor() cur.execute('select now() as timenow') res = fetchone() return "time now: " + res['timenow'] """ class MySQL(object): def __init__(self, app=None, prefix='MYSQL', autocommit = Flase, cursorclass = None): self.prefix = prefix self.autocommit = autocommit self.cursorclass = cursorclass if app is not None: self.app = app self.init_app(self.app) else: self.app = None def init_app(self, app): self.app = app self.app.config.setdefault(self.prefix + '_DATABASE_HOST', 'localhost') self.app.config.setdefault(self.prefix + '_DATABASE_PORT', 3306) self.app.config.setdefault(self.prefix + '_DATABASE_USER', None) self.app.config.setdefault(self.prefix + '_DATABASE_PASSWORD', None) self.app.config.setdefault(self.prefix + '_DATABASE_DB', None) self.app.config.setdefault(self.prefix + '_DATABASE_CHARSET', 'utf8') self.app.config.setdefault(self.prefix + '_DATABASE_USE_UNICODE', True) self.app.teardown_request(self.teardown_request) self.app.before_request(self.before_request) def connect(self): kwargs = {} if self.app.config[self.prefix + '_DATABASE_HOST']: kwargs['host'] = self.app.config[self.prefix + '_DATABASE_HOST'] if self.app.config[self.prefix + '_DATABASE_PORT']: kwargs['port'] = self.app.config[self.prefix + '_DATABASE_PORT'] if self.app.config[self.prefix + '_DATABASE_USER']: kwargs['user'] = self.app.config[self.prefix + '_DATABASE_USER'] if self.app.config[self.prefix + '_DATABASE_PASSWORD']: kwargs['passwd'] = self.app.config[self.prefix + '_DATABASE_PASSWORD'] if self.app.config[self.prefix + '_DATABASE_DB']: kwargs['db'] = self.app.config[self.prefix + '_DATABASE_DB'] if self.app.config[self.prefix + '_DATABASE_CHARSET']: kwargs['charset'] = self.app.config[self.prefix + '_DATABASE_CHARSET'] if self.app.config[self.prefix + '_DATABASE_USE_UNICODE']: kwargs['use_unicode'] = self.app.config[self.prefix + '_DATABASE_USE_UNICODE'] if self.cursorclass: kwargs['cursorclass'] = self.cursorclass db = MySQLdb.connect(**kwargs) db.autocommit(self.autocommit) return db def before_request(self): ctx = _request_ctx_stack.top if hasattr(ctx, 'mysql_cons'): ctx.mysql_cons[self.prefix] = self.connect() else: ctx.mysql_cons = {self.prefix : self.connect()} def teardown_request(self, exception): ctx = _request_ctx_stack.top if hasattr(ctx, 'mysql_cons'): ctx.mysql_cons[self.prefix].close() def get_db(self): ctx = _request_ctx_stack.top if ctx is not None: return ctx.mysql_cons[self.prefix]
The “Multiple Connections Example” in the “Usage” section at https://flask-mysql.readthedocs.io/en/stable/ should be indented so that line breaks are preserved. (See attached screenshot)
MySQLdb._exceptions.OperationalError: (2026, 'SSL connection error: unknown error number')
getting this error
Hi, I'm trying to install flask-mysql on Windows, and I'm wondering if there are .whl binaries available (to avoid compiler errors). Thanks.
The version of this repo on pypi is too old, can we update it? @cyberdelia
Please give a docs to explain how to use this. Even it is just so easy to you.Thank you!
When running the code on the buttom on development mode with restart on the code will get stack when it's supposed to return the app the entire app will get stuck. Run the same code without the restart (using production or --no-reload) and the code will work. remove the gepass (or any other thing that will wait for input, such as input()) and the app will work.
from flask import Flask
from getpass import getpass
from flaskext.mysql import MySQL
def create_app(test_config=None):
# Create and configure the create_app
app = Flask(__name__, instance_relative_config=True)
# Connect us to the MySQL server
breaker = True
while breaker:
try:
mysql = MySQL()
app.config['MYSQL_DATABASE_USER'] = 'server'
app.config['MYSQL_DATABASE_PASSWORD'] = getpass()
app.config['MYSQL_DATABASE_DB'] = 'flask_tutorial'
app.config['MYSQL_DATABASE_HOST'] = 'localhost'
mysql.init_app(app)
conn = mysql.connect()
cursor = conn.cursor()
cursor.execute("SELECT 1")
cursor.fetchall()
cursor.close()
conn.close()
breaker = False
except Exception as E:
print(E)
print("11")
# a simple page that will
@app.route('/hello')
def hello():
return 'Hello, World!'
return app
Hi,
in new Flask 3.0.0 authors decided to remove deprecated method _request_ctx_stack.
Unfortunately your flask-mysql use them what cause exception during booting.
i want to konw if insert successfully is there a response? or i need to insert then to query?
sqlStatement = "INSERT INTO `users` (`userName`, `passWord`, `roleID`) VALUES (%s, %s, 2);"
cursor = mysql.connect().cursor()
cursor.execute(sqlStatement, (userName, passWord))
????
if ????:
return 'ok'
else:
return
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.