Skip to content

Instantly share code, notes, and snippets.

@jsatt
jsatt / async_tests.py
Last active December 14, 2023 17:16
Samples of various asyncio patterns to understand how it works.
import asyncio
from time import time
from httpx import AsyncClient
async def async_request(url: str):
async with AsyncClient() as client:
resp = await client.get(url)
result = len(resp.read())
@jsatt
jsatt / policies.json
Created September 14, 2016 00:50
AWS IAM Policy examples
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": [
"iam:ListUsers"
],
"Resource": "arn:aws:iam::*:*"
},
@jsatt
jsatt / fields.py
Created June 30, 2021 20:25
Django Encrypted Data field
import base64
import json
from typing import Any, Optional, Union
from cryptography.fernet import Fernet
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives import hashes
from django.conf import settings
from django.db import models
@jsatt
jsatt / gist:d844173e001be3eafbbcdad41f4617a7
Created April 20, 2021 20:27
Dot-notation access to deeply nested dict
def deep_get(path, data, default=None):
"""
Uses a provided dot-notation path to retrieve values from a deeply nested dict
"""
if isinstance(path, str):
path = path.split('.')
obj = data
for key in path:
obj = obj.get(key)
if obj is None:
@jsatt
jsatt / deep_merge.py
Last active August 26, 2020 14:38 — forked from yatsu/deep_merge.py
Python dict deep merge
from copy import deepcopy
from functools import reduce
def merge_dicts(dict1: dict, dict2: dict) -> dict:
"""
Merges dicts.
"""
for key in dict2:
if key not in dict1 or not isinstance(dict1[key], dict):
@jsatt
jsatt / parsers.py
Created August 26, 2020 14:31
Django view to capture file from multipart or body POST
from io import BytesIO
from django.conf import settings
from django.core.files.uploadedfile import InMemoryUploadedFile
from django.core.files.uploadhandler import FileUploadHandler
from rest_framework.parsers import DataAndFiles, FileUploadParser
class BodyUploadHandler(FileUploadHandler):
def new_file(self, *args, **kwargs):
@jsatt
jsatt / views.py
Created February 12, 2020 20:10
DRF flex field optimization
import coreapi
from django.core.exceptions import FieldDoesNotExist
from rest_flex_fields.utils import is_expanded
from rest_framework.exceptions import APIException
from rest_framework.schemas.inspectors import AutoSchema
class FlexFieldSchema(AutoSchema):
def __init__(self, view, *args, **kwargs):
super().__init__(*args, **kwargs)
@jsatt
jsatt / serializers.py
Created February 12, 2020 20:03
Catalog serizalier and field
from catalog import CatalogMember
from collections import OrderedDict
from itertools import chain
from rest_framework.exceptions import APIException
from rest_framework.fields import ReadOnlyField
from rest_framework.serializers import Serializer
class CatalogSerializer(Serializer):
@jsatt
jsatt / main.py
Last active February 9, 2020 00:44
CircuitPy neopixel color dial
import math
import board
import neopixel
import analogio
import time
from simpleio import map_range
NEOPIXEL_PIN = board.D5
NEOPIXEL_COUNT = 20
@jsatt
jsatt / paginate.py
Created December 30, 2013 16:07
A more powerful Django queryset paginator. Sets up common boilerplate for pagination, including page number validity checking. It also provides a range of "neighbor" page numbers and find what page a specific object is on. `object_list` can be a queryset or iterable of objects, (not just Django models). Setting `page_range` arg will adjust numbe…
from django.core.paginator import Paginator, InvalidPage, EmptyPage
def paginate(request, object_list, limit=10, page_range=10, object_pk=None):
paginator = Paginator(object_list, limit)
page = None
if object_pk:
if hasattr(object_list, 'values_list') and callable(
object_list.values_list):
object_list = list(object_list.values_list('pk', flat=True))