在控制台脚本中执行查询

时间:2018-01-15 10:04:14

标签: python sqlalchemy pyramid

我正在努力弄清楚为什么我在金字塔引导之后得到的会话拒绝执行查询,引发bootstrap例外。

我尝试使用金字塔配置创建脚本,但正在处理后台任务。我使用from pyramid.plaster import bootstrap with bootstrap(sys.argv[1]) as env dbsession = env['request'].dbsession with dbsession.begin_nested(): res = dbsession.execute('''SELECT ....''') ... 函数来获取适当的环境。我尝试过的方法之一是:

SessionTransaction

按预期创建NoTransaction,但仍会提升import tensorflow as tf from tensorflow.contrib.tensorboard.plugins import projector sess = tf.InteractiveSession() with tf.device("/cpu:0"): tf_embedding = tf.Variable(embedding, trainable = False, name = "embedding") tf.global_variables_initializer().run() path = "tensorboard" saver = tf.train.Saver() writer = tf.summary.FileWriter(path, sess.graph) config = projector.ProjectorConfig() embed = config.embeddings.add() embed.tensor_name = "embedding" embed.metadata_path = "metadata.tsv" projector.visualize_embeddings(writer, config) saver.save(sess, path+'/model.ckpt' , global_step=max_size )

如何初始化连接,以便我可以像往常一样在视图中访问它?

2 个答案:

答案 0 :(得分:2)

https://github.com/Pylons/pyramid/issues/3219中所述,默认情况下不会初始化事务。它可以使用:

完成
with bootstrap(sys.argv[1]) as env:
    with env['request'].tm:
        dbsession = env['request'].dbsession
        dbsession.execute(...)

答案 1 :(得分:1)

我从未使用pyramid.plaster.bootstrap。但是,您可以使用与使用alchemy模板创建新项目时自动生成的脚本相同的模板。

pcreate -t alchemy myproject

脚本如下所示:

import os
import sys
import transaction

from pyramid.paster import (
    get_appsettings,
    setup_logging,
    )

from pyramid.scripts.common import parse_vars

from ..models.meta import Base
from ..models import (
    get_engine,
    get_session_factory,
    get_tm_session,
    )
from ..models import MyModel


def usage(argv):
    cmd = os.path.basename(argv[0])
    print('usage: %s <config_uri> [var=value]\n'
          '(example: "%s development.ini")' % (cmd, cmd))
    sys.exit(1)


def main(argv=sys.argv):
    if len(argv) < 2:
        usage(argv)
    config_uri = argv[1]
    options = parse_vars(argv[2:])
    setup_logging(config_uri)
    settings = get_appsettings(config_uri, options=options)

    engine = get_engine(settings)
    Base.metadata.create_all(engine)

    session_factory = get_session_factory(engine)

    with transaction.manager:
        dbsession = get_tm_session(session_factory, transaction.manager)

        model = MyModel(name='one', value=1)
        dbsession.add(model)

setup.py中的入口点如下所示:

entry_points="""\
  [paste.app_factory]
  main = myproject:main
  [console_scripts]
  initialize_myproject_db = myproject.scripts.initializedb:main
  """,