简体   繁体   English

从交互式控制台运行代码时无法访问数据库

[英]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).我正在为 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_.基本上我想要的是从 _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如果我只是在这种情况下尝试打印db变量,结果是: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 .我的代码在浏览器上正常运行,但我无法从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.实现此目的的一种简单方法是使用Flask-Script ,它提供了一个 shell 命令来为您设置应用程序。 Or use Flask's integration with Click if you are using the development version.或者如果您使用的是开发版本,则使用Flask 与 Click 的集成

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块中使用上下文:

with app.app_context():
    # do stuff

Use flask shell instead of default python interpreter使用flask shell代替默认的python解释器

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 PyDev:将代码运行到交互式控制台 - PyDev: Running code to interactive console 运行测试时将鼻子或pytest插入交互式控制台 - Nose or pytest drop in to interactive console when running tests 键盘快捷键破坏了从脚本运行交互式Python控制台 - Keyboard shortcuts broken running interactive Python Console from a script 如果从IPython交互式控制台运行PySide应用,则上下文菜单消失 - Context menu disappears if PySide app is running from IPython interactive console 如何从 Python 代码清除交互式 IPython 控制台的屏幕 - How to clear the screen of Interactive IPython console from Python code 使用paramiko运行交互式shell时,代码会挂起 - code hangs when running interactive shell using paramiko 没有控制TTY不能运行交互式控制台 - Cannot run interactive console without a controlling TTY 如何访问数据存储信息(交互式控制台)? - How to access datastore information (Interactive Console)? 如何以交互方式将代码的输出输入到另一个代码中,并从Pycharm交互式python控制台运行它们? - How to interactively input the output of a code into another code and run them from Pycharm interactive python console? VS代码中具有自动完成功能的交互式python控制台 - Interactive python console with autocomplete in VS code
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM