Jeremy Satterfield
Coding, Brewing and Tulsa Life

Viewing posts tagged hacks

Unit Testing Recursion in Python

Today I finally figured out the solution to a problem I've been trying to solve for a while. It's kind of hacky and maybe a bad idea, but now I know it's possible. The problem has always been that I'd like to test that a function recurses, but not needing it to actually have the recursion execute within to test. Just a unit test to assert that recursion is happening. After a little thought about how Python stores references I came up with this.

Class-based Celery Tasks

Update 2017-11-02: Celery 4 now adivises against inheriting from Task unless you are extending common functionality. However you can still get similar functionality by creating a new class and calling is from inside a decorated function task.

Abusing Django Rest Framework Part 4: Object-level field exclusion

Similar to the object-level readonly field from my previous post, there are some cases where we want to exclude certain fields based on what object the user is trying to access. You could overwrite the views get_serializer method to use a different serializer based on their access, but if nesting serializers is a possiblility this get messy, somewhere in the neighborhood of O(n2). Another option is to modify a serializers to_native method.

Abusing Django Rest Framework Part 3: Object-level read-only fields

DRF has tools to control access in a few ways. Serializers make it easy to select what fields can be accessed and whether or not they are read-only. Permissions are great for restricting access to objects at all or even making certain objects read-only. But there are also cases where you might only want to allow access to a field on a specific object but leave that field restricted on other objects, or vice-versa.

Abusing Django Rest Framework Part 2: Non-rate-based Throttling

Anyone running an API that can be reached by the outside world should most definitely be concerned that someone might pummel their server by making a massive amount of requests to that one endpoint that requires a bunch of on-the-fly calculations. Enter Django Rest Framework's throttling. It allows you to easily configure the framework to stop allowing requests from a user once they've made so many requests in a period of time. Whether you're concerned about requests over a sustained period of time or in short bursts, rate limiting with throttles will handle it.