def app(): # Define your database metadata # ----------------------------- db = Gino() # Define tables as you would normally do # -------------------------------------- class User(db.Model): __tablename__ = 'users' id = db.Column(db.Integer(), primary_key=True, autoincrement=True) nickname = db.Column(db.Unicode(), nullable=False) # Now just use your tables # ------------------------ class AllUsers(GinoRequestHandler): async def get(self): users = await User.query.gino.all() for user in users: self.write('<a href="{url}">{nickname}</a><br/>'.format( url=self.application.reverse_url('user', user.id), nickname=tornado.escape.xhtml_escape(user.nickname))) class GetUser(GinoRequestHandler): async def get(self, uid): user = await User.get_or_404(int(uid)) self.write('Hi, {}!'.format(user.nickname)) class AddUser(GinoRequestHandler): async def post(self): user = await User.create(nickname=self.get_argument('name')) self.write('Hi, {}!'.format(user.nickname)) options = { 'db_host': DB_ARGS['host'], 'db_port': DB_ARGS['port'], 'db_user': DB_ARGS['user'], 'db_password': DB_ARGS['password'], 'db_database': DB_ARGS['database'], } for option, value in options.items(): setattr(tornado.options.options, option, value) app = Application([ tornado.web.URLSpec(r'/', AllUsers, name='index'), tornado.web.URLSpec(r'/user/(?P<uid>[0-9]+)', GetUser, name='user'), tornado.web.URLSpec(r'/user', AddUser, name='user_add'), ], debug=True) loop = tornado.ioloop.IOLoop.current().asyncio_loop loop.run_until_complete(app.late_init(db)) loop.run_until_complete(db.gino.create_all()) try: yield app finally: loop.run_until_complete(db.gino.drop_all())
def let_the_streaming_begin(io_loop, bootstrap_ip_ports): #Setup the DHT global dht dht = DHT(51414, bootstrap_ip_ports, io_loop = io_loop) #Setup KTorrent and Its URL Handlers settings = dict( (k, v.value()) for k,v in options.items() ) application = BTApplication(routes, **settings) Connection.ioloop = io_loop Connection.application = application settings['log_function'] = request_logger frontend_application = tornado.web.Application(frontend_routes, **settings) frontend_server = tornado.httpserver.HTTPServer(frontend_application, io_loop=io_loop) Connection.frontend_server = frontend_server try: frontend_server.bind(options.frontend_port, '') frontend_server.start() #logging.info('started frontend server') except: logging.error('could not start frontend server') btserver = BTProtocolServer(application, io_loop=io_loop) btserver.bind(options.port, '') btserver.start() logging.info('started btserver') logging.info('\n\n') Client.resume() client = Client.instances[0] Client.http_client = httpclient.AsyncHTTPClient() Torrent.client = client tornado.ioloop.PeriodicCallback( Connection.make_piece_request, 1000 * 1, io_loop=io_loop ).start() tornado.ioloop.PeriodicCallback( Connection.get_metainfo, 1000 * 1, io_loop=io_loop ).start() # better to make event driven tornado.ioloop.PeriodicCallback( Client.tick, 1000 * 1, io_loop=io_loop ).start() tornado.ioloop.PeriodicCallback( client.do_trackers, 1000 * 1, io_loop=io_loop ).start() tornado.ioloop.PeriodicCallback( client.peer_think, 3000 * 1, io_loop=io_loop ).start() tornado.ioloop.PeriodicCallback( Connection.cleanup_old_requests, 1000 * 1, io_loop=io_loop ).start() def got_interrupt_signal(signum=None, frame=None): logging.info('got quit signal ... saving quick resume') Client.save_settings() #Torrent.save_quick_resume() sys.exit() signal.signal(signal.SIGINT, got_interrupt_signal) settings = dict( (k, v.value()) for k,v in options.items() ) dht_frontend_routes = [ ('/?', dhttornado.IndexHandler), ] dht_frontend_application = tornado.web.Application(dht_frontend_routes, **settings) dht_frontend_server = tornado.httpserver.HTTPServer(dht_frontend_application, io_loop=io_loop) dht_frontend_server.bind(options.dht_frontend_port, '') dht_frontend_server.start() dhttornado.IndexHandler.register_dht(dht) dht.bootstrap() dht.start() #This also does io_loop.start()
for node in root.childNodes: if node.nodeType != node.ELEMENT_NODE: continue categories += node.getAttribute('name') categories += '|' categories = categories[:-1] content = '{"msrc":"ws-update-category","content":"%s"}' % categories self.notify(content) except Exception, e: logging.error(e) #手动切换项目combobox时发送;提供当前project的buildoptions elif msg['msrc'] == 'ws-build-options': projName = msg['content'] try: options = project.build_options[projName] for key, val in options.items(): if val[0] == 'check': if len(val) == 4: content = '{"msrc":"ws-build-options","content":"%s|%s|%s|%s;%s"}' % ( key, val[0], val[1], val[2], val[3]) elif len(val) == 5: content = '{"msrc":"ws-build-options","content":"%s|%s|%s|%s;%s;%s"}' % ( key, val[0], val[1], val[2], val[3], val[4]) elif val[0] == 'radio': ctx = '' for item in val[2]: ctx += '%s,%s,%s' % (item[0], item[1], item[2]) if len(item) == 4: ctx += ',%s;' % item[3] else: ctx += ';'
d["Peers_for_%s" % id.encode("hex")] = self.dht.infohash_peers[id].keys() self.set_header('Content-Type', 'text/plain') self.write(json.dumps(d, indent=2, cls=ComplexEncoder)) if __name__ == "__main__": ioloop = tornado.ioloop.IOLoop() ioloop.install() define('debug', default=True, type=bool) # save file causes autoreload define('frontend_port', default=7070, type=int) tornado.options.parse_command_line() settings = dict((k, v.value()) for k, v in options.items()) ip_ports = [('202.177.254.130', 43251), ('71.7.233.108', 40641), ('189.223.55.147', 54037), ('186.213.54.11', 57479), ('85.245.177.29', 58042), ('2.81.68.199', 37263), ('188.24.193.27', 15796), ('210.252.33.4', 39118), ('175.143.215.38', 56067), ('95.42.100.15', 34278), ('211.224.26.47', 25628), ('92.6.154.240', 48783), ('173.255.163.104', 52159), ('2.10.206.61', 12815), ('187.123.98.253', 58901), ('83.134.13.212', 10770), ('78.139.207.123', 50045), ('125.25.191.209', 56548), ('71.234.82.146', 14973), ('72.207.74.219', 14884), ('79.136.190.188', 50634), ('72.80.103.198', 36823), ('77.122.72.44', 56554)] dht = dht.DHT(51414, ip_ports)
import tornado.netutil import tornado.httpserver import tornado.web import functools import logging import os from tornado.options import define, options define('debug',default=True, type=bool) define('asserts',default=True, type=bool) define('verbose',default=1, type=int) define('port',default=6969, type=int) tornado.options.parse_command_line() settings = dict( (k, v.value()) for k,v in options.items() ) from tornado.autoreload import add_reload_hook ioloop = tornado.ioloop.IOLoop() ioloop.install() from handlers import Handler, AnnounceHandler, DebugHandler routes = [ ('/announce/?', AnnounceHandler), ('/proxy/?', Handler), ('/status/?',DebugHandler) ] application = tornado.web.Application(routes, **settings)
for node in root.childNodes: if node.nodeType != node.ELEMENT_NODE: continue categories += node.getAttribute("name") categories += "|" categories = categories[:-1] content = '{"msrc":"ws-update-category","content":"%s"}' % categories self.notify(content) except Exception, e: logging.error(e) # 手动切换项目combobox时发送;提供当前project的buildoptions elif msg["msrc"] == "ws-build-options": projName = msg["content"] try: options = project.build_options[projName] for key, val in options.items(): if val[0] == "check": if len(val) == 4: content = '{"msrc":"ws-build-options","content":"%s|%s|%s|%s;%s"}' % ( key, val[0], val[1], val[2], val[3], ) elif len(val) == 5: content = '{"msrc":"ws-build-options","content":"%s|%s|%s|%s;%s;%s"}' % ( key, val[0], val[1], val[2],
def command_options(options): ''' Prints the current system options ''' print_banner('Current Service Settings') for name, option in options.items(): print "%20s :: %s" % (name, option.value()) sys.exit(0)
'upload_path': '/var/www/feiwenchao/upload/post' } tornado.web.Application.__init__(self, handlers=handlers, **settings) self.session_manager = session.SessionManager( settings['session_secret'], settings['store_options'], settings['session_timeout']) def log(): logging.basicConfig( filename='/var/log/blog.log', filemode='a', format='%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s', datefmt='%a, %d %b %Y %H:%M:%S', level=logging.INFO ) if __name__ == '__main__': log() try: tornado.options.parse_command_line() for i in options.items(): print i http_server = tornado.httpserver.HTTPServer(Application(), xheaders=True) http_server.listen(options.port) tornado.ioloop.IOLoop.instance().start() except Exception as e: logging.error(e)