4
# main.py
from flask import Flask, jsonify
from flask.ext.cors import CORS
from shared.database import db
from src import controllers
import os
app = Flask(__name__)
cors = CORS(app, allow_headers='Content-Type')
app.register_blueprint(controllers.api)
if (os.getenv('SERVER_SOFTWARE') and os.getenv('SERVER_SOFTWARE').startswith('Google App Engine/')):
app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql+gaerdbms:///gaiapro_api_dev?instance=dev-gaiapro-api:gaiapro-sql'
else:
app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql+mysqldb://[email protected]/gaiapro_api_dev'
app.config['DEBUG'] = True
db.init_app(app)
# shared/database.py
from flask.ext.sqlalchemy import SQLAlchemy
db = SQLAlchemy()
# src/controllers/__init__.py
from flask import Blueprint, jsonify, request
from src import models
from src import views
from shared.helpers import *
api = Blueprint('api', __name__)
@api.route('/test')
def test():
...
# shared/helpers.py
from flask import jsonify, request, abort, make_response
from shared.database import db
def some_method():
...
db.session.commit() # Can access db normally from here
# src/models/__init__.py
from shared.database import db
class Client(db.Model):
id = db.Column(db.Integer, primary_key=True)
...
我正在爲GAE(Google App Engine)開發。基本上我想要從_dev_appserver.py_的管理服務器內的交互式控制檯中測試我的模型。從Interactive Console運行代碼時無法訪問db
我試圖從交互式控制檯運行下面的代碼:
from main import *
from src import models
print models.Client.query.get(1)
結果是:
RuntimeError:應用程序未註冊的數據庫實例,並沒有綁定到當前上下文應用
如果我試圖在此上下文中輸出變量db t他的結果是:SQLAlchemy引擎=無
我不知道我在做什麼錯。我的代碼通常在瀏覽器上運行,但我無法從交互式控制檯中運行。
它完美地工作。非常感謝你! – stefanobaldo