我们从Python开源项目中,提取了以下3个代码示例,用于说明如何使用bottle.hook()。
def test_hooks(self): @bottle.route() def test(): return bottle.request.environ.get('hooktest','nohooks') @bottle.hook('before_request') def hook(): bottle.request.environ['hooktest'] = 'before' @bottle.hook('after_request') def hook(): bottle.response.headers['X-Hook'] = 'after' self.assertBody('before', '/test') self.assertHeader('X-Hook', 'after', '/test')
def test_module_shortcuts(self): for name in '''route get post put delete error mount hook install uninstall'''.split(): short = getattr(bottle, name) original = getattr(bottle.app(), name) self.assertWraps(short, original)
def __init__(self, bot, **kwargs): super().__init__(**kwargs) self.bot = bot self.file = os.path.join('data', 'ricedb.json') datadir = os.path.dirname(self.file) try: with open(self.file, 'r') as fd: self.update(json.load(fd)) except FileNotFoundError: # Database file itself doesn't need to exist on first run, it will be created on first write. if not os.path.exists(datadir): os.mkdir(datadir) self.bot.log.debug('Created {0}/ directory'.format(datadir)) try: self.config = self.bot.config[__name__] if not self.config.get('enable_http_server'): return host, port = self.config['http_host'], int(self.config['http_port']) except KeyError: host, port = '127.0.0.1', 8080 bottle.hook('before_request')(self.__strip_path) bottle.route('/')(self.__http_index) bottle.route('/<user>')(self.__http_index) bottle.route('/<user>/<key>')(self.__http_index) bottle_thread = threading.Thread( target=bottle.run, kwargs={'quiet': True, 'host': host, 'port': port}, name='{0} HTTP server'.format(__name__), daemon=True ) bottle_thread.start() self.bot.log.info('{0} started on http://{1}:{2}'.format(bottle_thread.name, host, port))