Example #1
0
def main():
    routes = get_routes(api)
    print("Routes\n======\n\n" + json.dumps([(url, repr(rh))
                                             for url, rh in routes]))
    app = Application(routes=routes, settings={}, generate_docs=True)
    app.listen(6060)
    tornado.ioloop.IOLoop.instance().start()
Example #2
0
def main():
    routes = get_routes(api)
    print(routes)

    application = Application(routes=routes, settings={})

    port = config["global"]["listen_port"]
    application.listen(port)
    tornado.ioloop.IOLoop.instance().start()
Example #3
0
def main():
    import cars

    routes = get_routes(cars)
    print("Routes\n======\n\n" + json.dumps([(url, repr(rh)) for url, rh in routes], indent=2))
    application = Application(routes=routes, settings={})

    application.listen(8888)
    tornado.ioloop.IOLoop.instance().start()
Example #4
0
def main():
    import hello
    routes = get_routes(hello)
    print("Routes\n======\n\n" +
          json.dumps([(url, repr(rh)) for url, rh in routes], indent=2))
    application = Application(routes=routes, settings={})

    application.listen(8888)
    tornado.ioloop.IOLoop.instance().start()
Example #5
0
def main():
    import helloworld

    routes = get_routes(helloworld)
    #    routes.extend(get_routes(git))

    print ("Routes\n======\n\n" + json.dumps([(url, repr(rh)) for url, rh in routes], indent=2))
    application = Application(routes=routes, settings={"token": token})

    application.listen(port)
    tornado.ioloop.IOLoop.instance().start()
Example #6
0
def main():
    import api
    routes = get_routes(api)
    print("Routes\n======\n\n" +
          json.dumps([(url, repr(rh)) for url, rh in routes], indent=2))
    # Create the application by passing routes and any settings
    application = Application(routes=routes, settings={}, generate_docs=True)

    # Start the application on port 8888
    application.listen(8080)
    tornado.ioloop.IOLoop.instance().start()
Example #7
0
def main():
    import helloworld

    routes = get_routes(helloworld)
    #    routes.extend(get_routes(git))

    print("Routes\n======\n\n" +
          json.dumps([(url, repr(rh)) for url, rh in routes], indent=2))
    application = Application(routes=routes, settings={'token': token})

    application.listen(port)
    tornado.ioloop.IOLoop.instance().start()
Example #8
0
def main():
    # Pass the web app's package the get_routes and it will generate
    #   routes based on the submodule names and ending with lowercase
    #   request handler name (with 'handler' removed from the end of the
    #   name if it is the name).
    # [("/api/helloworld", helloworld.api.HelloWorldHandler)]
    routes = get_routes(helloworld)

    # Create the application by passing routes and any settings
    application = Application(routes=routes, settings={})

    # Start the application on port 8888
    application.listen(8888)
    tornado.ioloop.IOLoop.instance().start()
Example #9
0
def make_app():
    import helloworld
    routes = get_routes(helloworld)
    print("Routes\n=======\n\n" +
          json.dumps([(url, repr(rh)) for url, rh in routes], indent=2))
    settings = {"debug": True, "default_handler_class": NotFoundHandler}
    return Application(routes=routes, settings=settings, generate_docs=True)
Example #10
0
 def get_app(self):
     ctconfig.define_options()
     self.db = db2.Connection("cutthroat_test.db").db
     settings = dict(cookie_secret="I am a secret cookie.", )
     return Application(routes=mod_routes.assemble_routes(),
                        settings=settings,
                        db_conn=self.db)
Example #11
0
def make_app():
    import blackbean
    routes = get_routes(blackbean)
    print("Routes\n=======\n\n" +
          json.dumps([(url, repr(rh)) for url, rh in routes], indent=2))
    settings = {"debug": True}
    return Application(routes=routes, settings=settings, generate_docs=True)
Example #12
0
def main():
    # Pass the web app's package the get_routes and it will generate
    #   routes based on the submodule names and ending with lowercase
    #   request handler name (with 'handler' removed from the end of the
    #   name if it is the name).
    # [("/api/helloworld", helloworld.api.HelloWorldHandler)]
    import notes
    routes = get_routes(notes)
    print("Routes\n======\n\n" +
          json.dumps([(url, repr(rh)) for url, rh in routes], indent=2))
    # Create the application by passing routes and any settings
    application = Application(routes=routes, settings={}, generate_docs=True)

    # Start the application on port 8888
    application.listen(8888)
    tornado.ioloop.IOLoop.instance().start()
Example #13
0
def main():
    print("We start working at "+str(datetime.now()))
    application = Application([tornado.web.url(r"/api/bloodbitapi/?", EngineReciever)], settings={})
    http_server = tornado.httpserver.HTTPServer(application, idle_connection_timeout=300)
    http_server.bind(8888)
    http_server.start()
    tornado.ioloop.IOLoop.instance().start()
Example #14
0
File: main.py Project: 106-/waker
def main():
    os.chdir(os.path.dirname(os.path.abspath(__file__)))

    wkr = waker()

    import api
    routes = get_routes(api)
    routes.append(("/ws", wsstream.wsstream))
    print("Routes\n======\n\n" +
          json.dumps([(url, repr(rh)) for url, rh in routes], indent=2))
    app = Application(routes=routes, settings={})
    app.listen(8080)

    try:
        IOLoop.instance().start()
    except (KeyboardInterrupt, SystemExit):
        logging.info("Interrupted.")
def main():
    # Pass the web app's package the get_routes and it will generate
    #   routes based on the submodule names and ending with lowercase
    #   request handler name (with 'handler' removed from the end of the
    #   name if it is the name).
    # [("/api/helloworld", helloworld.api.HelloWorldHandler)]
    import ApiFiles
    routes = get_routes(ApiFiles)
    print("Routes\n======\n\n" + json.dumps(
        [(url, repr(rh)) for url, rh in routes],
        indent=2)
    )
    # Create the application by passing routes and any settings
    application = Application(routes=routes, settings={}, generate_docs=True)

    # Start the application on port 8888
    application.listen(8888)
    tornado.ioloop.IOLoop.instance().start()
Example #16
0
 def get_app(self):
     routes = get_routes(dataservice)
     print routes
     settings = dict(
         hbase_host='192.168.33.10',
         hbase_thrift_port=9095,
         hdfs_host='192.168.33.10'
     )
     return Application(routes=routes, settings=settings, db_conn=TestDB())
Example #17
0
def make_app(sg_settings):
    #    routes = get_routes(sendsms)
    return Application(routes=[
        (r"/", MainHandler),
        (r"/v1/sendsms", sendsms.SendSMSHandler),
        (r"/v1/smsstatus/([0-9]+)", sendsms.GetStatusHandler),
    ],
                       settings={
                           "requestID": requestID,
                           "db_queue": db_queue,
                           "modem_queue": modem_queue,
                           "ipipe": ipipe,
                           "settings": sg_settings
                       })
Example #18
0
def main():
    tornado.options.parse_command_line()
    routes = get_routes(picture)
    print("Routes\n======\n\n" + json.dumps(
        [(url, repr(rh)) for url, rh in routes],
        indent=2)
          )

    application = Application(routes=routes, settings={"debug": True, })

    application.objects = peewee_async.Manager(database)

    application.listen(8080)

    tcelery.setup_nonblocking_producer(on_ready=call_task)

    io_loop = tornado.ioloop.IOLoop.instance()

    # connect("nero_gate", host="192.168.1.5", port=27017, connect=False, io_loop=io_loop)  4
    # connect("nero_gate", host="192.168.1.5", port=27017, connect=False, io_loop=io_loop)  3
    connect("nero_gate", host="192.168.1.5", port=27017)

    io_loop.start()
Example #19
0
def main():
    """
    Main entry point for my service.
    :return:
    """
    # pylint: disable=global-statement
    global APISERVER
    config.define_options()
    # Attempt to load config from config file
    try:
        parse_config_file("server.conf")
    except IOError:
        errmsg = (
            "{} doesn't exist or couldn't be opened. Using defaults.".format(
                options.conf_file_path))
        logging.warn(errmsg)
    logging.info(options.as_dict())
    platform = Platform.factory(CLOUDERA)
    endpoints = platform.discover(options)
    if not endpoints:
        logging.error("Failed to discover API endpoints of cluster")

    db_store = HDBDataStore(endpoints['HDFS'].geturl(),
                            endpoints['HBASE'].geturl(), options.thrift_port,
                            options.datasets_table, options.data_repo)
    routes = get_routes(dataservice)
    logging.info("Service Routes %s", routes)
    settings = dict()
    APISERVER = tornado.httpserver.HTTPServer(
        Application(routes=routes, settings=settings, db_conn=db_store))
    for port in options.ports:
        try:
            logging.debug(
                "Attempting to bind for dataset dataset on port:%d and address %s",
                port, options.bind_address)
            APISERVER.listen(port, options.bind_address)
            logging.info("Awesomeness is listening on:%s", port)
            break
        except socket.error:
            logging.warn("Not able to bind on port:%d", port)
    else:
        logging.warn("No free port available to bind dataset")

    signal.signal(signal.SIGTERM, sig_handler)
    signal.signal(signal.SIGINT, sig_handler)
    # keep collecting dataset
    tornado.ioloop.PeriodicCallback(db_store.collect,
                                    options.sync_period).start()
    # db_conn2.collect()
    tornado.ioloop.IOLoop.instance().start()
Example #20
0
def main():
    env_file = base_path(".env")
    if not os.path.isfile(env_file):
        env_example = base_path(".env.example")
        copy2(env_example, env_file)
    env = read_env()
    port = env.getint('APP', 'APP_PORT')
    address = env.get('APP', 'APP_ADDRESS')
    debug = env.getboolean('APP', 'APP_DEBUG')

    # 定义默认端口
    define("port", default=port, help="run on the given port", type=int)

    # 根据配置动态加载API模块
    api_modules = env.items("MODULE")
    routes = []
    for module, on in api_modules:
        if on == '1':
            routes += get_module_api_routes(module)
    print(routes)
    template_path = base_path("templates")
    static_path = base_path("static")
    # 服务参数设置
    app = Application(
        routes=routes,
        settings={
            'debug': debug,  # 调试模式,产品环境设为False
            'template_path': template_path,  # 模版文件存放路径
            'static_path': static_path,  # 静态文件存放路径
            'default_handler_class': PageHandler  # 默认页面控制器
        })
    # 解析命令行参数
    tornado.options.parse_command_line()
    http_server = tornado.httpserver.HTTPServer(app)
    # 设置服务监听端口
    http_server.listen(options.port, address=address)
    tornado.ioloop.IOLoop.instance().start()
Example #21
0
@author: Dani
"""

import tornado.ioloop
from tornado_json.routes import get_routes
from tornado_json.application import Application

from google.protobuf import timestamp_pb2
from gcloud import storage

import OFWorker

PICKLE_BUCKET = 'pickles-python'

if __name__ == '__main__':

    client = storage.Client()
    for filename in ['age_classifier.pkl', 'gender_classifier.pkl']:
        cblob = client.get_bucket(PICKLE_BUCKET).get_blob(filename)
        fp = open(filename, 'wb')
        cblob.download_to_file(fp)
        fp.close()

    routes = get_routes(OFWorker)

    application = Application(routes=routes, settings={})

    application.listen(8889)

    tornado.ioloop.IOLoop.instance().start()
Example #22
0
def main():
    routes = get_routes(helloworld)
    application = Application(routes=routes, settings={})
    application.listen(8889)
    tornado.ioloop.IOLoop.instance().start()
Example #23
0
def main():
    routes = get_routes(handlers)

    application = Application(routes=routes, settings=settings, db_conn=db)
    application.listen(options.port)
    tornado.ioloop.IOLoop.instance().start()
Example #24
0
def main():
    """
    - Get options from config file
    - Gather all routes
    - Create the server
    - Start the server
    """
    global http_server

    # NOTE: There should be NO logging done before options are loaded
    #   as logging handlers are not yet created
    ctconfig.define_options()  # Define options with defaults
    # Attempt to load config from config file
    try:
        tornado.options.parse_config_file(options.conf_file_path)
    except IOError as e:
        errmsg = ("{} doesn't exist or couldn't be opened. Using defaults."
                  .format(options.conf_file_path))
        logging.error(errmsg)

    logging.info("Getting any static dependencies . . .")
    deps = [
        ("https://raw.github.com/daneden/animate.css/master/animate.min.css", "src/static/animate.css"),
        ("https://raw.githubusercontent.com/cowboy/jquery-throttle-debounce/v1.1/jquery.ba-throttle-debounce.min.js", "src/static/debounce.js")
    ]
    map(retrieve_static_dep, deps)

    routes = mod_routes.assemble_routes()
    settings = dict(
        template_path=os.path.join(
            os.path.dirname(__file__), "templates"),
        static_path=os.path.join(os.path.dirname(__file__), "static"),
        gzip=True,
        cookie_secret=options.cookie_secret if options.cookie_secret
        else uuid.uuid4().hex,
        login_url="/signin/signin"
    )

    # If asked to write routes, do so
    if options.output_routes:
        with open("routes.json", "w+") as f:
            f.write(
                json.dumps(
                    [(route, jsonpickle.encode(rh)) for route, rh in routes],
                    indent=4
                )
            )

    http_server = tornado.httpserver.HTTPServer(
        Application(
            routes=routes,
            settings=settings,
            db_conn=db2.Connection(options.sqlite_db).db,
        )
    )

    for port in options.ports:
        try:
            logging.debug("Attempting to bind on {}.".format(port))
            http_server.listen(port)
            logging.info("Listening on {}.".format(port))
            break
        except socket.error:
            logging.debug("Could not bind on {}.".format(port))
    else:
        raise StandardError("Ran out of ports to try.")

    signal.signal(signal.SIGTERM, sig_handler)
    signal.signal(signal.SIGINT, sig_handler)

    tornado.ioloop.IOLoop.instance().start()

    logging.info("Exit...")
Example #25
0
def main(pargs):
    global redis
    if pargs.production:
        serverConf = configobj.ConfigObj('production.ini')
    else:
        serverConf = configobj.ConfigObj('develop.ini')

    routes = [
        (r"/auth/login", FacebookGraphLoginHandler),
        (r"/", HomeHandler),
        (r"/referral/([^/]+)", ReferralHandler),
        (r"/r/([^/]+)", ReferralHandler),
        (r'/(favicon.ico)', StaticFileHandler, {
            "path": "./static/"
        }),
    ]

    for api in [game, tips, user, referral, prizes]:
        routes.extend(get_routes(api))

    if pargs.admin:
        routes.extend(get_routes(admin))
        routes.extend(get_routes(box))
        from encontact import UserDataHandler
        routes.extend([
            (r"/admin/encontact?/", UserDataHandler),
        ])

    pprint(routes, indent=4)

    mailer = Mail(aws_access_key_id=serverConf['ses']['acceskeyid'],
                  aws_secret_access_key=serverConf['ses']['secretacceskeyid'],
                  region=serverConf['ses']['region'],
                  sender=serverConf['ses']['sender'],
                  template=serverConf['ses']['templates'])

    if pargs.production:
        dyn = DynamoDBConnection.connect(
            region=serverConf['dynamo']['region'],
            access_key=serverConf['dynamo']['acceskeyid'],
            secret_key=serverConf['dynamo']['secretacceskeyid'])
        session_settings = dict(
            driver="redis",
            force_persistence=True,
            cache_driver=True,
            driver_settings=dict(
                host=serverConf['redis']['host'],
                port=int(serverConf['redis']['port']),
                db=int(serverConf['redis']['db']),
                max_connections=1024,
            ),
        )
        pool = ConnectionPool(max_connections=2,
                              host=serverConf['redis']['host'],
                              port=int(serverConf['redis']['port']),
                              db=int(serverConf['redis']['db']) + 1)

        pool2 = ConnectionPool(max_connections=2,
                               host=serverConf['redis']['host'],
                               port=int(serverConf['redis']['port']),
                               db=int(serverConf['redis']['db']))

    else:
        dyn = DynamoDBConnection.connect(region='sp-east',
                                         host='127.0.0.1',
                                         port=8000,
                                         is_secure=False,
                                         access_key='asdas',
                                         secret_key='123ads')
        session_settings = dict(
            driver="redis",
            force_persistence=True,
            cache_driver=True,
            driver_settings=dict(
                host='localhost',
                port=6379,
                db=0,
                max_connections=1024,
            ),
        )
        pool = ConnectionPool(max_connections=2,
                              host='localhost',
                              port=6379,
                              db=1)

        pool2 = ConnectionPool(max_connections=2,
                               host='localhost',
                               port=6379,
                               db=0)

    redis = Redis(connection_pool=pool)
    redis2 = Redis(connection_pool=pool2)
    engine = Engine(dynamo=dyn)
    log = logging.getLogger(__name__)
    a = logging.basicConfig(
        level=logging.INFO,
        format=
        '[ %(asctime)s ][ %(levelname)s ][ %(filename)20s:%(lineno)4s - %(funcName)20s() ] %(message)s',
        datefmt='%m-%d %H:%M',
        filename='log/nextgame.log',
        filemode='a')

    log.addHandler(a)
    settings = {
        "debug": False,
        'xsrf_cookies': False,
        'serverConfig': serverConf,
        'instance': serverConf.get('instance'),
        'engine': engine,
        'facebook_api_key': serverConf['facebook']['key'],
        'facebook_secret': serverConf['facebook']['secret'],
        'session': session_settings,
        'template_path': serverConf['ses']['templates'],
        "login_url": "/auth/login/",
        "cookie_secret": 'sopadeletrinhas123',
        "mailer": mailer,
        "production": False
    }

    if (pargs.debug):
        # log.setLevel(logging.DEBUG)
        log.debug('DEBUGGING LOG')
        settings['debug'] = True

    app = Application(routes=routes,
                      settings=settings,
                      db_conn={
                          'ping': redis,
                          'session': redis2
                      })

    if pargs.provision:
        game.models.create_schemas(engine)
        tips.models.create_schemas(engine)
        referral.models.create_schemas(engine)

    if (pargs.production):
        print('Server Production Starting')
        server = tornado.httpserver.HTTPServer(app)
        server.bind(serverConf['tornado']['port'])
        server.start(int(serverConf['tornado']['instances']))
        tornado.ioloop.IOLoop.configure(TornadoUvloop)

    else:
        print('Server Develop Starting')
        app.listen(serverConf['tornado']['port'])
        tornado.ioloop.IOLoop.configure(TornadoUvloop)

    tornado.ioloop.IOLoop.current().start()