Python cherrypy.log() Examples
The following are 30
code examples of cherrypy.log().
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
cherrypy
, or try the search function
.
Example #1
Source File: cptools.py From opsbro with MIT License | 6 votes |
def log_hooks(debug=False): """Write request.hooks to the cherrypy error log.""" request = cherrypy.serving.request msg = [] # Sort by the standard points if possible. from cherrypy import _cprequest points = _cprequest.hookpoints for k in request.hooks.keys(): if k not in points: points.append(k) for k in points: msg.append(" %s:" % k) v = request.hooks.get(k, []) v.sort() for h in v: msg.append(" %r" % h) cherrypy.log('\nRequest Hooks for ' + cherrypy.url() + ':\n' + '\n'.join(msg), "HTTP")
Example #2
Source File: api_service.py From sql_python_deep_learning with MIT License | 6 votes |
def run_server(): # Enable WSGI access logging via Paste app_logged = TransLogger(app) # Mount the WSGI callable object (app) on the root directory cherrypy.tree.graft(app_logged, '/') # Set the configuration of the web server cherrypy.config.update({ 'engine.autoreload_on': True, 'log.screen': True, 'log.error_file': "cherrypy.log", 'server.socket_port': 5000, 'server.socket_host': '0.0.0.0', 'server.thread_pool': 50, # 10 is default }) # Start the CherryPy WSGI web server cherrypy.engine.start() cherrypy.engine.block() # Connection
Example #3
Source File: sessions.py From cherrypy with BSD 3-Clause "New" or "Revised" License | 6 votes |
def acquire_lock(self, path=None): """Acquire an exclusive lock on the currently-loaded session data.""" if path is None: path = self._get_file_path() path += self.LOCK_SUFFIX checker = locking.LockChecker(self.id, self.lock_timeout) while not checker.expired(): try: self.lock = zc.lockfile.LockFile(path) except zc.lockfile.LockError: time.sleep(0.1) else: break self.locked = True if self.debug: cherrypy.log('Lock acquired.', 'TOOLS.SESSIONS')
Example #4
Source File: sessions.py From cherrypy with BSD 3-Clause "New" or "Revised" License | 6 votes |
def save(self): """Save session data.""" try: # If session data has never been loaded then it's never been # accessed: no need to save it if self.loaded: t = datetime.timedelta(seconds=self.timeout * 60) expiration_time = self.now() + t if self.debug: cherrypy.log('Saving session %r with expiry %s' % (self.id, expiration_time), 'TOOLS.SESSIONS') self._save(expiration_time) else: if self.debug: cherrypy.log( 'Skipping save of session %r (no session loaded).' % self.id, 'TOOLS.SESSIONS') finally: if self.locked: # Always release the lock if the user didn't release it self.release_lock() if self.debug: cherrypy.log('Lock released after save.', 'TOOLS.SESSIONS')
Example #5
Source File: static.py From cherrypy with BSD 3-Clause "New" or "Revised" License | 6 votes |
def _attempt(filename, content_types, debug=False): if debug: cherrypy.log('Attempting %r (content_types %r)' % (filename, content_types), 'TOOLS.STATICDIR') try: # you can set the content types for a # complete directory per extension content_type = None if content_types: r, ext = os.path.splitext(filename) content_type = content_types.get(ext[1:], None) serve_file(filename, content_type=content_type, debug=debug) return True except cherrypy.NotFound: # If we didn't find the static file, continue handling the # request. We might find a dynamic handler instead. if debug: cherrypy.log('NotFound', 'TOOLS.STATICFILE') return False
Example #6
Source File: cptools.py From cherrypy with BSD 3-Clause "New" or "Revised" License | 6 votes |
def flatten(debug=False): """Wrap response.body in a generator that recursively iterates over body. This allows cherrypy.response.body to consist of 'nested generators'; that is, a set of generators that yield generators. """ def flattener(input): numchunks = 0 for x in input: if not is_iterator(x): numchunks += 1 yield x else: for y in flattener(x): numchunks += 1 yield y if debug: cherrypy.log('Flattened %d chunks' % numchunks, 'TOOLS.FLATTEN') response = cherrypy.serving.response response.body = flattener(response.body)
Example #7
Source File: cptools.py From cherrypy with BSD 3-Clause "New" or "Revised" License | 6 votes |
def trailing_slash(missing=True, extra=False, status=None, debug=False): """Redirect if path_info has (missing|extra) trailing slash.""" request = cherrypy.serving.request pi = request.path_info if debug: cherrypy.log('is_index: %r, missing: %r, extra: %r, path_info: %r' % (request.is_index, missing, extra, pi), 'TOOLS.TRAILING_SLASH') if request.is_index is True: if missing: if not pi.endswith('/'): new_url = cherrypy.url(pi + '/', request.query_string) raise cherrypy.HTTPRedirect(new_url, status=status or 301) elif request.is_index is False: if extra: # If pi == '/', don't redirect to ''! if pi.endswith('/') and pi != '/': new_url = cherrypy.url(pi[:-1], request.query_string) raise cherrypy.HTTPRedirect(new_url, status=status or 301)
Example #8
Source File: cptools.py From cherrypy with BSD 3-Clause "New" or "Revised" License | 6 votes |
def log_hooks(debug=False): """Write request.hooks to the cherrypy error log.""" request = cherrypy.serving.request msg = [] # Sort by the standard points if possible. from cherrypy import _cprequest points = _cprequest.hookpoints for k in request.hooks.keys(): if k not in points: points.append(k) for k in points: msg.append(' %s:' % k) v = request.hooks.get(k, []) v.sort() for h in v: msg.append(' %r' % h) cherrypy.log('\nRequest Hooks for ' + cherrypy.url() + ':\n' + '\n'.join(msg), 'HTTP')
Example #9
Source File: base_webpage.py From SecPi with GNU General Public License v3.0 | 6 votes |
def update(self): if(hasattr(cherrypy.request, 'json')): data = cherrypy.request.json id = data['id'] # check for valid id if(id and id > 0): if(data and len(data)>0): cherrypy.log("update something %s"%data) obj = self.db.query(self.baseclass).get(id) for k, v in data.iteritems(): if(not k == "id"): # and v is not None --> can be null!? setattr(obj, k, utils.str_to_value(v)) self.db.commit() return {'status': 'success', 'message': "Updated object with id %i"%obj.id} else: return {'status':'error', 'message': "Invalid ID!" } return {'status': 'error', 'message': 'No data recieved!'}
Example #10
Source File: _cplogging.py From cherrypy with BSD 3-Clause "New" or "Revised" License | 6 votes |
def error(self, msg='', context='', severity=logging.INFO, traceback=False): """Write the given ``msg`` to the error log. This is not just for errors! Applications may call this at any time to log application-specific information. If ``traceback`` is True, the traceback of the current exception (if any) will be appended to ``msg``. """ exc_info = None if traceback: exc_info = _cperror._exc_info() self.error_log.log( severity, ' '.join((self.time(), context, msg)), exc_info=exc_info, )
Example #11
Source File: main.py From SecPi with GNU General Public License v3.0 | 6 votes |
def __init__(self): cherrypy.log("Initializing Webserver") cherrypy.config.update({'request.error_response': self.handle_error}) cherrypy.config.update({'error_page.404': self.error_404}) cherrypy.config.update({'error_page.401': self.error_401}) self.sensors = SensorsPage() self.zones = ZonesPage() self.setups = SetupsPage() self.alarms = AlarmsPage() self.workers = WorkersPage() self.actions = ActionsPage() self.notifiers = NotifiersPage() self.sensorparams = SensorParamsPage() self.actionparams = ActionParamsPage() self.notifierparams = NotifierParamsPage() self.logs = LogEntriesPage() self.setupszones = SetupsZonesPage() self.workersactions = WorkersActionsPage() self.alarmdata = AlarmDataPage() self.connect() cherrypy.log("Finished initialization")
Example #12
Source File: base_webpage.py From SecPi with GNU General Public License v3.0 | 6 votes |
def add(self): if(hasattr(cherrypy.request, 'json')): data = cherrypy.request.json if(data and len(data)>0): cherrypy.log("got something %s"%data) newObj = self.baseclass() for k, v in data.iteritems(): if(not k == "id"): setattr(newObj, k, utils.str_to_value(v)) self.db.add(newObj) self.db.commit() return {'status': 'success','message':"Added new object with id %i"%newObj.id} return {'status': 'error', 'message': 'No data recieved!'}
Example #13
Source File: processpipe.py From blissflixx with GNU General Public License v2.0 | 5 votes |
def start(self, pmsgq): self.pmsgq = pmsgq self._start_next() while True: m = self.msgq.get() idx = self.msgq.get() name = self.procs[idx].name() if m == MSG_PROCESS_READY: cherrypy.log("READY: " + name) args = self.msgq.get() if not self._is_last_proc(idx): self._start_next(args) else: self.started = True elif m == MSG_PROCESS_FINISHED: cherrypy.log("FINISHED: " + name) if self._is_last_proc(idx): self.stop() break elif m == MSG_PROCESS_HALTED: cherrypy.log("HALTED: " + name) self.stop() break
Example #14
Source File: _cptree.py From opsbro with MIT License | 5 votes |
def release_serving(self): """Release the current serving (request and response).""" req = cherrypy.serving.request cherrypy.engine.publish('after_request') try: req.close() except: cherrypy.log(traceback=True, severity=40) cherrypy.serving.clear()
Example #15
Source File: cptools.py From opsbro with MIT License | 5 votes |
def referer(pattern, accept=True, accept_missing=False, error=403, message='Forbidden Referer header.', debug=False): """Raise HTTPError if Referer header does/does not match the given pattern. pattern A regular expression pattern to test against the Referer. accept If True, the Referer must match the pattern; if False, the Referer must NOT match the pattern. accept_missing If True, permit requests with no Referer header. error The HTTP error code to return to the client on failure. message A string to include in the response body on failure. """ try: ref = cherrypy.serving.request.headers['Referer'] match = bool(re.match(pattern, ref)) if debug: cherrypy.log('Referer %r matches %r' % (ref, pattern), 'TOOLS.REFERER') if accept == match: return except KeyError: if debug: cherrypy.log('No Referer header', 'TOOLS.REFERER') if accept_missing: return raise cherrypy.HTTPError(error, message)
Example #16
Source File: cptools.py From opsbro with MIT License | 5 votes |
def ignore_headers(headers=('Range',), debug=False): """Delete request headers whose field names are included in 'headers'. This is a useful tool for working behind certain HTTP servers; for example, Apache duplicates the work that CP does for 'Range' headers, and will doubly-truncate the response. """ request = cherrypy.serving.request for name in headers: if name in request.headers: if debug: cherrypy.log('Ignoring request header %r' % name, 'TOOLS.IGNORE_HEADERS') del request.headers[name]
Example #17
Source File: cptools.py From opsbro with MIT License | 5 votes |
def response_headers(headers=None, debug=False): """Set headers on the response.""" if debug: cherrypy.log('Setting response headers: %s' % repr(headers), 'TOOLS.RESPONSE_HEADERS') for name, value in (headers or []): cherrypy.serving.response.headers[name] = value
Example #18
Source File: cptools.py From opsbro with MIT License | 5 votes |
def allow(methods=None, debug=False): """Raise 405 if request.method not in methods (default ['GET', 'HEAD']). The given methods are case-insensitive, and may be in any order. If only one method is allowed, you may supply a single string; if more than one, supply a list of strings. Regardless of whether the current method is allowed or not, this also emits an 'Allow' response header, containing the given methods. """ if not isinstance(methods, (tuple, list)): methods = [methods] methods = [m.upper() for m in methods if m] if not methods: methods = ['GET', 'HEAD'] elif 'GET' in methods and 'HEAD' not in methods: methods.append('HEAD') cherrypy.response.headers['Allow'] = ', '.join(methods) if cherrypy.request.method not in methods: if debug: cherrypy.log('request.method %r not in methods %r' % (cherrypy.request.method, methods), 'TOOLS.ALLOW') raise cherrypy.HTTPError(405) else: if debug: cherrypy.log('request.method %r in methods %r' % (cherrypy.request.method, methods), 'TOOLS.ALLOW')
Example #19
Source File: __init__.py From blissflixx with GNU General Public License v2.0 | 5 votes |
def _exec(cmd): s = subprocess.check_output(cmd) lines = s.split('\n') for l in lines: if l.strip() != "": cherrypy.log("GIT: " + l)
Example #20
Source File: processpipe.py From blissflixx with GNU General Public License v2.0 | 5 votes |
def _wait(self): # Drain stderr/stdout pipe to stop it filling up and blocking process cpthr = _bgcopypipe(self.proc.stdout, None) retcode = self.proc.wait() self.proc = None #if retcode != 0: # cherrypy.log("Process exited with code: " + str(retcode)) if self.has_error() or self.killing: self.msg_halted() else: self.msg_finished()
Example #21
Source File: _cplogging.py From cherrypy with BSD 3-Clause "New" or "Revised" License | 5 votes |
def _set_wsgi_handler(self, log, enable): h = self._get_builtin_handler(log, 'wsgi') if enable: if not h: h = WSGIErrorHandler() h.setFormatter(logfmt) h._cpbuiltin = 'wsgi' log.addHandler(h) elif h: log.handlers.remove(h)
Example #22
Source File: processpipe.py From blissflixx with GNU General Public License v2.0 | 5 votes |
def _start_next(self, args={}): proc = self.procs[self.next_proc] cherrypy.log("STARTING: " + proc.name()) proc.set_msgq(self.msgq, self.next_proc) self.threads.append(_start_thread(proc.start, args)) self.next_proc = self.next_proc + 1
Example #23
Source File: _cplogging.py From cherrypy with BSD 3-Clause "New" or "Revised" License | 5 votes |
def _add_builtin_file_handler(self, log, fname): h = logging.FileHandler(fname) h.setFormatter(logfmt) h._cpbuiltin = 'file' log.addHandler(h)
Example #24
Source File: player.py From blissflixx with GNU General Public License v2.0 | 5 votes |
def start(self): msgq = self.msgq nextpipe = None while True: m = msgq.get() if m == MSG_PLAYER_PLAY: if self.play_pipe is not None: nextpipe = msgq.get() self._stop() else: self._play(msgq.get()) elif m == MSG_PLAYER_STOP: self._stop() elif m == MSG_PLAYER_PIPE_STOPPED: self.error = msgq.get() self.play_thread.join() cherrypy.log("PIPE STOPPED") if nextpipe is not None: self._play(nextpipe) nextpipe = None else: self.play_pipe = None self.play_thread = None elif m == MSG_PLAYER_QUIT: self._stop() break
Example #25
Source File: mako_template_tool.py From SecPi with GNU General Public License v3.0 | 5 votes |
def bind_lookup(self): # cherrypy.engine.publish('mako.get_lookup', self.lookup) # cherrypy.log("found lookup %s"%self.lookup) cherrypy.request.lookup = self.lookup
Example #26
Source File: rtmpproc.py From blissflixx with GNU General Public License v2.0 | 5 votes |
def _ready(self): while True: line = self._readline() if line.startswith('Starting download at:'): return {'pid':self.proc.pid, 'outfile':OUT_FILE} else: cherrypy.log("RTMPDUMP: " + line)
Example #27
Source File: main.py From SecPi with GNU General Public License v3.0 | 5 votes |
def connect(self, num_tries=3): credentials = pika.PlainCredentials(config.get('rabbitmq')['user'], config.get('rabbitmq')['password']) parameters = pika.ConnectionParameters(credentials=credentials, host=config.get('rabbitmq')['master_ip'], port=5671, ssl=True, socket_timeout=10, ssl_options = { "ca_certs":PROJECT_PATH+"/certs/"+config.get('rabbitmq')['cacert'], "certfile":PROJECT_PATH+"/certs/"+config.get('rabbitmq')['certfile'], "keyfile":PROJECT_PATH+"/certs/"+config.get('rabbitmq')['keyfile'] } ) connected = False while not connected and num_tries > 0: try: cherrypy.log("Trying to connect to rabbitmq service...") self.connection = pika.BlockingConnection(parameters=parameters) self.channel = self.connection.channel() connected = True cherrypy.log("Connection to rabbitmq service established") #except pika.exceptions.AMQPConnectionError as pe: except Exception as e: cherrypy.log("Error connecting to Queue! %s" % e, traceback=True) num_tries-=1 time.sleep(30) if not connected: return False # define exchange self.channel.exchange_declare(exchange=utils.EXCHANGE, exchange_type='direct') # define queues self.channel.queue_declare(queue=utils.QUEUE_ON_OFF) self.channel.queue_bind(exchange=utils.EXCHANGE, queue=utils.QUEUE_ON_OFF) return True
Example #28
Source File: blissflixx.py From blissflixx with GNU General Public License v2.0 | 5 votes |
def access(self): request = cherrypy.serving.request # Ignore all status requests as they do nothing but fill up the log if request.request_line != "GET /api/playr?fn=status HTTP/1.1": return LogManager.access(self)
Example #29
Source File: main.py From SecPi with GNU General Public License v3.0 | 5 votes |
def connection_cleanup(self): try: self.channel.close() self.connection.close() except pika.exceptions.ConnectionClosed: cherrypy.log("Wasn't able to cleanup connection")
Example #30
Source File: main.py From SecPi with GNU General Public License v3.0 | 5 votes |
def activate(self): if(hasattr(cherrypy.request, 'json')): id = cherrypy.request.json['id'] if(id and id > 0): su = self.db.query(objects.Setup).get(int(id)) try: if(hasattr(self, "channel")): su.active_state = True self.db.commit() ooff = { 'active_state': True , 'setup_name': su.name } self.channel.basic_publish(exchange=utils.EXCHANGE, routing_key=utils.QUEUE_ON_OFF, body=json.dumps(ooff)) else: return {'status':'error', 'message': "Error activating %s! No connection to queue server!" % su.name } except pika.exceptions.ConnectionClosed: cherrypy.log("Reconnecting to RabbitMQ Server!") reconnected = self.connect(5) if reconnected: cherrypy.log("Reconnect finished!") su.active_state = True self.db.commit() ooff = { 'active_state': True, 'setup_name': su.name } self.channel.basic_publish(exchange=utils.EXCHANGE, routing_key=utils.QUEUE_ON_OFF, body=json.dumps(ooff)) return {'status': 'success', 'message': "Activated setup %s!" % su.name} else: return {'status':'error', 'message': "Error activating %s! Wasn't able to reconnect!" % su.name } except Exception as e: su.active_state = False self.db.commit() cherrypy.log("Error activating! %s"%str(e), traceback=True) return {'status':'error', 'message': "Error activating! %s" % e } else: return {'status': 'success', 'message': "Activated setup %s!" % su.name} else: return {'status':'error', 'message': "Invalid ID!" } return {'status': 'error', 'message': 'No data recieved!'}