Skip to content

Instantly share code, notes, and snippets.

View cypreess's full-sized avatar

Kris Dorosz cypreess

View GitHub Profile
from rest_framework.authentication import SessionAuthentication
class CsrfExemptSessionAuthentication(SessionAuthentication):
def enforce_csrf(self, request):
return # To not perform the csrf check previously happening
@cypreess
cypreess / natural_timedelta.py
Last active June 29, 2018 10:38
Formatting negative timedelta in more natural way
import datetime
def timedelta_to_string(timedelta):
total_seconds = timedelta.total_seconds()
if total_seconds < 0:
timedelta_str = '-' + str(datetime.timedelta() - timedelta)
else:
timedelta_str = '+' + str(timedelta)
return timedelta_str
@cypreess
cypreess / import.py
Last active June 29, 2018 09:07
Import specific class in Python
def import_name(name):
components = name.split('.')
mod = __import__(
'.'.join(components[0:-1])
)
for m in components[1:]:
mod = getattr(mod, m)
return mod
from collections import OrderedDict
def deep_search(needles, haystack):
found = {}
if type(needles) != type([]):
needles = [needles]
if type(haystack) == type(OrderedDict()) or type(haystack) == type(dict()):
for needle in needles:
@cypreess
cypreess / disable_migrations
Created June 28, 2018 10:32
Easily disable migratinons when testing in your django project, set `MIGRATION_MODULES = DisableMigrations()`in settings.py
class DisableMigrations(object):
def __contains__(self, item):
return True
def __getitem__(self, item):
return None
@cypreess
cypreess / pprint
Created June 28, 2018 10:41
Pretty printer
def pprint(data, ident=2, start_ident=0, ident_char=' ', inside_dict=False, inside_list=False, line_length=80,
line_context=0):
if not inside_dict:
print(ident_char * start_ident, end='')
if len(repr(data)) + start_ident + line_context < line_length:
print(repr(data) + (',' if inside_dict or inside_list else ''))
return
elif isinstance(data, dict):
@cypreess
cypreess / 12factors.py
Last active July 6, 2018 11:06
Lightweight helpers to read settings from environement variables
import os
import re
import sys
from functools import wraps
import logging
logger = logging.getLogger(__name__)
WARN_ON_MISSING = True
@cypreess
cypreess / django_enum_choices.py
Created July 11, 2018 08:18
Django choices helper class
# Example usage:
# class Car(models.Model):
# class Colors(ChoiceEnum):
# RED = 'red'
# WHITE = 'white'
# BLUE = 'blue'
#
# color = models.CharField(max_length=5, choices=Colors.choices(), default=Colors.RED)
#
# Querying requires an extra word to type though...
@cypreess
cypreess / compassbearing.py
Last active July 23, 2018 11:52 — forked from jeromer/compassbearing.py
compass bearing between two points in Python
import math
def calculate_initial_compass_bearing(pointA, pointB):
"""
Calculates the bearing between two points.
The formulae used is the following:
θ = atan2(sin(Δlong).cos(lat2),
cos(lat1).sin(lat2) − sin(lat1).cos(lat2).cos(Δlong))
import re
def zstd_readline(filename, chunksize=zstd.DECOMPRESSION_RECOMMENDED_OUTPUT_SIZE):
with open(filename, 'rb') as fh:
with zstd.ZstdDecompressor().stream_reader(fh) as reader:
leftovers = ''
while True:
chunk = reader.read(chunksize).decode('utf-8')
if not chunk:
break