teloon
1/3/2011 - 2:25 AM

Create a virtualenv for a Tornado app

Create a virtualenv for a Tornado app

#!/usr/bin/env python
'''
Setup a virtualenv with tornado/master and a run script to serve static files.
'''
import virtualenv
import os
import subprocess
import stat

def after_install(options, home_dir):
    # use pip to install tornado from github
    pip = os.path.join(home_dir, 'bin', 'pip')
    subprocess.call([pip, 'install', '-e', 'git+https://github.com/facebook/tornado.git#egg=Tornado'])
    # create a www folder for static content
    www = os.path.join(home_dir, 'www')
    os.makedirs(www)
    # write a simple tornado script
    bin = os.path.join(home_dir, 'bin')
    script = os.path.join(bin, 'run_server.py')
    file(script, 'w').write("""\
#!/usr/bin/env python
# tornado
import tornado.httpserver
import tornado.ioloop
import tornado.web
import tornado.options
# std lib
import os.path
import logging

# cmd line options
tornado.options.define('port', type=int, default=8080, 
    help='server port number (default: 8080)')
tornado.options.define('debug', type=bool, default=False, 
    help='run in debug mode with autoreload (default: false)')

if __name__ == '__main__':
    tornado.options.parse_command_line()
    options = tornado.options.options
    kwargs = {
        'debug' : options.debug,
        'static_path' :  os.path.join(os.path.dirname(__file__), "../www")
    }
    app = tornado.web.Application([], **kwargs)
    http_server = tornado.httpserver.HTTPServer(app)
    http_server.listen(options.port)
    ioloop = tornado.ioloop.IOLoop.instance()
    logging.info('started on port: %d', options.port)
    ioloop.start()
""")
    os.chmod(script, stat.S_IRWXU|stat.S_IRGRP|stat.S_IROTH)
    # write an index.html
    index = os.path.join(www, 'index.html')
    file(index, 'w').write('''\
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <title>Hello from Tornado!</title>
  </head>
  <body>Hello from Tornado!</body>
</html>
''')
virtualenv.after_install = after_install

def adjust_options(options, args):
    # force no site packages
    options.no_site_packages = True
virtualenv.adjust_options = adjust_options

if __name__ == '__main__':
    virtualenv.main()