Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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://[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)
    ...

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.

like image 835
stefanobaldo Avatar asked Jan 14 '15 17:01

stefanobaldo


People also ask

How do I access the Python console?

Working with Python console The console appears as a tool window every time you choose the corresponding command on the Tools menu. You can assign a shortcut to open Python console: press Ctrl+Alt+S , navigate to Keymap, specify a shortcut for Main menu | Tools | Python or Debug Console.

What is interactive console?

Interactive Console Console is a tool which allows developers to conveniently run DSL code directly in the MPS environment against the active models. It enables you to quickly query the model and change it.

What are the benefits of the Python interactive shell?

The following are the advantages of running your code in interactive mode: Helpful when your script is extremely short and you want immediate results. Faster as you only have to type a command and then press the enter key to get the results. Good for beginners who need to understand Python basics.


2 Answers

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
like image 176
davidism Avatar answered Nov 04 '22 23:11

davidism


Use flask shell instead of default python interpreter

$ flask shell
$ from yourappname import db
$ db     # this will print your connection string
$ db.create_all()
like image 28
mukti wibowo Avatar answered Nov 04 '22 22:11

mukti wibowo