Python tornado.options.options.debug() Examples

The following are 30 code examples of tornado.options.options.debug(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module tornado.options.options , or try the search function .
Example #1
Source File: test_app.py    From webssh with MIT License 6 votes vote down vote up
def get_app(self):
        self.body_dict = {
            'hostname': '127.0.0.1',
            'port': str(self.sshserver_port),
            'username': 'robey',
            'password': '',
            '_xsrf': 'yummy'
        }
        loop = self.io_loop
        options.debug = False
        options.policy = random.choice(['warning', 'autoadd'])
        options.hostfile = ''
        options.syshostfile = ''
        options.tdstream = ''
        app = make_app(make_handlers(loop, options), get_app_settings(options))
        return app 
Example #2
Source File: dashboard.py    From pyaiot with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def __init__(self):
        self._nodes = {}
        if options.debug:
            logger.setLevel(logging.DEBUG)

        handlers = [
            (r'/', DashboardHandler),
        ]
        settings = {'debug': True,
                    "cookie_secret": "MY_COOKIE_ID",
                    "xsrf_cookies": False,
                    'static_path': options.static_path,
                    'template_path': options.static_path
                    }
        super().__init__(handlers, **settings)
        logger.info('Application started, listening on port {0}'
                    .format(options.web_port)) 
Example #3
Source File: test_app.py    From adminset with GNU General Public License v2.0 6 votes vote down vote up
def get_app(self):
        self.body_dict = {
            'hostname': '127.0.0.1',
            'port': str(self.sshserver_port),
            'username': 'robey',
            'password': '',
            '_xsrf': 'yummy'
        }
        loop = self.io_loop
        options.debug = False
        options.policy = random.choice(['warning', 'autoadd'])
        options.hostfile = ''
        options.syshostfile = ''
        options.tdstream = ''
        app = make_app(make_handlers(loop, options), get_app_settings(options))
        return app 
Example #4
Source File: server.py    From politicos with GNU Affero General Public License v3.0 6 votes vote down vote up
def main():
    app = Application()
    app.listen(options.port)
    loop = asyncio.get_event_loop()
    app.init_with_loop(loop)

    enable_pretty_logging()

    if options.debug:
        env = 'development'
    else:
        env = 'production'

    print(f'Starting {env} server at http://localhost:{options.port}/')
    print('Quit the server with CONTROL-C.')

    loop.run_forever() 
Example #5
Source File: user.py    From mltshp with Mozilla Public License 2.0 6 votes vote down vote up
def invalidate_email(self):
        self.email_confirmed = 0
        h = hashlib.sha1()
        h.update("%s" % (time.time()))
        h.update("%s" % (random.random()))
        self.verify_email_token = h.hexdigest()
        self.save()
        if not options.debug:
            pm = postmark.PMMail(api_key=options.postmark_api_key,
                sender="hello@mltshp.com", to=self.email,
                subject="[mltshp] Please verify your email address",
                text_body="Hi there, could you visit this URL to verify your email address for us? Thanks. \n\nhttps://%s/verify-email/%s" % (
                    options.app_host, self.verify_email_token))
            pm.send()
            return True
        return False 
Example #6
Source File: task_tests.py    From mltshp with Mozilla Public License 2.0 6 votes vote down vote up
def test_tweet_best_posts(self):
        old_likes = options.likes_to_tweet
        old_magic = options.likes_to_magic
        old_debug = options.debug
        try:
            options.likes_to_tweet = 1
            options.likes_to_magic = 1
            options.debug = False
            add_posts(shake_id=self.shake_a.id, sharedfile_id=self.shared_1.id, sourcefile_id=self.source.id)
            self.user_b.add_favorite(self.shared_1)
            # this like should trigger a tweet
            self.assertEqual(MockTweepy.count, 1)
            mf = Magicfile.get("sharedfile_id = %s", self.shared_1.id)
            self.assertIsNotNone(mf)
        finally:
            options.likes_to_tweet = old_likes
            options.likes_to_magic = old_magic
            options.debug = old_debug 
Example #7
Source File: fake-registration-server.py    From tuya-convert with MIT License 6 votes vote down vote up
def main():
	parse_command_line()
	get_file_stats('../files/upgrade.bin')
	app = tornado.web.Application(
		[
			(r"/", MainHandler),
			(r"/gw.json", JSONHandler),
			(r"/d.json", JSONHandler),
			('/files/(.*)', FilesHandler, {'path': str('../files/')}),
			(r".*", tornado.web.RedirectHandler, {"url": "http://" + options.addr + "/", "permanent": False}),
		],
		#template_path=os.path.join(os.path.dirname(__file__), "templates"),
		#static_path=os.path.join(os.path.dirname(__file__), "static"),
		debug=options.debug,
	)
	try:
		app.listen(options.port, options.addr)
		print("Listening on " + options.addr + ":" + str(options.port))
		tornado.ioloop.IOLoop.current().start()
	except OSError as err:
		print("Could not start server on port " + str(options.port))
		if err.errno == 98: # EADDRINUSE
			print("Close the process on this port and try again")
		else:
			print(err) 
Example #8
Source File: main.py    From chain with Apache License 2.0 6 votes vote down vote up
def on_write(self):
        logging.debug('worker {} on write'.format(self.id))
        if not self.data_to_dst:
            return

        data = ''.join(self.data_to_dst)
        logging.debug('"{}" to {}:{}'.format(data, *self.dst_addr))

        try:
            sent = self.chan.send(data)
        except (OSError, IOError) as e:
            logging.error(e)
            if errno_from_exception(e) in _ERRNO_CONNRESET:
                self.close()
            else:
                self.update_handler(IOLoop.WRITE)
        else:
            self.data_to_dst = []
            data = data[sent:]
            if data:
                self.data_to_dst.append(data)
                self.update_handler(IOLoop.WRITE)
            else:
                self.update_handler(IOLoop.READ) 
Example #9
Source File: main.py    From chain with Apache License 2.0 6 votes vote down vote up
def on_read(self):
        logging.debug('worker {} on read'.format(self.id))
        try:
            data = self.chan.recv(BUF_SIZE)
        except (OSError, IOError) as e:
            logging.error(e)
            if errno_from_exception(e) in _ERRNO_CONNRESET:
                self.close()
        else:
            logging.debug('"{}" from {}:{}'.format(data, *self.dst_addr))
            if not data:
                self.close()
                return

            logging.debug('"{}" to {}:{}'.format(data, *self.handler.src_addr))
            try:
                self.handler.write_message(data)
            except tornado.websocket.WebSocketClosedError:
                self.close() 
Example #10
Source File: bast.py    From Bast with MIT License 6 votes vote down vote up
def run(self):
        """
        Function to Run the server. Server runs on host: 127.0.0.1 and port: 2000 by default. Debug is also set to false
        by default

        Can be overriden by using the config.ini file
        """
        define("port", default=self.port, help="Run on given port", type=int)
        define("host", default=self.host, help="Run on given host", type=str)
        define("debug", default=self.debug, help="True for development", type=bool)

        parse_command_line()

        print(Fore.GREEN + "Starting Bast Server....")
        print(Fore.GREEN + "Bast Server Running on %s:%s" % (options.host, options.port))

        application = Application(self.handler, debug=options.debug)
        server = HTTPServer(application)
        server.listen(options.port, options.host)
        IOLoop.current().start() 
Example #11
Source File: chatdemo.py    From tornado-zh with MIT License 6 votes vote down vote up
def main():
    parse_command_line()
    app = tornado.web.Application(
        [
            (r"/", MainHandler),
            (r"/a/message/new", MessageNewHandler),
            (r"/a/message/updates", MessageUpdatesHandler),
            ],
        cookie_secret="__TODO:_GENERATE_YOUR_OWN_RANDOM_VALUE_HERE__",
        template_path=os.path.join(os.path.dirname(__file__), "templates"),
        static_path=os.path.join(os.path.dirname(__file__), "static"),
        xsrf_cookies=True,
        debug=options.debug,
        )
    app.listen(options.port)
    tornado.ioloop.IOLoop.current().start() 
Example #12
Source File: latency.py    From python-socketio with MIT License 5 votes vote down vote up
def main():
    parse_command_line()
    app = tornado.web.Application(
        [
            (r"/", MainHandler),
            (r"/socket.io/", socketio.get_tornado_handler(sio)),
        ],
        template_path=os.path.join(os.path.dirname(__file__), "templates"),
        static_path=os.path.join(os.path.dirname(__file__), "static"),
        debug=options.debug,
    )
    app.listen(options.port)
    tornado.ioloop.IOLoop.current().start() 
Example #13
Source File: app.py    From python-socketio with MIT License 5 votes vote down vote up
def main():
    parse_command_line()
    app = tornado.web.Application(
        [
            (r"/", MainHandler),
            (r"/socket.io/", socketio.get_tornado_handler(sio)),
        ],
        template_path=os.path.join(os.path.dirname(__file__), "templates"),
        static_path=os.path.join(os.path.dirname(__file__), "static"),
        debug=options.debug,
    )
    app.listen(options.port)
    tornado.ioloop.IOLoop.current().start() 
Example #14
Source File: latency.py    From python-engineio with MIT License 5 votes vote down vote up
def main():
    parse_command_line()
    app = tornado.web.Application(
        [
            (r"/", MainHandler),
            (r"/engine.io/", engineio.get_tornado_handler(eio)),
        ],
        template_path=os.path.join(os.path.dirname(__file__), "templates"),
        static_path=os.path.join(os.path.dirname(__file__), "static"),
        debug=options.debug,
    )
    app.listen(options.port)
    tornado.ioloop.IOLoop.current().start() 
Example #15
Source File: tools.py    From mltshp with Mozilla Public License 2.0 5 votes vote down vote up
def on_thumbnail_response(self, response):
        if response.code != 200:
            self.render("tools/save-video-error.html", message="We could not load the thumbnail for this file and therefore could not save this video. Please contact support.")
            return

        # save the response
        url = self.get_argument('url')
        current_user = self.get_current_user_object()

        sha1_key = Sourcefile.get_sha1_file_key(file_path=None, file_data=url)
        thumbnail_path = "%s/%s" % (options.uploaded_files, sha1_key)
        fh = open(thumbnail_path, 'wb')
        fh.write(response.body)
        fh.close()
        source_file = Sourcefile.create_from_json_oembed(link=url, oembed_doc=self.oembed_doc, thumbnail_file_path=thumbnail_path)
        #cleanup
        if not options.debug:
            try:
                os.remove(thumbnail_path)
            except:
                pass

        title = ''
        if self.oembed_doc.has_key('title'):
            title = self.oembed_doc['title']

        shared_file = Sharedfile(user_id=current_user.id, name=url, content_type='text/html', source_id=source_file.id, title=title, source_url=url)
        shared_file.save()

        share_key = base36encode(shared_file.id)
        shared_file.share_key = share_key
        shared_file.save()

        user_shake = Shake.get('user_id = %s and type=%s', current_user.id, 'user')
        shared_file.add_to_shake(self.destination_shake)

        if self.oembed_doc.has_key('description'):
            shared_file.description = self.oembed_doc['description']

        self.write({'path' : "/p/%s" % (share_key)})
        self.finish() 
Example #16
Source File: user.py    From mltshp with Mozilla Public License 2.0 5 votes vote down vote up
def create_reset_password_token(self):
        """
        This function will set the reset token and email the user
        """

        h = hashlib.sha1()
        h.update("%s" % (time.time()))
        h.update("%s" % (random.random()))
        self.reset_password_token = h.hexdigest()
        self.save()
        body = """
Hi there,

We just received a password reset request for this email address (user: %s). If you want to change your password just click this link:
https://%s/account/reset-password/%s

Thanks for using the site!
hello@mltshp.com

(If you're having problems with your account, please mail us! We are happy to help.)
""" % (self.name, options.app_host, self.reset_password_token)
        if not options.debug:
            pm = postmark.PMMail(api_key=options.postmark_api_key,
                sender="hello@mltshp.com", to=self.email,
                subject="[mltshp] Password change request",
                text_body=body)
            pm.send() 
Example #17
Source File: command.py    From wscelery with MIT License 5 votes vote down vote up
def setup_logging(self):
        if options.debug and options.logging == 'info':
            options.logging = 'debug'
            enable_pretty_logging()
        else:
            logging.getLogger('tornado.access').addHandler(
                logging.NullHandler())
            logging.getLogger('tornado.access').propagate = False 
Example #18
Source File: notification.py    From mltshp with Mozilla Public License 2.0 5 votes vote down vote up
def new_invitation_to_shake(sender, receiver, action_id):
        """
        sender - user making request
        receiver - user who owns the shake
        action_id - the shake_id
        """
        the_shake = shake.Shake.get('id=%s', action_id)
        
        n = Notification(sender_id=sender.id, receiver_id=receiver.id, action_id=action_id, type='invitation_request')
        text_message = """Hi, %s.
%s has requested to join "%s". This means they will be able to put files into the "%s" shake.

If you want to let %s do this, simply visit your shake and approve the request:

https://%s/%s

You can also ignore the request by deleting the notification.
""" % (receiver.display_name(), sender.display_name(), the_shake.display_name(), the_shake.display_name(),
       sender.display_name(), options.app_host, the_shake.name)
        html_message = """<p>Hi, %s.</p>
<p><a href="https://%s/user/%s">%s</a> has requested to join "<a href="https://%s/%s">%s</a>". This means they will be able to put files into the "%s" shake.</p>

<p>If you want to let %s do this, simply visit your shake and approve the request:</p>

<p><a href="https://%s/%s">https://%s/%s</a></p>

You can also ignore the request by deleting the notification.
""" % (receiver.display_name(), options.app_host, sender.name, sender.display_name(),
       options.app_host, the_shake.name, the_shake.display_name(), the_shake.display_name(),
       sender.display_name(), options.app_host, the_shake.name, options.app_host, the_shake.name)

        n.save()
        if not receiver.disable_notifications and not options.debug:
            pm = postmark.PMMail(api_key=options.postmark_api_key, 
                sender="hello@mltshp.com", to=receiver.email, 
                subject="%s has requested an invitation to %s!" % (sender.display_name(), the_shake.display_name()), 
                text_body=text_message, 
                html_body=html_message)
            pm.send()
        return n 
Example #19
Source File: main.py    From mltshp with Mozilla Public License 2.0 5 votes vote down vote up
def app_settings(cls):
        dirname = os.path.dirname(os.path.abspath(__file__))
        return {
            "debug": options.debug,
            "cookie_secret": options.cookie_secret,
            "xsrf_cookies": options.xsrf_cookies,
            "twitter_consumer_key": options.twitter_consumer_key,
            "twitter_consumer_secret": options.twitter_consumer_secret,

            # invariant settings
            "login_url": "/sign-in",
            "static_path": os.path.join(dirname, "static"),
            "template_path":  os.path.join(dirname, "templates"),
            "ui_modules": lib.uimodules,
        } 
Example #20
Source File: counts.py    From mltshp with Mozilla Public License 2.0 5 votes vote down vote up
def tweet_or_magic(db, sharedfile_id, like_count):
    likes_to_tweet = options.likes_to_tweet
    likes_to_magic = options.likes_to_magic
    if like_count not in (likes_to_tweet, likes_to_magic):
        return

    sf = db.get("SELECT * from sharedfile where id = %s", sharedfile_id)
    if int(sf['original_id']) != 0:
        return

    if like_count == likes_to_magic:
        created_at = datetime.utcnow().strftime("%Y-%m-%d %H:%M:%S")
        db.execute("INSERT IGNORE INTO magicfile (sharedfile_id, created_at) VALUES (%s, %s)", sharedfile_id, created_at)
    if like_count == likes_to_tweet and not options.debug:
        title = ''
        if sf['title'] == '' or sf['title'] == None:
            title = sf['name']
        else:
            title = sf['title']

        auth = tweepy.OAuthHandler(options.twitter_consumer_key, options.twitter_consumer_secret)
        auth.set_access_token(options.twitter_access_key, options.twitter_access_secret)
        api = tweepy.API(auth)
        via_twitter_account = ""
        twitter_account = db.get("SELECT screen_name from externalservice where user_id = %s and deleted=0", sf['user_id'])
        if twitter_account:
            via_twitter_account = " via @{0}".format(twitter_account['screen_name'])
        api.update_status('https://mltshp.com/p/%s "%s"%s' % (sf['share_key'], title[:90], via_twitter_account)) 
Example #21
Source File: test_app.py    From adminset with GNU General Public License v2.0 5 votes vote down vote up
def get_app(self):
        self.body.update(port=str(self.sshserver_port))
        loop = self.io_loop
        options.debug = self.debug
        options.xsrf = self.xsrf
        options.policy = self.policy if self.policy else random.choice(['warning', 'autoadd'])  # noqa
        options.hostfile = self.hostfile
        options.syshostfile = self.syshostfile
        options.tdstream = self.tdstream
        options.maxconn = self.maxconn
        app = make_app(make_handlers(loop, options), get_app_settings(options))
        return app 
Example #22
Source File: simple.py    From python-engineio with MIT License 5 votes vote down vote up
def main():
    parse_command_line()
    app = tornado.web.Application(
        [
            (r"/", MainHandler),
            (r"/engine.io/", engineio.get_tornado_handler(eio)),
        ],
        template_path=os.path.join(os.path.dirname(__file__), "templates"),
        static_path=os.path.join(os.path.dirname(__file__), "static"),
        debug=options.debug,
    )
    app.listen(options.port)
    tornado.ioloop.IOLoop.current().start() 
Example #23
Source File: selftest.py    From SpoofcheckSelfTest with Apache License 2.0 5 votes vote down vote up
def start_worker():
    from tasks import selftest_task_queue
    from tasks.helpers import create_mq_url
    from celery.bin import worker

    worker = worker.worker(app=selftest_task_queue)
    worker_options = {
        'broker': create_mq_url(options.mq_hostname, options.mq_port,
                                username=options.mq_username,
                                password=options.mq_password),
        'loglevel': options.mq_loglevel,
        'traceback': options.debug,
    }
    worker.run(**worker_options) 
Example #24
Source File: bast.py    From Bast with MIT License 5 votes vote down vote up
def __init__(self, route):
        """
         Bast Server Class. Runs on Tornado HTTP Server (http://www.tornadoweb.org/en/stable/)

        Constructor for the Bast Server. Takes an instance of the route as parameter.
        The Web handler with routes are handled here.

        Config files are also loaded from the config/config.ini folder.
        Appropriate configurations are loaded from the config file into the os environment for use
        :param route:
        """

        super(Bast, self).__init__()
        init()

        load_env()
        self.config()

        self.host = os.getenv("HOST", "127.0.0.1")
        self.port = os.getenv("PORT", 2000)
        self.debug = os.getenv("DEBUG", True)

        self.handler = route.all().url
        self.handler.append((r'/css/(.*)', StaticFileHandler, {"path": self.css_folder}))
        self.handler.append((r'/script/(.*)', StaticFileHandler, {"path": self.script_folder}))
        self.handler.append((r'/images/(.*)', StaticFileHandler, {"path": self.image_folder}))

        # append the URL for static files to exception
        self.handler.append((r'/exp/(.*)', StaticFileHandler,
                             {'path': os.path.join(os.path.dirname(os.path.realpath(__file__)), "exception")})) 
Example #25
Source File: app.py    From gprime with GNU General Public License v2.0 5 votes vote down vote up
def default_settings(self):
        """
        """
        import gprime.const
        return {
            "cookie_secret": base64.b64encode(uuid.uuid4().bytes + uuid.uuid4().bytes),
            "login_url":     self.make_url("/login"),
            'template_path': os.path.join(gprime.const.DATA_DIR, "templates"),
            'debug':         self.options.debug,
            "xsrf_cookies":  self.options.xsrf,
        } 
Example #26
Source File: app.py    From gprime with GNU General Public License v2.0 5 votes vote down vote up
def main():
    from tornado.options import options
    import traceback
    try:
        run_app()
    except Exception as exc:
        if options.debug:
            traceback.print_exc()
        else:
            print(exc) 
Example #27
Source File: main.py    From chain with Apache License 2.0 5 votes vote down vote up
def close(self):
        logging.debug('Closing worker {}'.format(self.id))
        if self.handler:
            self.loop.remove_handler(self.fd)
            self.handler.close()
        self.chan.close()
        self.ssh.close()
        logging.info('Connection to {}:{} lost'.format(*self.dst_addr)) 
Example #28
Source File: main.py    From chain with Apache License 2.0 5 votes vote down vote up
def get_args(self):
        hostname = self.get_value('hostname')
        port = self.get_port()
        username = self.get_value('username')
        password = self.get_argument('password')
        privatekey = self.get_privatekey()
        pkey = self.get_pkey(privatekey, password) if privatekey else None
        args = (hostname, port, username, decrypt_p(password), pkey)
        logging.debug(args)
        return args 
Example #29
Source File: main.py    From chain with Apache License 2.0 5 votes vote down vote up
def on_message(self, message):
        logging.debug('"{}" from {}:{}'.format(message, *self.src_addr))
        worker = self.worker_ref()
        worker.data_to_dst.append(message)
        worker.on_write() 
Example #30
Source File: main.py    From chain with Apache License 2.0 5 votes vote down vote up
def get_application_settings():
    base_dir = os.path.dirname(__file__)
    filename = os.path.join(base_dir, 'known_hosts')
    host_keys = get_host_keys(filename)
    system_host_keys = get_host_keys(os.path.expanduser('~/.ssh/known_hosts'))
    policy_class = get_policy_class(options.policy)
    logging.info(policy_class.__name__)

    if policy_class is paramiko.client.AutoAddPolicy:
        host_keys.save(filename)  # for permission test
        host_keys._last_len = len(host_keys)
        tornado.ioloop.PeriodicCallback(
            lambda: save_host_keys(host_keys, filename),
            options.period * 1000  # milliseconds
        ).start()
    elif policy_class is paramiko.client.RejectPolicy:
        if not host_keys and not system_host_keys:
            raise ValueError('Empty known_hosts with reject policy?')

    settings = dict(
        template_path=os.path.join(base_dir, 'templates'),
        static_path=os.path.join(base_dir, 'static'),
        cookie_secret=uuid.uuid4().hex,
        xsrf_cookies=False,  ##修改源代码的地方
        host_keys=host_keys,
        system_host_keys=system_host_keys,
        policy=policy_class(),
        debug=options.debug
    )

    return settings