Last active
December 30, 2015 18:29
-
-
Save simonrad/7868198 to your computer and use it in GitHub Desktop.
A webserver to scramble a Rubik's cube.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #! /usr/bin/env python | |
| """ | |
| A webserver to scramble a Rubik's cube. | |
| It renders a sequence of moves which you should perform to scramble your cube. | |
| The generated scrambles are perfectly, uniformly random. | |
| """ | |
| import sys | |
| import logging | |
| import tornado.ioloop | |
| import tornado.web | |
| from tornado.httpclient import HTTPClient | |
| class LoggerWriter: | |
| """ Wraps a logger with a file-like API. """ | |
| def __init__(self, logger, level): | |
| self.logger = logger | |
| self.level = level | |
| def write(self, message): | |
| if message != '\n': | |
| self.logger.log(self.level, message) | |
| logfile_path = 'cubing_logfile.log' | |
| img_url = 'http://www.geocities.jp/fjtkt/misc/2006_0007/rotateimage/%s.png' | |
| scramble_url = 'http://voltara.org/cube/scramble.php' | |
| def render_moves(move_seq_str): | |
| to_ret = '' | |
| to_ret += '/moves/%s<br/><br/>\n' % move_seq_str | |
| move_seq = [move.upper().replace("'", 'd') for move in move_seq_str.split()] | |
| for move in move_seq: | |
| to_ret += '<img src="%s" style="margin:5px">' % (img_url % move) | |
| return to_ret | |
| class MovesHandler(tornado.web.RequestHandler): | |
| def get(self, move_seq_str): | |
| # logging.info('/moves/ with %r' % move_seq_str) | |
| self.write(render_moves(move_seq_str)) | |
| class ScrambleHandler(tornado.web.RequestHandler): | |
| def get(self): | |
| move_seq_str = HTTPClient().fetch(scramble_url).body.strip() | |
| # logging.info('/ with %r' % move_seq_str) | |
| self.write(render_moves(move_seq_str)) | |
| application = tornado.web.Application([ | |
| (r'/', ScrambleHandler), | |
| (r'/moves/(.*)', MovesHandler), | |
| ]) | |
| if __name__ == '__main__': | |
| logging.basicConfig(level = logging.DEBUG, | |
| filename = logfile_path, | |
| filemode = 'a+', | |
| format = '%(asctime)-15s %(levelname)-8s %(message)s') | |
| sys.orig_stdout = sys.stdout | |
| sys.orig_stderr = sys.stderr | |
| sys.stdout = LoggerWriter(logging.getLogger(), logging.INFO) | |
| sys.stderr = LoggerWriter(logging.getLogger(), logging.ERROR) | |
| print 'Starting Tornado server.' | |
| # logging.info('Starting Tornado server.') | |
| # application.listen(8888) | |
| application.listen(14853) # The port assigned by WebFaction | |
| tornado.ioloop.IOLoop.instance().start() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment