mirror of
https://github.com/barkeser2002/offline-db.git
synced 2026-09-25 03:40:05 +03:00
This commit adds a new `slow_query_logger` function in `core/utils.py` that wraps Django database executions and logs queries taking longer than 100ms. It uses `time.monotonic()` for robust timing. The logger is globally registered in `core/apps.py` via the `connection_created` signal with `weak=False` to ensure all new database connections are properly instrumented. Unit tests have been added to `core/tests/test_slow_query.py` and the development plan checkbox is updated. Co-authored-by: google-labs-jules[bot] <161369871+google-labs-jules[bot]@users.noreply.github.com>
93 lines
2.8 KiB
Python
93 lines
2.8 KiB
Python
import requests
|
|
import random
|
|
import time
|
|
import logging
|
|
from .models import SiteSettings
|
|
from django.core.cache import cache
|
|
from django.http import HttpResponseForbidden
|
|
from functools import wraps
|
|
|
|
logger = logging.getLogger(__name__)
|
|
|
|
def slow_query_logger(execute, sql, params, many, context):
|
|
"""
|
|
Database execute wrapper that logs queries taking longer than 100ms.
|
|
"""
|
|
start = time.monotonic()
|
|
try:
|
|
return execute(sql, params, many, context)
|
|
finally:
|
|
duration = time.monotonic() - start
|
|
if duration >= 0.1:
|
|
logger.warning(
|
|
"Slow query detected (%.3fs): %s",
|
|
duration,
|
|
sql,
|
|
extra={'duration': duration, 'sql': sql}
|
|
)
|
|
|
|
class DeepLTranslator:
|
|
def __init__(self):
|
|
self.settings = SiteSettings.get_solo()
|
|
self.keys = [k.strip() for k in self.settings.deepl_api_keys.split(',') if k.strip()]
|
|
|
|
def translate(self, text, target_lang='TR'):
|
|
if not self.keys:
|
|
# Fallback or error
|
|
return f"[No Keys] {text}"
|
|
|
|
# Rotate keys (Random selection for simplicity, could be round-robin)
|
|
key = random.choice(self.keys)
|
|
|
|
try:
|
|
# DeepL API logic (Free API url for example)
|
|
url = "https://api-free.deepl.com/v2/translate"
|
|
params = {
|
|
"auth_key": key,
|
|
"text": text,
|
|
"target_lang": target_lang
|
|
}
|
|
# response = requests.post(url, data=params) # Commented out to avoid external calls without keys
|
|
# result = response.json()
|
|
# return result['translations'][0]['text']
|
|
|
|
return f"[Translated to {target_lang}] {text}"
|
|
except Exception as e:
|
|
return f"[Error] {text}"
|
|
|
|
def get_client_ip(request):
|
|
x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR')
|
|
if x_forwarded_for:
|
|
ip = x_forwarded_for.split(',')[0].strip()
|
|
else:
|
|
ip = request.META.get('REMOTE_ADDR')
|
|
return ip
|
|
|
|
def rate_limit_ip(limit=5, period=60):
|
|
"""
|
|
Decorator to rate limit views by IP address.
|
|
"""
|
|
def decorator(view_func):
|
|
@wraps(view_func)
|
|
def _wrapped_view(request, *args, **kwargs):
|
|
ip = get_client_ip(request)
|
|
if not ip:
|
|
ip = 'unknown'
|
|
|
|
key = f"ratelimit_{ip}_{view_func.__name__}"
|
|
|
|
try:
|
|
# Returns the new value
|
|
count = cache.incr(key)
|
|
except ValueError:
|
|
# Key didn't exist
|
|
cache.set(key, 1, period)
|
|
count = 1
|
|
|
|
if count > limit:
|
|
return HttpResponseForbidden("Rate limit exceeded")
|
|
|
|
return view_func(request, *args, **kwargs)
|
|
return _wrapped_view
|
|
return decorator
|