<s> """<STR_LIT>""" <EOL> import logging <EOL> import tornado . escape <EOL> import tornado . ioloop <EOL> import tornado . options <EOL> import tornado . web <EOL> import tornado . websocket <EOL> import os . path <EOL> import uuid <EOL> from tornado . options import define , options <EOL> define ( "<STR_LIT:port>" , default = <NUM_LIT> , help = "<STR_LIT>" , type = int ) <EOL> class Application ( tornado . web . Application ) : <EOL> def __init__ ( self ) : <EOL> handlers = [ <EOL> ( r"<STR_LIT:/>" , MainHandler ) , <EOL> ( r"<STR_LIT>" , ChatSocketHandler ) , <EOL> ] <EOL> settings = dict ( <EOL> cookie_secret = "<STR_LIT>" , <EOL> template_path = os . path . join ( os . path . dirname ( __file__ ) , "<STR_LIT>" ) , <EOL> static_path = os . path . join ( os . path . dirname ( __file__ ) , "<STR_LIT>" ) , <EOL> xsrf_cookies = True , <EOL> ) <EOL> super ( Application , self ) . __init__ ( handlers , ** settings ) <EOL> class MainHandler ( tornado . web . RequestHandler ) : <EOL> def get ( self ) : <EOL> self . render ( "<STR_LIT>" , messages = ChatSocketHandler . cache ) <EOL> class ChatSocketHandler ( tornado . websocket . WebSocketHandler ) : <EOL> waiters = set ( ) <EOL> cache = [ ] <EOL> cache_size = <NUM_LIT:200> <EOL> def get_compression_options ( self ) : <EOL> return { } <EOL> def open ( self ) : <EOL> ChatSocketHandler . waiters . add ( self ) <EOL> def on_close ( self ) : <EOL> ChatSocketHandler . waiters . remove ( self ) <EOL> @ classmethod <EOL> def update_cache ( cls , chat ) : <EOL> cls . cache . append ( chat ) <EOL> if len ( cls . cache ) > cls . cache_size : <EOL> cls . cache = cls . cache [ - cls . cache_size : ] <EOL> @ classmethod <EOL> def send_updates ( cls , chat ) : <EOL> logging . info ( "<STR_LIT>" , len ( cls . waiters ) ) <EOL> for waiter in cls . waiters : <EOL> try : <EOL> waiter . write_message ( chat ) <EOL> except : <EOL> logging . error ( "<STR_LIT>" , exc_info = True ) <EOL> def on_message ( self , message ) : <EOL> logging . info ( "<STR_LIT>" , message ) <EOL> parsed = tornado . escape . json_decode ( message ) <EOL> chat = { <EOL> "<STR_LIT:id>" : str ( uuid . uuid4 ( ) ) , <EOL> "<STR_LIT:body>" : parsed [ "<STR_LIT:body>" ] , <EOL> } <EOL> chat [ "<STR_LIT:html>" ] = tornado . escape . to_basestring ( <EOL> self . render_string ( "<STR_LIT>" , message = chat ) ) <EOL> ChatSocketHandler . update_cache ( chat ) <EOL> ChatSocketHandler . send_updates ( chat ) <EOL> def main ( ) : <EOL> tornado . options . parse_command_line ( ) <EOL> app = Application ( ) <EOL> app . listen ( options . port ) <EOL> tornado . ioloop . IOLoop . current ( ) . start ( ) <EOL> if __name__ == "<STR_LIT:__main__>" : <EOL> main ( ) </s>
