Skip to content

Instantly share code, notes, and snippets.

@cessor
Last active June 4, 2018 19:52
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cessor/f0b69681311d7d269f7937e55274fa85 to your computer and use it in GitHub Desktop.
Save cessor/f0b69681311d7d269f7937e55274fa85 to your computer and use it in GitHub Desktop.
Simple Tornado App Skeleton
import logging
import os
import uuid
from tornado import gen
from tornado.httpserver import HTTPServer
from tornado.ioloop import IOLoop
from tornado.options import define, options
from tornado.web import Application, StaticFileHandler, url
from web import Home, Login, Logout
define('debug', default=True)
define('loglevel', default='debug')
define('port', default=8888)
def directory(path):
return os.path.join(os.path.dirname(__file__), path)
clients = [
uuid.uuid4(),
uuid.uuid4()
]
routes = [
url(r"/?", Home, dict(clients=clients)),
url(r"/login", Login),
url(r"/logout", Logout),
url(r'/(favicon\.ico)', StaticFileHandler, dict(path=directory('static')))
]
def configure():
# Read config file
try:
config_file = 'config.cfg'
options.parse_config_file(config_file, final=False)
except:
pass
options.parse_command_line()
settings = dict(
autoreaload=True,
compress_response=True,
cookie_secret=os.urandom(64),
debug=options.debug,
logging=options.loglevel,
login_url='/login',
static_path=directory('static'),
template_path=directory('templates'),
xheaders=True,
xsrf_cookies=True,
)
return Application(routes, **settings)
def main():
# Run app
app = configure()
server = HTTPServer(app, xheaders=True)
server.bind(options.port)
server.start(1)
logging.info('Running on port %s' % options.port)
IOLoop.current().start()
if __name__ == '__main__':
main()
from tornado import gen
from tornado.web import RequestHandler, authenticated
USER_ID = 'USER_ID'
def fastauth(fn):
return authenticated(gen.coroutine(fn))
class Authenticated(RequestHandler):
def get_current_user(self):
return self.get_secure_cookie(USER_ID)
class Home(Authenticated):
def initialize(self, clients):
self.clients = clients
@fastauth
def get(self):
self.render("index.html")
class Login(RequestHandler):
'''Make sure that the login handler is accessible'''
@gen.coroutine
def get(self):
self.render("login.html")
@gen.coroutine
def post(self):
with open('.secret') as file_:
secret = file_.read().strip()
if self.get_argument('password') == secret:
self.set_secure_cookie(USER_ID, USER_ID);
self.redirect("/")
class Logout(RequestHandler):
@gen.coroutine
def get(self):
self.clear_cookie(USER_ID)
self.redirect("/")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment