python: Normalize quotes with Black.

Signed-off-by: Anders Kaseorg <anders@zulip.com>
This commit is contained in:
Anders Kaseorg
2021-02-11 23:20:45 -08:00
committed by Tim Abbott
parent 11741543da
commit 6e4c3e41dc
989 changed files with 32792 additions and 32792 deletions

View File

@@ -37,7 +37,7 @@ class _RateLimitFilter:
should_reset_handling_exception = False
def can_use_remote_cache(self) -> Tuple[bool, bool]:
if getattr(self.handling_exception, 'value', False):
if getattr(self.handling_exception, "value", False):
# If we're processing an exception that occurred
# while handling an exception, this almost
# certainly was because interacting with the
@@ -56,8 +56,8 @@ class _RateLimitFilter:
# that this is the main exception handler thread.
try:
self.handling_exception.value = True
cache.set('RLF_TEST_KEY', 1, 1)
return cache.get('RLF_TEST_KEY') == 1, True
cache.set("RLF_TEST_KEY", 1, 1)
return cache.get("RLF_TEST_KEY") == 1, True
except Exception:
return False, True
@@ -72,13 +72,13 @@ class _RateLimitFilter:
try:
# Track duplicate errors
duplicate = False
rate = getattr(settings, f'{self.__class__.__name__.upper()}_LIMIT', 600) # seconds
rate = getattr(settings, f"{self.__class__.__name__.upper()}_LIMIT", 600) # seconds
if rate > 0:
(use_cache, should_reset_handling_exception) = self.can_use_remote_cache()
if use_cache:
if record.exc_info is not None:
tb = '\n'.join(traceback.format_exception(*record.exc_info))
tb = "\n".join(traceback.format_exception(*record.exc_info))
else:
tb = str(record)
key = self.__class__.__name__.upper() + hashlib.sha1(tb.encode()).hexdigest()
@@ -126,7 +126,7 @@ def skip_200_and_304(record: logging.LogRecord) -> bool:
# Apparently, `status_code` is added by Django and is not an actual
# attribute of LogRecord; as a result, mypy throws an error if we
# access the `status_code` attribute directly.
if getattr(record, 'status_code', None) in [200, 304]:
if getattr(record, "status_code", None) in [200, 304]:
return False
return True
@@ -136,7 +136,7 @@ def skip_site_packages_logs(record: logging.LogRecord) -> bool:
# This skips the log records that are generated from libraries
# installed in site packages.
# Workaround for https://code.djangoproject.com/ticket/26886
if 'site-packages' in record.pathname:
if "site-packages" in record.pathname:
return False
return True
@@ -154,15 +154,15 @@ def find_log_caller_module(record: logging.LogRecord) -> Optional[str]:
f = logging.currentframe()
while True:
if f.f_code.co_filename == record.pathname:
return f.f_globals.get('__name__')
return f.f_globals.get("__name__")
if f.f_back is None:
return None
f = f.f_back
logger_nicknames = {
'root': '', # This one is more like undoing a nickname.
'zulip.requests': 'zr', # Super common.
"root": "", # This one is more like undoing a nickname.
"zulip.requests": "zr", # Super common.
}
@@ -175,25 +175,25 @@ def find_log_origin(record: logging.LogRecord) -> str:
# Abbreviate a bit.
pass
else:
logger_name = '{}/{}'.format(logger_name, module_name or '?')
logger_name = "{}/{}".format(logger_name, module_name or "?")
if settings.RUNNING_INSIDE_TORNADO:
# In multi-sharded Tornado, it's often valuable to have which shard is
# responsible for the request in the logs.
from zerver.tornado.ioloop_logging import logging_data
shard = logging_data.get('port', 'unknown')
shard = logging_data.get("port", "unknown")
logger_name = f"{logger_name}:{shard}"
return logger_name
log_level_abbrevs = {
'DEBUG': 'DEBG',
'INFO': 'INFO',
'WARNING': 'WARN',
'ERROR': 'ERR',
'CRITICAL': 'CRIT',
"DEBUG": "DEBG",
"INFO": "INFO",
"WARNING": "WARN",
"ERROR": "ERR",
"CRITICAL": "CRIT",
}
@@ -205,25 +205,25 @@ def abbrev_log_levelname(levelname: str) -> str:
class ZulipFormatter(logging.Formatter):
# Used in the base implementation. Default uses `,`.
default_msec_format = '%s.%03d'
default_msec_format = "%s.%03d"
def __init__(self) -> None:
super().__init__(fmt=self._compute_fmt())
def _compute_fmt(self) -> str:
pieces = ['%(asctime)s', '%(zulip_level_abbrev)-4s']
pieces = ["%(asctime)s", "%(zulip_level_abbrev)-4s"]
if settings.LOGGING_SHOW_PID:
pieces.append('pid:%(process)d')
pieces.extend(['[%(zulip_origin)s]', '%(message)s'])
return ' '.join(pieces)
pieces.append("pid:%(process)d")
pieces.extend(["[%(zulip_origin)s]", "%(message)s"])
return " ".join(pieces)
def format(self, record: logging.LogRecord) -> str:
if not getattr(record, 'zulip_decorated', False):
if not getattr(record, "zulip_decorated", False):
# The `setattr` calls put this logic explicitly outside the bounds of the
# type system; otherwise mypy would complain LogRecord lacks these attributes.
setattr(record, 'zulip_level_abbrev', abbrev_log_levelname(record.levelname))
setattr(record, 'zulip_origin', find_log_origin(record))
setattr(record, 'zulip_decorated', True)
setattr(record, "zulip_level_abbrev", abbrev_log_levelname(record.levelname))
setattr(record, "zulip_origin", find_log_origin(record))
setattr(record, "zulip_decorated", True)
return super().format(record)
@@ -248,18 +248,18 @@ class ZulipWebhookFormatter(ZulipFormatter):
request = get_current_request()
if not request:
setattr(record, 'user', None)
setattr(record, 'client', None)
setattr(record, 'url', None)
setattr(record, 'content_type', None)
setattr(record, 'custom_headers', None)
setattr(record, 'payload', None)
setattr(record, "user", None)
setattr(record, "client", None)
setattr(record, "url", None)
setattr(record, "content_type", None)
setattr(record, "custom_headers", None)
setattr(record, "payload", None)
return super().format(record)
if request.content_type == 'application/json':
if request.content_type == "application/json":
payload = request.body
else:
payload = request.POST.get('payload')
payload = request.POST.get("payload")
try:
payload = orjson.dumps(orjson.loads(payload), option=orjson.OPT_INDENT_2).decode()
@@ -270,19 +270,19 @@ class ZulipWebhookFormatter(ZulipFormatter):
header_text = ""
for header in request.META.keys():
if header.lower().startswith('http_x'):
if header.lower().startswith("http_x"):
header_text += custom_header_template.format(
header=header, value=request.META[header]
)
header_message = header_text if header_text else None
setattr(record, 'user', f"{request.user.delivery_email} ({request.user.realm.string_id})")
setattr(record, 'client', request.client.name)
setattr(record, 'url', request.META.get('PATH_INFO', None))
setattr(record, 'content_type', request.content_type)
setattr(record, 'custom_headers', header_message)
setattr(record, 'payload', payload)
setattr(record, "user", f"{request.user.delivery_email} ({request.user.realm.string_id})")
setattr(record, "client", request.client.name)
setattr(record, "url", request.META.get("PATH_INFO", None))
setattr(record, "content_type", request.content_type)
setattr(record, "custom_headers", header_message)
setattr(record, "payload", payload)
return super().format(record)