2015-04-08 84 views
1

我正在構建一個簡單的使用現有MySQL數據庫的網絡應用程序。這是我第一次使用Flask,我一直在努力理解過去幾個小時我做錯了什麼。燒瓶+ MySQL的奇怪行爲

我簡單的項目結構:

/root 
/app 
    __init__.py 
    db.py 
    forms.py 
    views.py 
    /templates 
    base.html 
    index.html 
    login.html 
config.py 
run.py 

我想查詢我的MySQL數據庫,並從查詢結果填寫模板。

我db.py:

from app import app 
from flaskext.mysql import MySQL 


class DB(object): 
    mysql = MySQL() 

    def __init__(self): 
     app.config['MYSQL_DATABASE_USER'] = 'loguser' 
     app.config['MYSQL_DATABASE_PASSWORD'] = 'asdzxc' 
     app.config['MYSQL_DATABASE_DB'] = 'log' 
     app.config['MYSQL_DATABASE_HOST'] = '127.0.0.1' 
     app.config['MYSQL_DATABASE_PORT'] = 33006 
     self.mysql.init_app(app) 

    def query_db(self): 
     cursor = self.mysql.connect().cursor() 
     cursor.execute("SELECT name from users limit 1") 
     data = cursor.fetchone() 
     if data is None: 
      return "No results from query" 
     else: 
      return data 

而在我的views.py我有以下幾點:

from flask import render_template, flash, redirect 
from app import app 
from .forms import LoginForm 
from .db import DB 

@app.route('/') 
@app.route('/index') 
def index(): 
    db = DB() 
    user = db.query_db() 
    print(user) (it prints it here so the db connection works) 


    posts = [ # fake array of posts 
     { 
      'author': {'nickname': 'John'}, 
      'body': 'Beautiful day in Portland!' 
     }, 
     { 
      'author': {'nickname': 'Susan'}, 
      'body': 'The Avengers movie was so cool!' 
     } 
    ] 
    return render_template("index.html", 
          title='Home', 
          user=user, 
          posts=posts) 

我得到 「Asse田」 當我嘗試指派 「用戶」 用戶從模板:

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.

我相信我違反了框架的一個主要原則。將數據傳遞給模板的正確方法是什麼?

回答

1

最好使用Flask-SQLAlchemy和MySQL-python 1.2,成功的代碼和文檔可在下面的鏈接中找到。

http://techarena51.com/index.php/flask-sqlalchemy-tutorial/

從我的經驗,我發現,MySQL的支持是不是蟒蛇3 ATLEAST,最好是使用PostgreSQL的好,不過這只是我個人的意見。

0

給出答案已經很晚了,但它可能對某人有幫助。

在將任何路由源添加到API之前,您必須連接到MySQL

它應該在的

# 1. MySQL setup should be done at first 
app = Flask(__name__) 
api = Api(app) 
mysql = MySQL() 

app.config['MYSQL_DATABASE_USER'] = 'root' 
app.config['MYSQL_DATABASE_PASSWORD'] = 'root' 
app.config['MYSQL_DATABASE_DB'] = 'DataBase' 
app.config['MYSQL_DATABASE_HOST'] = 'localhost' 
mysql.init_app(app) 
conn = mysql.connect() 
cursor = conn.cursor() 

# 2. Create API resource after that 
api.add_resource(CreateUser, '/CreateUser') 
順序