0

The 'app' is created in views.py. The folder structure is:

~/tasks/
   /tasks
   /__init__.py
   /cron1.py
   /views.py  # app object is created here

There are some functions that I wish to import in the standalone cron1.py which I wish to run as cron job. The cron function call I make as follows:

if __name__ == '__main__':
    try:
        with app.app_context():
        # with current_app.test_request_context():
    get_recurring_tasklist()
    except Exception, e:
        print e

On execution from root folder with command $ PYTHONPATH=. python tasks/create_recurring_tasks.py Error I get is: working outside of request context I am using a method call from views which uses request object. How to go about?

dirn
  • 19,454
  • 5
  • 69
  • 74
user956424
  • 1,611
  • 2
  • 37
  • 67
  • Unless you need to support Python 2.5 -- which hasn't been supported for a few years -- you [shouldn't use the `except Exception, e` syntax](http://stackoverflow.com/a/2535770/978961). – dirn Jan 20 '16 at 14:40
  • @dirn Using python v. 2.7 – user956424 Jan 21 '16 at 03:45

1 Answers1

1

If you have a standalone cron job the better practice is to avoid using any sort of logic in the job that involves the Flask request context/object. The test_request_context context is just for testing and shouldn't be used in task setup.

I don't know what your view function looks like, but you should abstract away the "task creation" part of the function into its own method that lives independently. That the cron job and view function can both share it.

@app.route('/task_list')
def get_task_list():
    data = request.args.get('tasks')

    # some sort of logic happening here
    ret = []
    for word in data:
        ret.append('some task')

    return jsonify(data=ret)

After

def convert_data_to_tasks(data):
    ret = []
    for word in tasks:
        ret.append('some task')

    return ret


@app.route('/task_list')
def get_task_list():
    tasks = request.args.get('tasks')
    ret = convert_data_to_tasks(tasks)

    return jsonify(ret)
jumbopap
  • 3,969
  • 5
  • 27
  • 47
  • thx for the hint, I got rid of a session value in the view which was causing the problem. and resolved it. :) – user956424 Jan 21 '16 at 04:50