Skip to content

Instantly share code, notes, and snippets.

View mariocesar's full-sized avatar

Mario-César mariocesar

View GitHub Profile
@mariocesar
mariocesar / celery.py
Created December 18, 2024 14:30
Celery. Reduce risk of idle connections by closing connections.
from celery import Celery
from celery.signals import worker_shutdown, task_postrun
from django.db import connections
app = Celery()
...
atom dimension {
width: int?
height: int?
depth: int?
}
atom money {
amount: int
currency: string
}
@mariocesar
mariocesar / models.py
Created August 9, 2024 19:09
SearchableCharField in Django, GIN Index for case-insensitive search
from django.db import models
from django.contrib.postgres.indexes import GinIndex
from django.db.models.functions import Lower
class SearchableCharField(models.CharField):
def contribute_to_class(self, cls, name, **kwargs):
super().contribute_to_class(cls, name, **kwargs)
# Add a GIN index with trigram operations for fast search
@mariocesar
mariocesar / json_jinja2_decoder.py
Last active August 12, 2024 18:17
A JSON Decoder that will evaluate strings as jinja2 expressions
"""
TODO: Use an strict environment like SandboxedEnvironment
TODO: Create an "allowed list" of filters and functions to use in the expression
TODO: Make or check the context object is inmutable (Prevent thread-safe situations)
"""
import json
from datetime import datetime
from jinja2 import Environment, meta, sandbox
@mariocesar
mariocesar / README.md
Last active November 15, 2024 14:20
Useful oneliners that I often forget. #terminal #python #shell

bash

Get a sha256sum hash for all the given files, similar to GitHub Action hashFiles function.

hashFiles() {
    local files=("$@")
    if [[ ${#files[@]} -eq 0 ]]; then
        echo "Error: No files provided" >&2
        return 1

This small snippet can be implemented in your Django project to handle locks. It is particularly useful for replacing Redis locks, reducing dependency overhead. To use this snippet, simply copy and adapted to your Django project.

The hash_string function is used to convert a string value into a numerical hash value, as PostgreSQL advisory lock mechanism requires an integer.

Tested on Python3.11 and Django4

Learn more about advisory locks in:

@mariocesar
mariocesar / ruff.toml
Created May 6, 2024 17:03
My ruff toml configuration with useful defaults and rules
exclude = ["docs/*", "*/migrations/*", ".git/*"]
line-length = 100
indent-width = 4
target-version = "py311"
[lint]
select = [
"E", # pycodestyle errors
"W", # pycodestyle warnings
"N", # pep8-naming
@mariocesar
mariocesar / parsing_commands.py
Last active May 2, 2024 03:38
An example on how to Parse commands from Slack using argparse
import argparse
import shlex
from typing import List, Optional, TypedDict
class Command(TypedDict):
prefix: str
name: str
args: List[str]
@mariocesar
mariocesar / README.md
Last active April 12, 2024 14:09
Prueba de revisión. Code Challenge. Programming Skills

Instrucciones para el candidato

Adjunto encontrarás un script de Python llamado script.py y un archivo CSV llamado data.csv.

  1. El archivo data.csv contiene datos de productos con las siguientes columnas: product_id, name, category_name, price, quantity.
  2. El script script.py carga los datos del archivo CSV, calcula la media, el promedio y la moda de los precios de los productos agrupados por categoría, y muestra los resultados en la consola.
  3. Tu tarea es revisar el código del script script.py y proponer cambios, mejoras o identificar cualquier problema, similar a lo que harías en una revisión a un Merge Request.
  4. Prepara tus comentarios, sugerencias y mejoras propuestas para discutirlas durante la siguiente entrevista.

El objetivo de este ejercicio es evaluar tus habilidades para identificar problemas, proponer mejoras y más que todo comunicar tus ideas de manera efectiva.