Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: reworked API #624

Merged
merged 3 commits into from
Jul 3, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -106,7 +106,8 @@ def test_stamp_get(
assert body["stamps"][0]["provider"] == "Google"


def test_weights_get():
def test_weights_get(scorer_community_with_binary_scorer):
settings.CERAMIC_CACHE_SCORER_ID = scorer_community_with_binary_scorer.pk
event = {
"isBase64Encoded": False,
}
Expand Down
33 changes: 31 additions & 2 deletions api/ceramic_cache/api/v1.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
"""Ceramic Cache API"""

import json
from datetime import timedelta
from typing import Any, Dict, List, Type, Optional
from typing import Any, Dict, List, Optional, Type


import api_logging as logging
import tos.api
Expand All @@ -11,6 +13,7 @@
from django.conf import settings
from django.contrib.auth import get_user_model
from django.contrib.auth.models import AbstractUser
from django.core.cache import cache
from django.http import HttpRequest
from django.shortcuts import get_object_or_404
from ninja import Router
Expand All @@ -22,6 +25,9 @@
# from ninja_jwt.schema import RefreshToken
from ninja_jwt.settings import api_settings
from ninja_jwt.tokens import RefreshToken, Token, TokenError

import tos.api
import tos.schema
from registry.api.v1 import (
DetailedScoreResponse,
ErrorMessageResponse,
Expand Down Expand Up @@ -361,13 +367,36 @@ def handle_delete_stamps(
)


class InvalidScorerConfiguration(APIException):
status_code = status.HTTP_500_INTERNAL_SERVER_ERROR
default_detail = "Unable to retrieve configured scorer!"


@router.get("weights", response=Dict[str, str])
def get_scorer_weights(request):
return handle_get_scorer_weights()


def handle_get_scorer_weights() -> Dict[str, str]:
return settings.GITCOIN_PASSPORT_WEIGHTS
cache_key = f"ceramic_cache_scorer_weights_{settings.CERAMIC_CACHE_SCORER_ID}"
weights = cache.get(cache_key)
if weights:
try:
return json.loads(weights)
except Exception:
log.error("Failed to parse weights from cache!", exc_info=True)

try:
community = Community.objects.get(id=settings.CERAMIC_CACHE_SCORER_ID)
weights = community.get_scorer().weights
# Cache the value for 1 minute
cache.set(cache_key, json.dumps(weights), 1 * 60)
return weights

except Exception:
msg = f"Unable to retrieve configured scorer! settings.CERAMIC_CACHE_SCORER_ID={settings.CERAMIC_CACHE_SCORER_ID}"
log.error(msg, exc_info=True)
raise InvalidScorerConfiguration(msg)


@router.get("stamp", response=GetStampResponse)
Expand Down
38 changes: 38 additions & 0 deletions api/ceramic_cache/test/test_weights.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
from account.models import Community
from scorer_weighted.models import Scorer, BinaryWeightedScorer
from django.test import Client
from django.conf import settings
import pytest

pytestmark = pytest.mark.django_db # noqa: F821

client = Client()


class TestGetWeights:
base_url = "/ceramic-cache"

def test_get_weights(
self,
scorer_account,
):
scorer_weights = {"provider-1": "0.5", "provider-2": "0.5"}
scorer = BinaryWeightedScorer.objects.create(
type=Scorer.Type.WEIGHTED_BINARY, weights=scorer_weights
)

community = Community.objects.create(
name="Community 1",
description="Community 1 - testing",
account=scorer_account,
scorer=scorer,
)

settings.CERAMIC_CACHE_SCORER_ID = community.pk
response = client.get(
f"{self.base_url}/weights",
)

returned_weights = response.json()
assert response.status_code == 200
assert scorer_weights == returned_weights
Loading