in opbeans/views.py [0:0]
def maybe_dt(view_func):
"""
Either calls the view, or randomly forwards the request to another opbeans service
"""
other_services = [s for s in os.environ.get("OPBEANS_SERVICES", "").split(",") if s and "opbeans-python" not in s]
if other_services:
logger.info("Registered Opbeans Services: {}".format(", ".join(other_services)))
else:
logger.info("dt_ping_pong_disabled", reason="no_services_discovered")
try:
probability = float(os.environ.get("OPBEANS_DT_PROBABILITY", 0.5))
except ValueError:
probability = 0.5
def wrapped_view(request, *args, **kwargs):
r = random.random()
logger.info("dt_ping_pong_dice_throw", random_val=r, probability=probability, passed=bool(r < probability))
if request.method == "GET" and other_services and r < probability:
other_service = random.choice(other_services)
if not other_service.startswith("http://"):
other_service = "http://{}:3000".format(other_service)
url = other_service + request.get_full_path()
logger.info("dt_ping_pong_proxy", url=url)
try:
other_response = requests.get(url, timeout=15)
except requests.exceptions.Timeout:
logger.error("dt_ping_pong_timeout", service=other_service)
raise
except Exception:
logger.error("dt_ping_pong_connection_failed", service=other_service)
raise
try:
content_type = other_response.headers['content-type']
except KeyError:
logger.debug("dt_ping_pong_missing_content_type", service=other_service)
content_type = "text/plain"
return HttpResponse(other_response.content, status=other_response.status_code, content_type=content_type)
return view_func(request, *args, **kwargs)
return wraps(view_func)(wrapped_view)