Tuesday, 7 June 2011

Adding Shell Access to Our Flask-Script Example

The starting example of how you can use flask-script was given in my earlier article;
A Simple Flask-Script Example.

Next thing we are going to add is the ability to run a shell which that shares your applications environment. You need to decide what you ant to import and put it in the shell_context function. Call it whatever you want, but it has to return a dict with your context items inside. To keep it simple I just import the app itself. The lines you need to change are:

from flaskext.script import Manager, Server, Shell

and

def shell_context():
    return dict(app=app)            
            
if __name__ == "__main__":
    manager.add_command('dev', DevServer())
    manager.add_command('test', Test())
    manager.add_command('zen', ZenTest())
    manager.add_command('shell', Shell(make_context=shell_context))
    manager.run()

now test it:

python manager.py shell

>>> app.debug
True
>>> app.logger
<flask.logging.DebugLogger instance at 0x2ee3518>

and so on.

There's one final installment to follow - Let Your Imagination Run Riot On Our Flask-Script Example


The full listing for what we did here is below:

from flaskext.script import Manager, Server, Shell
from flaskext.zen import Test, ZenTest
import application


app = application.create_app()

manager = Manager(app)

class DevServer(Server):
    
    def handle(self, app, host, port, use_debugger, use_reloader):
        try:
            from flaskext.lesscss import lesscss
            lesscss(app)
        except: pass

        app.run(host=host,
            port=port,
            debug=use_debugger,
            use_debugger=use_debugger,
            use_reloader=use_reloader,
            **self.server_options)
    
def shell_context():
    return dict(app=app)            
            
if __name__ == "__main__":
    manager.add_command('dev', DevServer())
    manager.add_command('test', Test())
    manager.add_command('zen', ZenTest())
    manager.add_command('shell', Shell(make_context=shell_context))
    manager.run()

No comments:

Post a Comment