【问题标题】:Flask - Apscheduler cannot call function that executes database commandFlask - Apscheduler 无法调用执行数据库命令的函数
【发布时间】:2012-09-01 12:26:56
【问题描述】:
Python: 2.7.3

Flask: 0.9

您好,我想使用Apscheduler 制作汽车模拟器。每辆车在数据库中都有distance 列,会定期递增。

这是导入部分

from __future__ import with_statement
from flask import Flask, request, session, g, redirect, url_for, \
    abort, render_template, flash, views
from sqlite3 import dbapi2 as sqlite3
from contextlib import closing
from apscheduler.scheduler import Scheduler

这是代码的sn-p:

sched = Scheduler()
sched.add_interval_job(moveAllCars, seconds = 5)
sched.start()

def moveAllCars():
    print "debug 1"
    dbCommand = g.db.execute('SELECT CarID FROM Car')
    print "debug 2"
    #and so on

我没有编写完整的代码,因为错误发生在“调试 1”之后,并显示错误消息:找不到记录器“apscheduler.scheduler”的处理程序。 Google 帮不上什么忙。

但调度程序仍在运行,每 5 秒仅打印一次“debug1”。错误信息仅在第一个循环期间出现。

有人知道解决办法吗?谢谢之前

[更新]

使用logging 后,我发现它是 RunTimeError: working outside of request context。除了使用app.test_request_context之外还有其他解决方案吗?

【问题讨论】:

标签: python flask scheduler


【解决方案1】:
from os import getcwd
import logging
logging.basicConfig(
        filename=''.join([getcwd(), '/', 'log_file_name']),
        level=logging.DEBUG,
        format='%(levelname)s[%(asctime)s]: %(message)s'
)

以上对我的情况确实有帮助。

KAcper

【讨论】:

  • +1 感谢您的回复,不过我已经找到了答案。有机会我会试试你的解决方案
【解决方案2】:

g 可能是threading.local()。不同的线程在其中看到不同的值。

g.db 可能会为每个请求分配一个新的数据库连接。当前没有请求 - 没有连接。

您可以在 move_all_cars() 中创建数据库连接或将其作为参数显式传递。

【讨论】:

  • 我尝试将moveCar() 复制到声明g.db 的类中,但它仍然返回相同的“找不到记录器的处理程序”错误我认为我应该处理记录器,但我不能在 Google 中找到好的简单的解决方案
  • 修复“无处理程序”配置日志记录。之后它将显示您遇到的实际错误。
  • 谢谢,问题如你所说,它适用于不同的线程。所以我把连接到数据库的代码放在 moveCar() 中
猜你喜欢
  • 1970-01-01
  • 2018-09-23
  • 2021-01-17
  • 2015-05-14
  • 1970-01-01
  • 2021-02-17
  • 1970-01-01
  • 2013-01-30
  • 2015-03-06
相关资源
最近更新 更多