简体   繁体   中英

Cannot access db when running code from Interactive Console

# 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://root@127.0.0.1/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)
    ...

I am developing for GAE (Google App Engine). Basically what I want is to test my models in the Interactive Console from inside the Admin Server of _dev_appserver.py_.

I have tried to run the following code from the Interactive Console :

from main import *
from src import models
print models.Client.query.get(1)

The result was:

RuntimeError: application not registered on db instance and no application bound to current context

If I try just to print the db variable in this context, the result is: SQLAlchemy engine=None

I don't know what I am doing wrong. My code runs normally on the browser, but I cannot get it to work from the Interactive Console .

You need to be in an app context (or a request context) to access application bound objects.

An easy way to achieve this is to use Flask-Script , which provides a shell command that sets up the application for you. Or use Flask's integration with Click if you are using the development version.

To just get it working immediately, set up the context yourself:

ctx = app.app_context()
ctx.push()
# do stuff
ctx.pop()
# quit

You can also use a context in a with block:

with app.app_context():
    # do stuff

Use flask shell instead of default python interpreter

$ flask shell
$ from yourappname import db
$ db     # this will print your connection string
$ db.create_all()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM