当前位置: 首页>>代码示例>>Python>>正文


Python方法tornado.options.options.debug代码示例

以下是Python方法tornado.options.options.debug的代码示例。如果您正苦于以下问题:Python options.debug方法的具体用法?Python options.debug怎么用?Python options.debug使用的例子?那么恭喜您, 这里整理的方法代码示例例程将为您提供帮助。您也可以进一步了解该方法所在模块tornado.options.options的用法示例。

本文一共展示了options.debug的44个开源代码实例,这些例子默认根据受欢迎程度排序。您可以为喜欢的代码打CALL点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。

示例1: setup_backup

# 需要导入模块: from tornado.options import options [as 别名]
# 或者: from tornado.options.options import debug [as 别名]
def setup_backup():
    if not Options['backup_hhmm']:
        return
    curTimeSec = sliauth.epoch_ms()/1000.0
    curDate = sliauth.iso_date(sliauth.create_date(curTimeSec*1000.0))[:10]
    backupTimeSec = sliauth.epoch_ms(sliauth.parse_date(curDate+'T'+Options['backup_hhmm']))/1000.0
    backupInterval = 86400
    if curTimeSec+60 > backupTimeSec:
        backupTimeSec += backupInterval
    print >> sys.stderr, Options['site_name'] or 'ROOT', 'Scheduled daily backup in dir %s, starting at %s' % (Options['backup_dir'], sliauth.iso_date(sliauth.create_date(backupTimeSec*1000.0)))
    def start_backup():
        if Options['debug']:
            print >> sys.stderr, "Starting periodic backup"
        backupSite()
        Global.backup = PeriodicCallback(backupSite, backupInterval*1000.0)
        Global.backup.start()

    IOLoop.current().call_at(backupTimeSec, start_backup) 
开发者ID:mitotic,项目:slidoc,完整代码来源:sdserver.py


示例2: __init__

# 需要导入模块: from tornado.options import options [as 别名]
# 或者: from tornado.options.options import debug [as 别名]
def __init__(self):
        handlers = [
            (r"/", IndexHandler),
            (r"/plugin/(.*)", PluginsHandler),
        ]

        settings = dict(
            template_path=os.path.join(os.path.dirname(__file__), "templates"),
            static_path=os.path.join(os.path.dirname(__file__), "static"),
            # xsrf_cookies=True,
            # cookie_secret="__TODO:_GENERATE_YOUR_OWN_RANDOM_VALUE_HERE__",
            # login_url="/auth/login",
            ui_modules={'Plugin': PluginModule},
            debug=options.debug,
        )
        tornado.web.Application.__init__(self, handlers, **settings) 
开发者ID:wtq2255,项目:sys_monitor,完整代码来源:server_web.py


示例3: set_id

# 需要导入模块: from tornado.options import options [as 别名]
# 或者: from tornado.options.options import debug [as 别名]
def set_id(self, username, role='', sites='', displayName='', email='', altid='', data={}):
        if Options['debug']:
            print >> sys.stderr, 'sdserver.UserIdMixin.set_id', username, role, sites, displayName, email, altid, data

        if ':' in username or ':' in role or ':' in sites or ':' in displayName:
            raise Exception('Colon character not allowed in username/role/name')

        cookie_data = {'version': COOKIE_VERSION}
        cookie_data['name'] = displayName or username
        if email:
            cookie_data['email'] = email
        if altid:
            cookie_data['altid'] = altid

        cookie_data.update(data)

        token = gen_proxy_auth_token(username, role, sites, root=True)
        cookieStr = ':'.join( sliauth.safe_quote(x) for x in [username, role, sites, token, base64.b64encode(json.dumps(cookie_data,sort_keys=True))] )

        self.set_user_cookie(cookieStr, batch=cookie_data.get('batch')) 
开发者ID:mitotic,项目:slidoc,完整代码来源:sdserver.py


示例4: imageUpload

# 需要导入模块: from tornado.options import options [as 别名]
# 或者: from tornado.options.options import debug [as 别名]
def imageUpload(self, sessionName, imageFile, fname, fbody, autonumber=None):
        if Options['debug']:
            print >> sys.stderr, 'ActionHandler:imageUpload', sessionName, imageFile, fname, autonumber, len(fbody)
        if not self.previewActive():
            raise tornado.web.HTTPError(404, log_message='CUSTOM:Not previewing session')
        if not imageFile:
            imgName = re.sub(r'[^\w,.+-]', '', fname.strip().replace(' ','_'))
            if imgName and not autonumber:
                imageFile = imgName
            else:
                imageFile = (md2md.IMAGE_FMT % self.previewState['new_image_number']) + os.path.splitext(fname)[1].lower()
            self.previewState['new_image_number'] += 1
        if not self.previewState['image_zipfile']:
            self.previewState['image_zipbytes'] = io.BytesIO()
            self.previewState['image_zipfile'] = zipfile.ZipFile(self.previewState['image_zipbytes'], 'a')
        imagePath = sessionName+'_images/' + imageFile
        self.previewState['image_zipfile'].writestr(imagePath, fbody)
        self.previewState['image_paths'][imageFile] = imagePath
        self.previewState['modimages'] = 'append'

        self.set_header('Content-Type', 'application/json')
        self.write( json.dumps( {'result': 'success', 'imageFile': imageFile} ) ) 
开发者ID:mitotic,项目:slidoc,完整代码来源:sdserver.py


示例5: on_close

# 需要导入模块: from tornado.options import options [as 别名]
# 或者: from tornado.options.options import debug [as 别名]
def on_close(self):
        if Options['debug']:
            print >> sys.stderr, "DEBUG: WSon_close", getattr(self, 'pathUser', 'NOT OPENED')
        try:
            if self.eventFlusher:
                self.eventFlusher.stop()
                self.eventFlusher = None
            self._connections[self.pathUser[0]][self.pathUser[1]].remove(self)
            if not self._connections[self.pathUser[0]][self.pathUser[1]]:
                del self._connections[self.pathUser[0]][self.pathUser[1]]
            if not self._connections[self.pathUser[0]]:
                del self._connections[self.pathUser[0]]

            if self._interactiveSession[0] is self:
                # Disable interactivity associated with this connection
                self._interactiveSession = (None, None, None, None)

        except Exception, err:
            pass 
开发者ID:mitotic,项目:slidoc,完整代码来源:sdserver.py


示例6: post

# 需要导入模块: from tornado.options import options [as 别名]
# 或者: from tornado.options.options import debug [as 别名]
def post(self, subpath=''):
        try:
            userRole = self.get_id_from_cookie(role=True, for_site=Options['site_name'])
            msg = WSHandler.processMessage(self.get_id_from_cookie(), userRole, self.get_id_from_cookie(name=True), self.get_argument("message", ""), allStatus=True, source='interact', adminBroadcast=True)
            if not msg:
                msg = 'Previous message accepted'
        except Exception, excp:
            if Options['debug']:
                import traceback
                traceback.print_exc()
                msg = 'Error in processing message: '+str(excp)
                print >> sys.stderr, "AuthMessageHandler.post", msg
            else:
                msg = 'Error in processing message'
        site_prefix = '/'+Options['site_name'] if Options['site_name'] else ''
        self.redirect(site_prefix+'/interact/?note='+sliauth.safe_quote(msg)) 
开发者ID:mitotic,项目:slidoc,完整代码来源:sdserver.py


示例7: restoreSheet

# 需要导入模块: from tornado.options import options [as 别名]
# 或者: from tornado.options.options import debug [as 别名]
def restoreSheet(sheetName, filepath, csvfile, overwrite=None):
    # Restore sheet from backup CSV file
    try:
        ##dialect = csv.Sniffer().sniff(csvfile.read(1024))
        ##csvfile.seek(0)
        reader = csv.reader(csvfile, delimiter=',')  # Ignore dialect for now
        rows = [row for row in reader]
        if not rows:
            raise Exception('No rows in CSV file %s for sheet %s' % (filepath, sheetName))

        sdproxy.importSheet(sheetName, rows[0], rows[1:], overwrite=overwrite)
        return ''

    except Exception, excp:
        if Options['debug']:
            import traceback
            traceback.print_exc()
        return 'Error in restoreSheet: '+str(excp) 
开发者ID:mitotic,项目:slidoc,完整代码来源:sdserver.py


示例8: shutdown_all

# 需要导入模块: from tornado.options import options [as 别名]
# 或者: from tornado.options.options import debug [as 别名]
def shutdown_all(keep_root=False):
    if Options['debug']:
        print >> sys.stderr, 'sdserver.shutdown_all:'

    if not Global.remoteShutdown:
        Global.remoteShutdown = True
        for j, site in enumerate(Options['site_list']):
            # Shutdown child servers
            relay_addr = SiteProps.relay_map(j+1)
            try:
                retval = sendPrivateRequest(relay_addr, path='/'+site+'/_shutdown?root='+Options['server_key'])
            except Exception, excp:
                print >> sys.stderr, 'sdserver.shutdown_all: Error in shutting down site', site, excp

    if not keep_root:
        shutdown_root() 
开发者ID:mitotic,项目:slidoc,完整代码来源:sdserver.py


示例9: start_multiproxy

# 需要导入模块: from tornado.options import options [as 别名]
# 或者: from tornado.options.options import debug [as 别名]
def start_multiproxy():
    import multiproxy
    class ProxyRequestHandler(multiproxy.RequestHandler):
        def get_relay_addr_uri(self, pipeline, header_list):
            """ Returns relay host, port.
            May modify self.request_uri or header list (excluding the first element)
            Raises exception if connection not allowed.
            """
            comps = self.request_uri.split('/')
            if len(comps) > 1 and comps[1] and comps[1] in Options['site_list']:
                # Site server
                site_number = 1+Options['site_list'].index(comps[1])
                retval = SiteProps.relay_map(site_number)
            elif Global.relay_forward and not self.request_uri.startswith('/_'):
                # Not URL starting with '_'; forward to underlying website
                retval = Global.relay_forward
            else:
                # Root server
                retval = SiteProps.relay_map(0)
            print >> sys.stderr, 'ABC: get_relay_addr_uri:', sliauth.iso_date(nosubsec=True), self.ip_addr, self.request_uri, retval
            return retval

    Global.proxy_server = multiproxy.ProxyServer(Options['host'], Options['port'], ProxyRequestHandler, log_interval=0,
                      io_loop=IOLoop.current(), xheaders=True, masquerade="server/1.2345", ssl_options=Options['ssl_options'], debug=True) 
开发者ID:mitotic,项目:slidoc,完整代码来源:sdserver.py


示例10: getSettingsSheet

# 需要导入模块: from tornado.options import options [as 别名]
# 或者: from tornado.options.options import debug [as 别名]
def getSettingsSheet(gsheet_url, site_name='', adminonly_fail=False):
    try:
        bak_dir = getBakDir(site_name)
        if bak_dir:
            settingsPath = os.path.join(bak_dir, sdproxy.SETTINGS_SHEET+'.csv')
            if not os.path.exists(settingsPath):
                raise Exception('Settings sheet %s not found in backup directory' % settingsPath )

            with open(settingsPath, 'rb') as f:
                rows = [row for row in csv.reader(f, delimiter=',')]
            if not rows:
                raise Exception('No rows in CSV file %s for settings sheet %s' % (settingsPath, sdproxy.SETTINGS_SHEET))
            headers = rows[0]
            rows = rows[1:]
        else:
            rows, headers = sliauth.read_sheet(gsheet_url, Options['root_auth_key'], sdproxy.SETTINGS_SHEET, site=site_name)
        return sliauth.get_settings(rows)
    except Exception, excp:
        ##if Options['debug']:
        ##    import traceback
        ##    traceback.print_exc()
        print >> sys.stderr, 'Error:site %s: Failed to read Google Sheet settings_slidoc from %s: %s' % (site_name, gsheet_url, excp)
        return {'site_access': 'adminonly'} if adminonly_fail else {} 
开发者ID:mitotic,项目:slidoc,完整代码来源:sdserver.py


示例11: getSiteRosterMaps

# 需要导入模块: from tornado.options import options [as 别名]
# 或者: from tornado.options.options import debug [as 别名]
def getSiteRosterMaps(gsheet_url, site_name=''):
    try:
        rows, headers = sliauth.read_sheet(gsheet_url, Options['root_auth_key'], sdproxy.ROSTER_SHEET, site=site_name)
        nameCol  = 1 + headers.index('name')
        idCol    = 1 + headers.index('id')
        emailCol = 1 + headers.index('email')
        rosterMaps = {}
        rosterMaps['id2email'] = dict( (x[idCol-1], x[emailCol-1]) for x in rows[1:] if x[idCol-1] )
        rosterMaps['id2name']  = dict( (x[idCol-1], x[nameCol-1])  for x in rows[1:] if x[idCol-1] )
        return rosterMaps

    except Exception, excp:
        ##if Options['debug']:
        ##    import traceback
        ##    traceback.print_exc()
        print >> sys.stderr, 'Error:site %s: Failed to read Google Sheet roster_slidoc from %s: %s' % (site_name, gsheet_url, excp)
        return {} 
开发者ID:mitotic,项目:slidoc,完整代码来源:sdserver.py


示例12: option_handle

# 需要导入模块: from tornado.options import options [as 别名]
# 或者: from tornado.options.options import debug [as 别名]
def option_handle():
    """?????????"""
    parse_command_line()
    if options.config:
        if os.path.exists(options.config):
            options.parse_config_file(options.config)
        else:
            print "can not find %s"%options.config
            print "usage:python %s --help"%os.path.basename(__file__)
            sys.exit(1)

    if options.voicelist:
        def _parse_voicelist():
            return tornado.escape.json_decode(options.voicelist)
        global ALL_VOICE
        ALL_VOICE = _parse_voicelist()
        logging.debug("conf voicelist: %s", ALL_VOICE)
    if options.cache_dir:
        mkdir_p(options.cache_dir) 
开发者ID:langsiji,项目:tts-server,完整代码来源:server.py


示例13: main

# 需要导入模块: from tornado.options import options [as 别名]
# 或者: from tornado.options.options import debug [as 别名]
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() 
开发者ID:hhstore,项目:annotated-py-tornado,完整代码来源:chatdemo.py


示例14: main

# 需要导入模块: from tornado.options import options [as 别名]
# 或者: from tornado.options.options import debug [as 别名]
def main():
    tornado.options.parse_command_line()
    app = App()
    http_server = tornado.httpserver.HTTPServer(app)
    http_server.listen(options.port)

    if options.debug:
        # autorelaod for template file
        tornado.autoreload.start()
        for root, dir, files in os.walk(TEMPLATE_PATH):
            for item in files:
                if item.endswith('.html'):
                    tornado.autoreload.watch(os.path.join(root, item))

    try:
        tornado.ioloop.IOLoop.current().start()
    except:
        tornado.ioloop.IOLoop.current().stop() 
开发者ID:PegasusWang,项目:wechannel,完整代码来源:app.py


示例15: main

# 需要导入模块: from tornado.options import options [as 别名]
# 或者: from tornado.options.options import debug [as 别名]
def main():
    parse_command_line()
    app = tornado.web.Application(
        [
            (r"/", MainHandler),
            (r"/a/message/new", MessageNewHandler),
            (r"/a/message/updates", MessageUpdatesHandler),
            ],
        cookie_secret="153A3FDSIKM56",
        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() 
开发者ID:mananpal1997,项目:Useful-Python-libraries,完整代码来源:tornado_test.py


示例16: send_shake_member_removal

# 需要导入模块: from tornado.options import options [as 别名]
# 或者: from tornado.options.options import debug [as 别名]
def send_shake_member_removal(former_shake, former_member):
        """
        Sends an email informing someone they were removed from a shake.
        """
        text_message = """Hi %s.
This is a note to let you know you were removed as a member of "%s". 

You can still follow the shake, but the editor has decided to remove you as an image contributor.

Editors remove members for various reasons. Either the shake is shutting down or they want to do something different with it.

Thank you,
- MLTSHP
""" % (former_member.display_name(), former_shake.display_name())
        if not former_member.disable_notifications and not options.debug:
            pm = postmark.PMMail(api_key=options.postmark_api_key, 
                sender="[email protected]", to=former_member.email, 
                subject="Removal from %s shake" % (former_shake.display_name()), 
                text_body=text_message)
            pm.send() 
开发者ID:MLTSHP,项目:mltshp,完整代码来源:notification.py


示例17: test_tweet_best_posts

# 需要导入模块: from tornado.options import options [as 别名]
# 或者: from tornado.options.options import debug [as 别名]
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 
开发者ID:MLTSHP,项目:mltshp,完整代码来源:task_tests.py


示例18: main

# 需要导入模块: from tornado.options import options [as 别名]
# 或者: from tornado.options.options import debug [as 别名]
def main():
    parse_command_line()
    redis.connect(host=options.redis_host)
    app = tornado.web.Application(
        [
            (r'/', MainHandler),
            (r'/oauth', OAuthHandler),
            (r'/command', CommandHandler),
            (r'/button', ButtonHandler),
        ],
        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)
    ioloop = tornado.ioloop.IOLoop.current()
    ioloop.start() 
开发者ID:marksteve,项目:slash-onenight,完整代码来源:app.py


示例19: main

# 需要导入模块: from tornado.options import options [as 别名]
# 或者: from tornado.options.options import debug [as 别名]
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() 
开发者ID:DingGuodong,项目:LinuxBashShellScriptForOps,完整代码来源:chatdemo.py


示例20: main

# 需要导入模块: from tornado.options import options [as 别名]
# 或者: from tornado.options.options import debug [as 别名]
def main():
    """Creates Tornado Application and starts the IO Loop
    """

    # Get the Port and Debug mode from command line options
    options.parse_command_line()

    # create logger for app
    logger = logging.getLogger('app')
    logger.setLevel(logging.INFO)

    FORMAT = '%(asctime)s - %(name)s - %(levelname)s - %(message)s'
    logging.basicConfig(format=FORMAT)

    tic_tac_toe_game_manager = TicTacToeGameManager()

    urls = [
        (r"/$", IndexHandler),
        (r"/tic-tac-toe$", TicTacToeHandler),
        (r"/tic-tac-toe/ws$", TicTacToeSocketHandler, dict(game_manager=tic_tac_toe_game_manager))
    ]

    # Create Tornado application
    application = tornado.web.Application(
        urls,
        debug=options.debug,
        autoreload=options.debug,
        **settings)

    # Start Server
    logger.info("Starting App on Port: {} with Debug Mode: {}".format(options.port, options.debug))
    application.listen(options.port)
    tornado.ioloop.IOLoop.current().start() 
开发者ID:sampathweb,项目:board-games-app,完整代码来源:server.py


示例21: run

# 需要导入模块: from tornado.options import options [as 别名]
# 或者: from tornado.options.options import debug [as 别名]
def run():
    define('port', default=8090, type=int, help='')
    define('debug', default=False, type=bool, help='')
    parse_command_line()
    settings['debug'] = options.debug
    if settings['debug']:
        print 'debug mode'

    '''
        connect mongodb
    '''
    try:
        client = MotorClient(settings['database']['address'])
        settings['connection'] = client[settings['database']['db']]
    except:
        print 'can not connect MongoDB'
        sys.exit(0)

    '''
        connect redis
    '''
    try:
        client = redis.Redis(host=settings['redis']['host'],
                             port=settings['redis']['port'],
                             db=settings['redis']['db'])
        settings['redis_conn'] = client
    except:
        print 'can not connect redis'
        sys.exit(0)

    application = Application(
        handlers=urlpattern,
        **settings
    )

    http_server = HTTPServer(application, xheaders=True)
    http_server.listen(options.port)
    IOLoop.instance().start() 
开发者ID:Hanaasagi,项目:Ushio,完整代码来源:main.py


示例22: __init__

# 需要导入模块: from tornado.options import options [as 别名]
# 或者: from tornado.options.options import debug [as 别名]
def __init__(self, debug):
        root = os.path.dirname(__file__)
        static_path = os.path.join(root, 'static')
        template_path = os.path.join(root, 'templates')
        settings = {
            'debug': debug,
            'compress_response': True,
            'template_path': template_path,
        }

        # routes
        handlers = [
            (r'/submit', FormHandler),
            (r'/results/?', ResultsSummaryHandler),
            (r'/results/([0-9a-fA-F-]+)/?', ResultsHandler),
            (r'/tracking/([0-9a-fA-F-]+)/([A-Za-z0-9._-]+)/?', TrackingHandler),
            (r'/unsubscribe/([0-9a-fA-F-]+)/?', BlacklistHandler),
            (r'/privacy/?', PrivacyHandler),
            (r'/', MainHandler),
            (r'/(.*)', StaticHandler, {'path': static_path}),
        ]

        # database instance
        self.db = db.MailerDatabase(config.DB_PATH)

        # rate limiters
        self.global_limiter = ratelimit.Bucket(**config.GLOBAL_RATE_LIMIT)
        self.ip_limiters = {}

        tornado.web.Application.__init__(self, handlers, **settings) 
开发者ID:itdelatrisu,项目:email-tracking-tester,完整代码来源:webserver.py


示例23: main

# 需要导入模块: from tornado.options import options [as 别名]
# 或者: from tornado.options.options import debug [as 别名]
def main():
    parse_command_line()
    app = application(options.debug)
    port = int(os.environ.get("PORT", options.port))
    app.listen(port)
    tornado.ioloop.IOLoop.current().start() 
开发者ID:icoxfog417,项目:karura,完整代码来源:run.py


示例24: default_settings

# 需要导入模块: from tornado.options import options [as 别名]
# 或者: from tornado.options.options import debug [as 别名]
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,
        } 
开发者ID:GenealogyCollective,项目:gprime,完整代码来源:app.py


示例25: main

# 需要导入模块: from tornado.options import options [as 别名]
# 或者: from tornado.options.options import debug [as 别名]
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) 
开发者ID:GenealogyCollective,项目:gprime,完整代码来源:app.py


示例26: write_error

# 需要导入模块: from tornado.options import options [as 别名]
# 或者: from tornado.options.options import debug [as 别名]
def write_error(self, status_code, **kwargs):
        if 'exc_info' in kwargs:
            exc_type, exc, trace = kwargs['exc_info']
            if exc.args and isinstance(exc.args[0], dict):
                error = exc.args[0]
            else:
                error = dict()
            if tornado_options.debug:
                error['traceback'] = format_exception(exc_type, exc, trace)
            self.reply(error) 
开发者ID:mxgnene01,项目:wxnotify,完整代码来源:controller.py


示例27: get_id_from_cookie

# 需要导入模块: from tornado.options import options [as 别名]
# 或者: from tornado.options.options import debug [as 别名]
def get_id_from_cookie(self, role=False, for_site='', sites=False, name=False, email=False, altid=False, data=False):
        # If for_site and site name does not appear in cookie.sites, None will be returned for role
        # Null string will be returned for role, if site name is present
        cookieStr = self.get_user_cookie()
        if not cookieStr:
            return None
        try:
            comps = [urllib.unquote(x) for x in cookieStr.split(':')]
            ##if Options['debug']:
                ##print >> sys.stderr, "DEBUG: sdserver.UserIdMixin.get_id_from_cookie", comps
            userId, userRole, userSites, token, data_json = comps[:5]
            userData = json.loads(base64.b64decode(data_json))

            if role:
                if not userRole and for_site:
                    if not userSites:
                        return None
                    return sdproxy.getSiteRole(for_site, userSites)
                return userRole

            if sites:
                return userSites
            if name:
                return userData.get('name', '')
            if email:
                return userData.get('email', '')
            if altid:
                return userData.get('altid', '')
            if data:
                return userData
            return userId
        except Exception, err:
            print >> sys.stderr, 'sdserver: COOKIE ERROR - '+str(err)
            self.clear_user_cookie()
            return None 
开发者ID:mitotic,项目:slidoc,完整代码来源:sdserver.py


示例28: get

# 需要导入模块: from tornado.options import options [as 别名]
# 或者: from tornado.options.options import debug [as 别名]
def get(self, subpath, inner=None):
        userId = self.get_current_user()
        if Options['debug'] and not self.get_argument('reload', ''):
            print >> sys.stderr, 'DEBUG: ActionHandler.get', userId, Options['site_number'], subpath
        if subpath == '_logout':
            self.clear_user_cookie()
            self.render('logout.html')
            return
        root = str(self.get_argument("root", ""))
        token = str(self.get_argument("token", ""))
        if not self.check_admin_access(token=token, root=root):
            if self.previewActive() and subpath.startswith('_preview/') and not self.get_user_cookie():
                next_url = '/' + subpath
                if Options['site_name']:
                    next_url = '/'+Options['site_name']+next_url
                self.redirect(Global.login_url+'?next='+urllib.quote_plus(next_url))
                return
            raise tornado.web.HTTPError(403, log_message='CUSTOM:<a href="/">Login</a> as admin to proceed %s' % self.previewActive())
        try:
            return self.getAction(subpath)
        except Exception, excp:
            msg = str(excp)
            if msg.startswith('CUSTOM:') and not Options['debug']:
                print >> sys.stderr, 'sdserver: '+msg
                self.custom_error(500, '<html><body><h3>%s</h3></body></html>' % msg[len('CUSTOM:'):])
                return
            else:
                raise 
开发者ID:mitotic,项目:slidoc,完整代码来源:sdserver.py


示例29: put

# 需要导入模块: from tornado.options import options [as 别名]
# 或者: from tornado.options.options import debug [as 别名]
def put(self, subpath):
        if Options['debug']:
            print >> sys.stderr, 'DEBUG: putAction', Options['site_number'], subpath, len(self.request.body), self.request.arguments, self.request.headers.get('Content-Type')
        action, sep, subsubpath = subpath.partition('/')
        if action == '_remoteupload':
            token = sliauth.gen_hmac_token(Options['auth_key'], 'upload:'+sliauth.digest_hex(self.request.body))
            if self.get_argument('token') != token:
                raise tornado.web.HTTPError(404, log_message='CUSTOM:Invalid remote upload token')
            fname, fext = os.path.splitext(subsubpath)
            uploadType, sessionNumber, src_path, web_path, web_images = self.getUploadType(fname)
            errMsg = ''
            if fext == '.zip':
                fname1, fbody1, fname2, fbody2 = '', '', subsubpath, self.request.body
            else:
                fname1, fbody1, fname2, fbody2 = subsubpath, self.request.body, '', ''
                if fbody1 and fext == '.md':
                    fbody1 = sliauth.normalize_newlines(fbody1)

            try:
                errMsg = self.uploadSession(uploadType, sessionNumber, fname1, fbody1, fname2, fbody2, modimages='clear')
            except Exception, excp:
                if Options['debug']:
                    import traceback
                    traceback.print_exc()
                errMsg = str(excp)
            if errMsg:
                raise tornado.web.HTTPError(404, log_message='CUSTOM:Error in remote uploading session: '+errMsg)
            self.set_status(200)
            self.finish()
            return
        raise tornado.web.HTTPError(403, log_message='CUSTOM:Invalid PUT action '+action) 
开发者ID:mitotic,项目:slidoc,完整代码来源:sdserver.py


示例30: reloadPreview

# 需要导入模块: from tornado.options import options [as 别名]
# 或者: from tornado.options.options import debug [as 别名]
def reloadPreview(self, slideNumber=0):
        previewingSession = self.previewActive()
        if not previewingSession:
            return
        previewPath = '_preview/index.html'
        if Options['site_name']:
            previewPath = Options['site_name'] + '/' + previewPath
        sessionConnections = WSHandler.get_connections('index')
        userId = self.get_id_from_cookie()
        userRole = self.get_id_from_cookie(role=True, for_site=Options['site_name'])
        userConnections = sessionConnections.get(userId, [])
        if Options['debug']:
            print >> sys.stderr, 'sdserver.reloadPreview: slide=%s, conn=%s' % (slideNumber, len(userConnections))
        for connection in userConnections:
            connection.sendEvent(previewPath, '', userRole, ['', 1, 'ReloadPage', [slideNumber]]) 
开发者ID:mitotic,项目:slidoc,完整代码来源:sdserver.py


示例31: rebuild

# 需要导入模块: from tornado.options import options [as 别名]
# 或者: from tornado.options.options import debug [as 别名]
def rebuild(self, uploadType='', indexOnly=False, make='', log_dict=False):
        if uploadType:
            utypes = [uploadType] if uploadType != TOP_LEVEL else []
        else:
            utypes = self.get_session_names()

        if not indexOnly:
            WSHandler.lockAllConnections('Site rebuilt. Reload page', reload=True)

        msg_dict = {}
        msg_list = []
        if Options['debug'] :
            print >> sys.stderr, 'sdserver.rebuild:', make, utypes
        for utype in utypes:
            retval = self.compile(utype, dest_dir=self.site_web_dir+privatePrefix(utype)+'/'+utype, indexOnly=indexOnly, make=make)
            msgs = retval.get('messages',[])
            msg_dict[utype] = msgs
            if msgs:
                msg_list += msgs + ['']

        retval = self.compile(TOP_LEVEL, dest_dir=self.site_web_dir, indexOnly=False, make='')
        msgs = retval.get('messages',[])
        msg_dict[TOP_LEVEL] = msgs
        if msgs:
            msg_list += msgs

        return msg_dict if log_dict else msg_list 
开发者ID:mitotic,项目:slidoc,完整代码来源:sdserver.py


示例32: truncateSession

# 需要导入模块: from tornado.options import options [as 别名]
# 或者: from tornado.options.options import debug [as 别名]
def truncateSession(self, truncateParams, prevSessionName='', prevMsgs=[], rollingOver=False):
        # Truncate session (possibly after rollover)
        sessionName = truncateParams['sessionName']
        sessionPath = getSessionPath(sessionName, site_prefix=True)

        try:
            errMsg = self.uploadSession(truncateParams['uploadType'], truncateParams['sessionNumber'], truncateParams['sessionName']+'.md', truncateParams['sessionText'], truncateParams['fname2'], truncateParams['fbody2'], modify='truncate', rollingOver=rollingOver)

        except Exception, excp:
            if Options['debug']:
                import traceback
                traceback.print_exc()
            raise tornado.web.HTTPError(404, log_message='CUSTOM:Error in truncating rolled over session %s: %s' % (sessionName, excp))

        if errMsg:
            if self.previewState:
                self.discardPreview()
            if prevSessionName:
                self.displayMessage('Error in truncating rolled over session '+sessionName+': '+errMsg, back_url=sessionPath)
            else:
                self.set_header('Content-Type', 'application/json')
                retval = {'result': 'error', 'error': errMsg}
                self.write( json.dumps(retval) )
            return

        self.previewState['modimages'] = 'clear'

        previewPath = '/_preview/index.html'
        if Options['site_name']:
            previewPath = '/'+Options['site_name']+previewPath

        if prevSessionName:
            html_prefix = 'Rolled over %s slides from session %s to session %s. Proceed to preview of truncated session <a href="%s">%s</a>' % (truncateParams['slidesRolled'], sessionName, prevSessionName, previewPath, sessionName)
            self.displayMessage(prevMsgs, html_prefix=html_prefix)
        else:
            self.set_header('Content-Type', 'application/json')
            retval = {'result': 'success'}
            self.write( json.dumps(retval) ) 
开发者ID:mitotic,项目:slidoc,完整代码来源:sdserver.py


示例33: extract_slides

# 需要导入模块: from tornado.options import options [as 别名]
# 或者: from tornado.options.options import debug [as 别名]
def extract_slides(self, src_path, web_path):
        try:
            return slidoc.extract_slides(src_path, web_path)
        except Exception, excp:
            if Options['debug']:
                import traceback
                traceback.print_exc()
            raise tornado.web.HTTPError(404, log_message='CUSTOM:'+str(excp)) 
开发者ID:mitotic,项目:slidoc,完整代码来源:sdserver.py


示例34: setupInteractive

# 需要导入模块: from tornado.options import options [as 别名]
# 或者: from tornado.options.options import debug [as 别名]
def setupInteractive(cls, connection, path, action, slideId='', questionAttrs=None, rollbackOption=None):
        if Options['debug']:
            print >> sys.stderr, 'sdserver.setupInteractive:', path, action, cls._interactiveSession

        interactiveSession = UserIdMixin.get_path_base(cls._interactiveSession[1]) if cls._interactiveSession[1] else ''
        basePath = UserIdMixin.get_path_base(path) if path else ''
        if action == 'start':
            if interactiveSession and interactiveSession != basePath:
                raise Exception('There is already an interactive session: '+interactiveSession)
            if not basePath:
                return
            cls._interactiveSession = (connection, path, slideId, questionAttrs)
            cls._interactiveErrors = {}
            if rollbackOption:
                sdproxy.startTransactSession(basePath)

        elif action in ('rollback', 'end'):
            if not interactiveSession:
                return
            cls._interactiveSession = (None, '', '', None)
            cls._interactiveErrors = {}
            if sdproxy.transactionalSession(interactiveSession):
                if action == 'rollback':
                    sdproxy.rollbackTransactSession(interactiveSession)
                else:
                    sdproxy.endTransactSession(interactiveSession) 
开发者ID:mitotic,项目:slidoc,完整代码来源:sdserver.py


示例35: closeConnections

# 需要导入模块: from tornado.options import options [as 别名]
# 或者: from tornado.options.options import debug [as 别名]
def closeConnections(cls, path, userIdList, excludeId=None):
        # Note: closed connections may be automatically re-opened; use lockConnection to force reloads
        sessionConnections = cls._connections.get(path,{})
        for userId in userIdList:
            if excludeId and userId == excludeId:
                continue
            if Options['debug']:
                print >> sys.stderr, "DEBUG: sdserver.closeConnections", 'Closing connections for user:', userId
            for connection in sessionConnections.get(userId,[])[:]:  # connection list may be altered by close
                connection.close() 
开发者ID:mitotic,项目:slidoc,完整代码来源:sdserver.py


示例36: lockSessionConnections

# 需要导入模块: from tornado.options import options [as 别名]
# 或者: from tornado.options.options import debug [as 别名]
def lockSessionConnections(cls, sessionName, lock_msg, reload=False):
        # Lock all socket connections for specified session (for uploads/modifications)
        # (Null string value for lock_msg unlocks)
        if Options['debug']:
            print >> sys.stderr, 'DEBUG: lockSessionConnections', sessionName, lock_msg, reload
        for userId, connections in cls.get_connections(sessionName).items():
            for connection in connections:
                connection.locked = lock_msg
                connection.write_message_safe(json.dumps([0, 'lock', [connection.locked, reload]] ))
        if Options['debug']:
            print >> sys.stderr, 'DEBUG: lockSessionConnections', 'DONE' 
开发者ID:mitotic,项目:slidoc,完整代码来源:sdserver.py


示例37: open

# 需要导入模块: from tornado.options import options [as 别名]
# 或者: from tornado.options.options import debug [as 别名]
def open(self, path=''):
        self.clientVersion = self.get_argument('version','')
        self.msgTime = time.time()
        self.locked = ''
        self.timeout = None
        self.userId = self.get_id_from_cookie()
        self.pathUser = (path, self.userId)
        self.sessionVersion = self.getSessionVersion(self.get_path_base(path))
        self.userRole = self.get_id_from_cookie(role=True, for_site=Options['site_name'])
        connectionList = self._connections[self.pathUser[0]][self.pathUser[1]]
        if not connectionList:
            connectionList.sd_role = self.userRole
        connectionList.append(self)
        self.pluginInstances = {}
        self.awaitBinary = None

        if Options['debug']:
            print >> sys.stderr, "DEBUG: WSopen", sliauth.iso_date(nosubsec=True), self.pathUser, self.clientVersion
        if not self.userId:
            self.close()

        self.eventBuffer = []
        self.eventFlusher = PeriodicCallback(self.flushEventBuffer, EVENT_BUFFER_SEC*1000)
        self.eventFlusher.start()

        self.write_message_safe(json.dumps([0, 'session_setup', [self.sessionVersion] ])) 
开发者ID:mitotic,项目:slidoc,完整代码来源:sdserver.py


示例38: write_message_safe

# 需要导入模块: from tornado.options import options [as 别名]
# 或者: from tornado.options.options import debug [as 别名]
def write_message_safe(self, msg):
        try:
            self.write_message(msg)
        except Exception, excp:
            if Options['debug']:
                print >> sys.stderr, 'DEBUG: write_message_safe: Error in write_message', self.pathUser, self.locked, str(excp) 
开发者ID:mitotic,项目:slidoc,完整代码来源:sdserver.py


示例39: get_absolute_path

# 需要导入模块: from tornado.options import options [as 别名]
# 或者: from tornado.options.options import debug [as 别名]
def get_absolute_path(self, *args, **kwargs):
        abs_path = super(AuthStaticFileHandler, self).get_absolute_path(*args, **kwargs)
        if '?' in abs_path:
            # Treat ? in path as the query delimiter (but not in get_current_user)
            abs_path, _, self.abs_query = abs_path.partition('?')
            if Options['debug']:
                print >>sys.stderr, "AuthStaticFileHandler.get_absolute_path", abs_path, self.abs_query
        return abs_path 
开发者ID:mitotic,项目:slidoc,完整代码来源:sdserver.py


示例40: sendPrivateRequest

# 需要导入模块: from tornado.options import options [as 别名]
# 或者: from tornado.options.options import debug [as 别名]
def sendPrivateRequest(relay_address, path='/', proto='http'):
    if Options['debug']:
        print >> sys.stderr, 'DEBUG: sdserver.sendPrivateRequest:', relay_address, path
    if isinstance(relay_address, tuple):
        http_client = tornado.httpclient.HTTPClient()
        url = proto+('://%s:%d' % relay_address)
        return http_client.fetch(url+path, request_timeout=300)
    else:
        import multiproxy
        sock = multiproxy.create_unix_client_socket(relay_address)
        retval = sock.sendall('''GET %s HTTP/1.1\r\nHost: localhost\r\n\r\n''' % path)
        sock.close()
        return retval 
开发者ID:mitotic,项目:slidoc,完整代码来源:sdserver.py


示例41: shutdown_server

# 需要导入模块: from tornado.options import options [as 别名]
# 或者: from tornado.options.options import debug [as 别名]
def shutdown_server():
    if Global.http_server:
        Global.http_server.stop()
        Global.http_server = None
    if Global.server_socket:
        try:
            Global.server_socket.close()
        except Exception, excp:
            print >> sys.stderr, 'sdserver.shutdown_server: ERROR', sexcp
            
    if Options['debug']:
        print >> sys.stderr, 'sdserver.shutdown_server:' 
开发者ID:mitotic,项目:slidoc,完整代码来源:sdserver.py


示例42: initialize

# 需要导入模块: from tornado.options import options [as 别名]
# 或者: from tornado.options.options import debug [as 别名]
def initialize(self, debug):
        if debug:
            self.write_error = self.write_debugger_error 
开发者ID:dongweiming,项目:web_develop,完整代码来源:app_tornado.py


示例43: create_application

# 需要导入模块: from tornado.options import options [as 别名]
# 或者: from tornado.options.options import debug [as 别名]
def create_application(debug=False):
    handlers = [
        ('/error/', BadHandler, {'debug': debug}),
    ]
    if debug:
        return DebugApplication(handlers, debug=True)
    return Application(handlers, debug=debug) 
开发者ID:dongweiming,项目:web_develop,完整代码来源:app_tornado.py


示例44: main

# 需要导入模块: from tornado.options import options [as 别名]
# 或者: from tornado.options.options import debug [as 别名]
def main():
    define('debug', default=False, type=bool, help='Run in debug mode.')
    define('port', default=9000, type=int, help='Port on which to listen.')
    parse_command_line()

    logger = logging.getLogger()
    port = options.port
    application = create_application(debug=options.debug)
    logger.info('Running tornado on port {}.'.format(port))
    application.listen(port)
    tornado.ioloop.IOLoop.instance().start() 
开发者ID:dongweiming,项目:web_develop,完整代码来源:app_tornado.py



注:本文示例均筛选自Github等开源项目,代码版权请参考对应项目的License;未经允许,请勿转载。