Backend Live Coding

Backend Live Coding

Explore backend live coding code snippets and tutorials

Backend Live Coding

Reducing polling load with ETag and conditional requests

Conditional requests with ETag.

python
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
# ======================================================================
# Q: Thousands of players ask every few minutes "has anything changed?". How do
# you reduce the load?
#
# Conditional requests with ETag. The player sends If-None-Match, and if nothing
# has changed I answer 304 with no body. I derive the ETag from a cheap field
# (e.g. the playlist's updated_at or content_version), so I don't need to build
# the whole response to compute it. It can also be kept in Redis so it doesn't
# even hit the database.
# Alternatively, push instead of poll: WebSocket (Django Channels) or MQTT,
# where the server notifies only when there is a change. You usually keep a poll
# with a long interval as a fallback too, because screen connections drop.
# ======================================================================

class PlayerManifestView(APIView):
    authentication_classes = [DeviceTokenAuthentication]

    def get(self, request):
        screen = request.auth.screen
        etag = f'"{screen.playlist_id}-{screen.playlist.content_version}"'
        if request.headers.get('If-None-Match') == etag:
            return Response(status=304)
        data = build_manifest(screen)          # the heavy part
        return Response(data, headers={'ETag': etag, 'Cache-Control': 'private, no-cache'})
Backend Live Coding

Filtering a related field's queryset in a DRF serializer

How do you filter the queryset of a related field in a serializer?

python
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
# ======================================================================
# Q: How do you filter the queryset of a related field in a serializer?
# ======================================================================

class ScreenSerializer(serializers.ModelSerializer):
    playlist = serializers.PrimaryKeyRelatedField(queryset=Playlist.objects.none())

    class Meta:
        model = Screen
        fields = ['id', 'name', 'playlist', 'timezone', 'last_seen']
        read_only_fields = ['last_seen']

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        request = self.context.get('request')
        if request:
            self.fields['playlist'].queryset = Playlist.objects.filter(
                workspace=request.user.workspace)
Backend Live Coding

Multi-tenant SaaS in DRF: scoping every queryset to the workspace

I never trust ids from the client.

python
 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
# ======================================================================
# Q: In a SaaS, each customer (workspace) must see only their own data. How do
# you ensure this in DRF?
#
# I never trust ids from the client. The filtering is done centrally in a mixin,
# so nobody can forget it in a new endpoint. Anything that does not belong to
# the workspace returns 404 (not 403), so its existence is not revealed.
# Watch out for nested fields too: if the serializer accepts playlist_id, the
# queryset of the PrimaryKeyRelatedField must also be filtered by workspace,
# otherwise someone can attach their screen to another customer's playlist
# (BOLA).
# ======================================================================

class WorkspaceScopedMixin:
    """Every queryset and every create is bound to the user's workspace."""
    def get_queryset(self):
        return super().get_queryset().filter(workspace=self.request.user.workspace)

    def perform_create(self, serializer):
        serializer.save(workspace=self.request.user.workspace)

class ScreenViewSet(WorkspaceScopedMixin, viewsets.ModelViewSet):
    queryset = Screen.objects.select_related('playlist')
    serializer_class = ScreenSerializer
    permission_classes = [IsAuthenticated]
Backend Live Coding

Check for balanced brackets in a string using a stack

Stack, O(n).

python
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
# ======================================================================
# Q: Check whether the brackets in a string are balanced.
#
# Stack, O(n).
# ======================================================================

def balanced(s: str) -> bool:
    pairs = {')': '(', ']': '[', '}': '{'}
    stack = []
    for ch in s:
        if ch in '([{':
            stack.append(ch)
        elif ch in pairs:
            if not stack or stack.pop() != pairs[ch]:
                return False
    return not stack
Backend Live Coding

Group orders by customer and find the top 3 products with Counter

The interviewer wants to see that you know the standard library: collections (Counter, defaultdict, deque), itertools (groupby, chain, islice), heapq (nlargest).

python
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
# ======================================================================
# Q: Group orders by customer and find the 3 best-selling products (without a
# database).
#
# The interviewer wants to see that you know the standard library: collections
# (Counter, defaultdict, deque), itertools (groupby, chain, islice), heapq
# (nlargest).
# ======================================================================

from collections import Counter, defaultdict

by_customer = defaultdict(list)
for o in orders:
    by_customer[o['customer_id']].append(o)

sold = Counter()
for o in orders:
    for item in o['items']:
        sold[item['sku']] += item['qty']
top3 = sold.most_common(3)