-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathapi.py
64 lines (47 loc) · 1.81 KB
/
api.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
"""Affiliate tracking logic"""
from affiliate.constants import AFFILIATE_QS_PARAM
from affiliate.models import Affiliate
from mitxpro.utils import first_or_none
def get_affiliate_code_from_qstring(request):
"""
Gets the affiliate code from the querystring if one exists
Args:
request (django.http.request.HttpRequest): A request
Returns:
Optional[str]: The affiliate code (or None)
"""
return request.GET.get(AFFILIATE_QS_PARAM) if request.method == "GET" else None
def get_affiliate_code_from_request(request):
"""
Helper method that gets the affiliate code from a request object if it exists
Args:
request (django.http.request.HttpRequest): A request
Returns:
Optional[str]: The affiliate code (or None)
"""
return getattr(request, "affiliate_code", None)
def get_affiliate_id_from_code(affiliate_code):
"""
Helper method that fetches the Affiliate id from the database that matches the affiliate code
Args:
affiliate_code (str): The affiliate code
Returns:
Optional[Affiliate]: The id of the Affiliate that matches the given code (if it exists)
"""
return first_or_none(
Affiliate.objects.filter(code=affiliate_code).values_list("id", flat=True)
)
def get_affiliate_id_from_request(request):
"""
Helper method that fetches the Affiliate id from the database that matches the affiliate code from the request
Args:
request (django.http.request.HttpRequest): A request
Returns:
Optional[Affiliate]: The Affiliate object that matches the affiliate code in the request (or None)
"""
affiliate_code = get_affiliate_code_from_request(request)
return (
get_affiliate_id_from_code(affiliate_code)
if affiliate_code is not None
else None
)