Skip to content

Instantly share code, notes, and snippets.

@dmwyatt
dmwyatt / channels_middleware.py
Last active August 7, 2021 16:03
[django-channels subprotocol auth middleware] Retrieves JWT from the websocket's subprotocol and retreives the appropriate user. #jwt #auth #django #websocket
import logging
from typing import Awaitable, Final, List, TYPE_CHECKING, TypedDict
from channels.auth import AuthMiddlewareStack
from channels.db import database_sync_to_async
from django.contrib.auth.models import AnonymousUser
from rest_framework.exceptions import AuthenticationFailed
from rest_framework_jwt.authentication import JSONWebTokenAuthentication
from rest_framework_jwt.blacklist.exceptions import MissingToken
@dmwyatt
dmwyatt / maybe_get.py
Created September 11, 2020 21:04
[maybe_get] Get values from mixed nested dicts and objects by list of strings.
def maybe_get(obj: Any, items: List[Hashable], default: Optional[Any] = None) -> Any:
"""
Retrieves a value from nested dicts and objects.
Given an object which can be a dict-like object or regular objects (aka, objects
who have values accessible via `getattr` or `operator.getitem`), and a list of
accessors for those objects, this function will retrieve the specified value.
This is perhaps easier to understand with an example:
@dmwyatt
dmwyatt / mekea.py
Last active August 13, 2020 21:15
[mekea] Get stock info from Ikea given a store number and an item number. #scripts
# Get store number from https://www.ikea.com/ext/us/local-stores/
#
# Requires python 3.8+
#
# Usage
# ==================
#
# $ python mekea.py 410 00470251
# Availability info for 00470251
# ┏━━━━━━━┳━━━━━━━┳━━━━━━━━━━━━━┳━━━━━━━━━━━━┓
@dmwyatt
dmwyatt / task_lock.py
Created August 2, 2020 22:25
[celery-dj-cache-lock] Lock tasks by task name and arguments. #django #celery
"""
A decorator to lock celery tasks using django's cache framework.
Based upon example in Celery's task cookbook.
https://docs.celeryproject.org/en/stable/tutorials/task-cookbook.html
"""
import logging
import time
from celery import Task
@dmwyatt
dmwyatt / path_path.py
Created May 1, 2020 18:29
[path path] A click option type that provides a pathlib.Path instead of a click.Path.
class PathPath(click.Path):
"""A Click path argument that returns a pathlib Path, not a string"""
def __init__(self, *args, require_dir: bool = False, make_absolute:
bool=True, **kwargs) -> None:
super().__init__(*args, **kwargs)
self.require_dir = require_dir
self.make_absolute = make_absolute
def convert(self, value, param, ctx):
@dmwyatt
dmwyatt / windows_service.py
Last active April 21, 2020 21:30
[windows service] Python as a windows service. #windows
"""
SMWinservice
by Davide Mastromatteo
Base class to create winservice in Python
-----------------------------------------
Instructions:
1. Just create a new class that inherits from this base class
@dmwyatt
dmwyatt / cli.py
Last active April 20, 2020 19:21
[remove control characters] Remove control characters from a string. #unicode
import unicodedata
def remove_control_characters(s):
return "".join(ch for ch in s if unicodedata.category(ch)[0] != "C")
@dmwyatt
dmwyatt / punctuation.py
Created April 4, 2020 20:21
[Character is punctuation] Returns whether a character is a punctuation/symbol character. #unicode #strings
import sys
from functools import lru_cache
from unicodedata import category
@lru_cache()
def get_punctuation_chars():
"""
https://stackoverflow.com/a/60983873
@dmwyatt
dmwyatt / dir_size.py
Created March 21, 2020 21:52
[Get directory size] Walk a directory tree and get the sizes of the directories
"""https://stackoverflow.com/a/12480543/23972"""
import os
from os.path import join, getsize
dirs_dict = {}
#We need to walk the tree from the bottom up so that a directory can have easy
# access to the size of its subdirectories.
for root, dirs, files in os.walk('python/Lib/email',topdown = False):
# Loop through every non directory file in this directory and sum their sizes
@dmwyatt
dmwyatt / highlightWord.js
Created February 27, 2020 00:26
[Highlight word] Properly highlight a word in a chunk of text #react
const highlightWord = (text, word, className) => {
const parts = text.split(new RegExp(`(${word})`, "gi"));
for (let i = 1; i < parts.length; i += 2) {
parts[i] = <span className={className} key={i}>{parts[i]}</span>;
}
return parts
};