Flask - Apscheduler cannot call a function that executes a database command

Python: 2.7.3 Flask: 0.9 

Hi, I want to make a car simulator using Apscheduler . Each car has a distance column in the database, which will increase regularly.

Here is the import part

 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 

and here is the code snippet:

 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 

I did not write the full code because the error occurred immediately after "debug 1" with the error message: no handlers for "apscheduler.scheduler" were found. Google doesn't really help.

But the scheduler still works, it only prints "debug1" every 5 seconds. The error message appears only during the first cycle.

Does anyone know a solution? Thanks before

[UPDATE]

After using logging I found this to be a RunTimeError: working out of the context of the request. Is there any other solution besides using with app.test_request_context ?

+4
source share
2 answers

g is probably threading.local() . Different threads see different meanings in it.

g.db is probably assigned a new db connection for each request. No current request - no connection.

You can create a db connection in move_all_cars () or pass it explicitly as a parameter.

+3
source
 from os import getcwd import logging logging.basicConfig( filename=''.join([getcwd(), '/', 'log_file_name']), level=logging.DEBUG, format='%(levelname)s[%(asctime)s]: %(message)s' ) 

The above was help in my case.

Kacper

+3
source

Source: https://habr.com/ru/post/1432978/


All Articles