import logging import requests import textwrap class HttpFormatter(logging.Formatter): def _formatHeaders(self, d): return '\n'.join(f'{k}: {v}' for k, v in d.items()) def formatMessage(self, record): result = super().formatMessage(record) if record.name == 'httplogger': result += textwrap.dedent(''' ---------------- request ---------------- {req.method} {req.url} {reqhdrs} {req.body} ---------------- response ---------------- {res.status_code} {res.reason} {res.url} {reshdrs} {res.text} ''').format( req=record.req, res=record.res, reqhdrs=self._formatHeaders(record.req.headers), reshdrs=self._formatHeaders(record.res.headers), ) return result formatter = HttpFormatter('{asctime} {levelname} {name} {message}', style='{') handler = logging.StreamHandler() handler.setFormatter(formatter) logging.basicConfig(level=logging.DEBUG, handlers=[handler]) logger = logging.getLogger('httplogger') def logRoundtrip(response, *args, **kwargs): extra = {'req': response.request, 'res': response} logger.debug('HTTP roundtrip', extra=extra) session = requests.Session() session.hooks['response'].append(logRoundtrip) session.get('http://secariolabs.com') # ya_imported_task_response = response.json() # if task.get('parent'): # parent_task_gid = task['parent']['gid'] # if parent_task_gid in ya_imported_task_response: # parent_task_id = ya_imported_task_response[parent_task_gid]['id'] # logger.debug(f'В задаче {task["summary"]} есть связка "parent"', ensure_ascii=False) # update_parent_task( # base_url, # headers, # ya_imported_task_response['id'], # parent_task_id, # ) # def update_parent_task(base_url, headers, task_id, parent_task_id): # """ Обновление данных родительской задачи в ЯндексТрекере""" # data = { # 'parent': parent_task_id # } # payload = json.dumps(data) # update_url = f"{base_url}/{task_id}" # response = requests.post(update_url, headers=headers, data=payload) # result = json.loads(response.text) # logger.warning(json.dumps(result, ensure_ascii=False)) # if response.status_code == 200: # logger.info('Данные о связи с задачей "parent" успешно обновлены') # else: # logger.error( # 'Ошибка при обновлении данных о связи с задачей "parent": %s', # response.content, # )