2014-02-06 60 views
0

我正在學習Flask框架。如何使用Flask與MySQL(沒有sqlalchemy - 原始的SQL查詢)?如何使用Flask與MySQL(沒有sqlalchemy - 原始的sql查詢)?

這裏是從官方教程的例子,如何配置它使用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) 
... 

如何配置它使用mysql?

+0

嘗試用這種[MySQLdb的(http://mysql-python.sourceforge.net/MySQLdb.html#mysqldb) –

+0

你不使用sqlite3的任何原因?在沒有模型的情況下執行原始sql非常容易。 – metersk

+0

看看這個http://www.techillumination.in/2014/01/python-web-application-development.html – iJade

回答

0

您需要一個mysql驅動程序。 Python默認沒有。您必須安裝第三方庫,如MySQLdb。即使你使用像sqlalchemy這樣的ORM,你仍然需要安裝驅動程序。此外,您可以使用sqlalchemy運行原始SQL。

+0

可以在燒瓶內運行原始SQL查詢嗎?我已經讀過SQL注入有它在安全性方面有其自身的缺陷。 – NSP

+1

@NSP在服務器端運行原始SQL沒有任何問題。當您開始使用用戶輸入作爲SQL請求的一部分時,問題就出現了。流行的ORM庫在構建查詢時有很多保護措施,如果您只是自己構建原始的sql字符串,您不會收到這些查詢。 –

相關問題