[英]How to use Flask with mysql (without sqlalchemy - raw sql query)?
I'm learning Flask framework. 我正在学习Flask框架。 How to use Flask with mysql (without sqlalchemy - raw sql query)?
如何在MySQL中使用Flask(不使用sqlalchemy-原始SQL查询)?
Here is example from official tutorial, how to configure it to use mysql? 这是官方教程的示例,如何配置它以使用mysql?
from sqlite3 import dbapi2 as sqlite3
from flask import Flask, request, session, g, redirect, url_for, abort, render_template, flash
# create our little application :)
app = Flask(__name__)
# Load default config and override config from an environment variable
app.config.update(dict(
DATABASE='/tmp/firma.db',
DEBUG=True,
SECRET_KEY='development key',
USERNAME='admin',
PASSWORD='default'
))
app.config.from_envvar('FIRMA_SETTINGS', silent=True)
def connect_db():
"""Connects to the specific database."""
rv = sqlite3.connect(app.config['DATABASE'])
rv.row_factory = sqlite3.Row
return rv
def init_db():
"""Creates the database tables."""
with app.app_context():
db = get_db()
with app.open_resource('firma.sql', mode='r') as f:
db.cursor().executescript(f.read())
db.commit()
def get_db():
"""Opens a new database connection if there is none yet for the
current application context.
"""
if not hasattr(g, 'sqlite_db'):
g.sqlite_db = connect_db()
return g.sqlite_db
@app.teardown_appcontext
def close_db(error):
"""Closes the database again at the end of the request."""
if hasattr(g, 'sqlite_db'):
g.sqlite_db.close()
@app.route('/')
def show_entries():
db = get_db()
cur = db.execute('select title, text from entries order by id desc')
entries = cur.fetchall()
return render_template('show_entries.html', entries=entries)
...
How to configure it to use mysql? 如何配置它以使用mysql?
You need a mysql driver. 您需要一个mysql驱动程序。 Python doesn't come with one by default.
Python默认不附带一个。 You'll have to install a 3rd party library like MySQLdb .
您必须安装第3方库,例如MySQLdb 。 Even if you use an ORM like sqlalchemy, you'll still need to install the driver.
即使您使用像sqlalchemy这样的ORM,您仍然需要安装驱动程序。 Also, you can run raw SQL with sqlalchemy.
另外,您可以使用sqlalchemy运行原始SQL。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.