Thursday, 9 June 2011

Let Your Imagination Run Riot On Our Flask-Script Example

In my last article in this series, "Adding Shell Access to Our Flask-Script Example" I showed you how you could indeed get shell access from our script.

You see the whole point of Flask-Script is that it gives you scripted access not to the application, but to the environment in which the app runs. You don't actually need to be running the app, or importantly, to interfere with the app to do some task or other.

An Example
For example, lets say you want to load some data into the database model.

There are three ways you could do this:

  1. Write a script that understands your app's data model and get it to insert the data. You may be able to import the model module straight from your app, but you may not, due to dependencies etc.
  2. Run the code straight from your app, possibly using an admin screen somewhere. This means designing and implementing the screens - including the obvious security requirements.
  3. Use Flask-Script like this:

from application.model import Articles
import csv

def ingest_csv():
    '''read data from a csv file and ingest it into the database'''
    reader = csv.reader(open('articles.csv'))
    for row in reader:
        a = Article()

and then;

python ingest_csv

Simpler I think you'll agree?

Scheduling Task
There is one other huge advantage to using Flask-Script; you can run them from crontabs.

*/10 * * * * /some/path/bin/python /some/path/ ingest_csv >>/tmp/ingest.log 2>&1

Other Ideas
Here are some other examples of things you might want to dovia script:
  • Purge old data from your database.
  • Backup data from your database.
  • Export data from your database.
  • Do anything else you want from your database!
  • Flush your caches.
  • Mail out reports.
  • Other stuff I haven't thought of. Let me know!
Okay, enough of all this, go and enjoy!


    1. Thanks for your posts on Flask - very useful for me. Keep them coming please!

    2. No problem, always open to ideas for articles too. Don't forget to subscribe or even tweet/facebook me.

    3. Hello,
      First, big thx for this old article. I'm new in python and try using flask-scrip, but have a little problem.
      I have a flask application running with flask-script extension. A function (with 3 arguments) is placed in my cron and ended by :
      if name == "main":
      like mentionned in the flask-script doc [link]
      This function works fine when i call it directly in the console (also mentionned in the flask-script doc)
      python functionpython arg1 arg2 arg3
      but not in my cron (a necessary comment "# arg2 comment" is added)...
      */1 * * * * /var/www/application/ functionpython arg1 arg2 arg3 # arg2 comment

      I run this script on a raspberry pi and have no error from cron or from python...
      Any clue ?