Skip to content

Instantly share code, notes, and snippets.

@dmwyatt
dmwyatt / temp_backup.py
Last active October 25, 2023 22:09
[temporarily replace file] Sometimes when testing I want to replace a file with a test file. This context manager does that. #testing
import contextlib
import shutil
from pathlib import Path
@contextlib.contextmanager
def replace_file(orig, replace_with):
if not replace_with.is_file():
raise ValueError("{} does not exist.".format(replace_with))
if orig.is_file():
@dmwyatt
dmwyatt / check_if_executable.py
Last active October 25, 2023 22:09
[Check if file is executable.]
def is_exe(filepath):
return os.path.isfile(filepath) and os.access(filepath, os.X_OK)
@dmwyatt
dmwyatt / hash_dir.py
Last active October 25, 2023 22:09
[hash directory and capture filename data]
import os
import hashlib
def hash_dir(path):
"""
Create a hash out of a directory that handles renamed files.
A hash of the contents of a file will not capture a hash of the filename.
This function will add filenames to the hash so that we can know if a
@dmwyatt
dmwyatt / recursive_glob.py
Last active December 6, 2019 18:39
[Recursive glob.] Demo of `fnmatch`. Matches filenames, recursively. From http://stackoverflow.com/questions/2186525/use-a-glob-to-find-files-recursively-in-python
import fnmatch
import os
matches = []
for root, dirnames, filenames in os.walk("src"):
for filename in fnmatch.filter(filenames, "*.c"):
matches.append(os.path.join(root, filename))
@dmwyatt
dmwyatt / string_format.js
Last active November 26, 2019 01:49
[String.format for javascript]
// From http://stackoverflow.com/questions/1038746/equivalent-of-string-format-in-jquery
String.prototype.format = String.prototype.f = function() {
var s = this,
i = arguments.length;
while (i--) {
s = s.replace(new RegExp('\\{' + i + '\\}', 'gm'), arguments[i]);
}
return s;
@dmwyatt
dmwyatt / test_cbv.py
Last active December 6, 2019 18:41
[Class based views (CBV) unit testing] #django
# From http://tech.novapost.fr/django-unit-test-your-views-en.html
# or https://tech.people-doc.com/django-unit-test-your-views.html
#
# django test client is an integration test, not a unit test so we
# need a way to test views.
import unittest
from django.test import RequestFactory
def setup_view(view, request, *args, **kwargs):
@dmwyatt
dmwyatt / model_diff_mixin.py
Last active October 25, 2023 22:08
[ModelDiffMixin: compare previous values to new values] lets you compare previous values to new values when saving Django model #django
from django.forms.models import model_to_dict
class ModelDiffMixin(object):
"""
A model mixin[1] that tracks model fields' values and provide some useful api
to know what fields have been changed.
[1] http://stackoverflow.com/questions/1355150/django-when-saving-how-can-you-check-if-a-field-has-changed
"""
@dmwyatt
dmwyatt / register_app_routes.py
Last active October 25, 2023 22:08
[auto drf url registration] Using Django Rest Framework's DefaultRouter to build an API Root for urls.py files located in individual apps. #django #drf
# urls.py
def register_routes(router, apps):
"""
Register DRF router routes from urls.py in the provided apps.
>>> router = routers.DefaultRouter()
>>> register_routes(router, ['app1', 'app2', 'app3])
"""
for app in apps:
urls = importlib.import_module(app+".urls")
@dmwyatt
dmwyatt / dict_differ.py
Last active October 25, 2023 22:07
[dict diff]
class DictDiffer(object):
"""
Calculate the difference between two dictionaries as:
(1) items added
(2) items removed
(3) keys same in both but changed values
(4) keys same in both and unchanged values
http://stackoverflow.com/questions/1165352/fast-comparison-between-two-python-dictionary/1165552#1165552
"""
@dmwyatt
dmwyatt / show_urls.py
Last active October 25, 2023 22:07
[Pretty print urls] Print indented list of urls configured in a django project #django
def show_urls(urllist: list, indent_depth: int = 0, indent_char: str = " "):
"""
Prints a list of urls for this project.
:param urllist: A list of url patterns. Typically `urlpatterns` imported from `urls.py`
:param indent_depth: How far to indent for each sub-level of urls
:param indent_char: The charcter to use to indent.
"""
for entry in urllist:
print(indent_char * indent_depth, entry.regex.pattern, end="")