def wrapper(*args, **kwargs): result = None exception = False try: result = func(*args, **kwargs) if isinstance(result, basestring): status_code = 200 else: status_code = result[1] result = result[0] except Exception: exception = True # A task can fail with an exception or an error status. if exception or not (200 <= status_code <= 299): failure_count = int(request.headers.get('X-AppEngine-TaskExecutionCount', 0)) + 1 if failure_count >= threshold: logging.error('Task has failed {} time(s)'.format(failure_count)) if exception: raise return result, status_code
def authorization_request() -> str: """ Register your ESP in cloud. It takes password and login from aws_config.json :return: JSON Web Token """ global cfg logging.debug("Authorization request function") headers = DEFAULT_JSON_HEADER url = cfg.api_url + API_AUTHORIZATION_URL body = {} body['is_removed'] = True body['created_at'] = 0 body['username'] = cfg.api_login body['password'] = cfg.api_password logging.debug('LOGIN: {}, password: {}'.format(cfg.api_login, cfg.api_password)) body = ujson.dumps(body) try: response = urequests.post(url, data=body, headers=headers) except IndexError as e: logging.info("No internet connection: {}".format(e)) return "" except Exception as e: logging.info("Failed to authorize in API {}".format(e)) return "" if response.status_code != '200' and response.status_code != 200: logging.error(response.text) return "" response_dict = response.json() jwt_token = response_dict.get("data") return jwt_token
def get(self, url): response = requests.get(url, auth=(self.user, self.password)) if response.status_code == 401: error('unauthorized access') exit(1) return response.text
def main(): """ CLI entry point. """ browser = None proc_cnt = 0 try: browser = conf_browser() total_cnt = len(config.PAGE_CHECKS) checks_start = datetime.now() print('Starting checks: {}'.format( checks_start.strftime("%Y-%m-%d %H:%M:%S")), flush=True) for page in config.PAGE_CHECKS: url = page['url'] fqdn = tldextract.extract(url).fqdn if proc_cnt > 0: # Back to previous line. sys.stdout.write("\033[F") # Clear line. sys.stdout.write("\033[K") print('{} - ({}/{}) > {}'.format(fqdn, proc_cnt, total_cnt, url.partition(fqdn)[2]), flush=True) process_url(browser, page) proc_cnt += 1 write_reports() checks_complete = datetime.now() duration = checks_complete - checks_start minutes, seconds = divmod(duration.seconds, 60) print('Completed: {} - {}.{} minutes.'.format( checks_complete.strftime("%Y-%m-%d %H:%M:%S"), minutes, seconds), flush=True) print("All checks are done. Please review /var for results", flush=True) except KeyboardInterrupt: pass except Exception as ex: logging.error('Exception: %s', ex) traceback.print_exc() finally: if browser: browser.quit()
def wrapper(*args, **kwargs): missing_params = [param for param in params if param not in request.args] if len(missing_params) > 0: message = 'Missing params: {}'.format(', '.join(missing_params)) # Only respond with an error if this isn't an App Engine task. Tasks will attempt to retry in the event # they fail, but this failure is not recoverable, so respond successfully after logging. if 'X-AppEngine-TaskName' not in request.headers: logging.info(message) return error_response(400, message) else: logging.error(message) return '', 200 return fn(*args, **kwargs)
def crash(msg): error(msg) exit(1)
fn() newDirectionX, newDirectionY = self.car.direction res = '%s: %s -> %s<br\>%s: %s -> %s' % ('Move', directionY, newDirectionY, 'Turn', directionX, newDirectionX) self.add_header('Content-Type', 'text/html') return self.write(str(res)) def make_app(): return tornado.web.Application([ (r"/.*", MainHandler), ]) if __name__ == "__main__": Signal.default().setup() try: app = make_app() port = 80 if inPi else 8080 app.listen(port) logger.info('started server on %s...', port) tornado.ioloop.IOLoop.current().start() except Exception as ex: logger.error('server error: %s', ex) finally: Signal.default().cleanup()