Skip to content

Instantly share code, notes, and snippets.

Avatar
🎯
Focusing

Mario César mariocesar

🎯
Focusing
View GitHub Profile
View script.py
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 Sep 30, 2020
Python requests timeout retry
View script.py
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 Jul 1, 2020
Adding custom header with the deploy datetime of a Django app. Useful also for adding revision, and other deploy information
View wsgi.py
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 Jun 30, 2020
Run a celery task in a django project using a command #django #celery
View runtasks.py
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 Feb 23, 2020
Django / Clone a model instance, exclude fields optionally
View django_clone_model_instance.py
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 Feb 18, 2020
NGINX / Rewrite all Uppercase urls to the lowercase form
View nginx.conf
# 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 Dec 16, 2019
Add responsive classes to the body using efficient mediaqueries. Useful to integrate CSS/JS actions
View script.js
(() => {
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')
}
}
View README.md

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
@mariocesar
mariocesar / README.md
Last active Oct 12, 2019
Terminal one-liners, helpers and tricks. #docker #bash #terminal #python
View README.md

Python

You have Python but not CURL or WGET installed, no problem

function urlget { \
    # urlget URL OUT \
    python -c "import urllib2;response=urllib2.urlopen('${1}');f=open('${2}', 'wb');f.write(response.read());f.close()" \
}
@mariocesar
mariocesar / script.sh
Created Sep 17, 2019
Output all scripts output as valid json lines / Bash function to output stdout lines as json formatted lines / Useful for logging in AWS ECS to CloudWatch logs
View script.sh
#!/usr/bin/env bash
set -eo pipefail
function message() {
python -c '
import sys
import os
import json
import datetime
You can’t perform that action at this time.