Skip to content

Instantly share code, notes, and snippets.

View mariocesar's full-sized avatar

Mario-César mariocesar

View GitHub Profile
@mariocesar
mariocesar / password_hasher.py
Created December 14, 2020 22:45
Some notes for twitch.tv/melkeydev to make a simple/secure password hasher
import base64
import hashlib
import secrets
from typing import NoReturn
def pbkdf2(password: str, salt: str, iterations: int, dklen: int=0, digest=None):
"""Return the hash of password using pbkdf2."""
if digest is None:
digest = hashlib.sha256
@mariocesar
mariocesar / Makefile
Last active November 25, 2020 21:41
Build all icons and favicon needed for a webpage, using a svg input file
INKSCAPE_BIN ?= flatpak run org.inkscape.Inkscape
iconsizes = 16 32 48 57 60 72 76 96 120 144 152 180 192 256 300
iconnames = $(addsuffix .png, $(addprefix icons/icon-, $(iconsizes)))
all: icons icons/favicon.ico $(iconnames)
@echo = Done =
icons:
mkdir -p icons
from multiprocessing import Queue, Process
def do_something_really_slow(url):
...
result = Queue()
proc = Process(target=do_something_really_slow, args=(url,))
proc.start()
proc.join(timeout=5) # Wait 5 seconds, then timeout
@mariocesar
mariocesar / script.py
Created September 30, 2020 20:43
Python requests timeout retry
import requests
from requests.adapters import Retry, HTTPAdapter
class RetryTimeoutAdapter(HTTPAdapter):
def __init__(self):
max_retries = Retry(
total=3,
backoff_factor=1,
status_forcelist=[500, 502, 503, 504],
method_whitelist=["GET", "HEAD", "INFO"],
@mariocesar
mariocesar / wsgi.py
Last active July 1, 2020 13:59
Adding custom header with the deploy datetime of a Django app. Useful also for adding revision, and other deploy information
import os
import subprocess
from datetime import datetime
import django
from django.core.handlers.wsgi import WSGIHandler
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "conf.settings.develop")
DEPLOY_REVISION = subprocess.check_output(["git", "rev-parse", "HEAD"]).decode().strip()
@mariocesar
mariocesar / runtasks.py
Created June 30, 2020 21:36
Run a celery task in a django project using a command #django #celery
import json
import logging
from logging import getLogger, DEBUG
from celery import signature
from django.core.management.base import BaseCommand, CommandError
class Command(BaseCommand):
def add_arguments(self, parser):
@mariocesar
mariocesar / django_clone_model_instance.py
Last active February 23, 2020 21:45
Django / Clone a model instance, exclude fields optionally
from typing import Any, Dict, List, Tuple, Optional
from django.db.models import Model, ManyToManyField
from django.db.models.fields import Field
def clone_model_instance(
instance: Model, exclude: Optional[Tuple[str]] = None, commit=True
) -> Model:
exclude = exclude or ()
concrete_fields: List[Field] = instance.__class__._meta.concrete_fields
@mariocesar
mariocesar / nginx.conf
Last active February 18, 2020 14:23
NGINX / Rewrite all Uppercase urls to the lowercase form
# Testing with docker:
# docker run --rm -it -p 8000:80 -v $(pwd)/nginx.conf:/etc/nginx/nginx.conf nginx:stable-perl
load_module modules/ngx_http_perl_module.so;
user nginx;
worker_processes 1;
http {
include /etc/nginx/mime.types;
@mariocesar
mariocesar / script.js
Created December 16, 2019 18:13
Add responsive classes to the body using efficient mediaqueries. Useful to integrate CSS/JS actions
(() => {
const checkMediaQuery = (mq) => {
// Check if we add or remove the class depending if it matches or not
if (mq.matches) {
document.body.classList.add('sm')
} else {
document.body.classList.remove('sm')
}
}
@mariocesar
mariocesar / README.md
Last active October 26, 2019 15:05
Watchexec

watchexec is a simple, standalone tool that watches a path and runs a command whenever it detects modifications.

Examples

Watch all JavaScript, CSS and HTML files in the current directory and all subdirectories for changes, running make when a change is detected:

watchexec --exts js,css,html make