Skip to content

Instantly share code, notes, and snippets.

@elsholz
elsholz / missing_fields.py
Last active December 29, 2023 13:41
Potentially Missing Fields for FastAPI Partial Updates

When working on patch requests with FastAPI, one may encounter the situation where you would want to ignore fields not supplied in a request. While you could do this with the Optional type annotation, this means that you have to use None as a flag that a field is not set, by setting it as the default value. This may not be suitable though, when None is an actual valid value for a field. In this case, you could use a special value for indicating a missing field.

Below is a code snippet where I have implemented this approach. The type MissingValueBaseClass is used for creating an object named Missing, which can be assigned as the default value for potentially missing fields. These fields have to be annotated using the function MaybeMissing, which takes in a type t and returns a Union with MissingValueBaseClass. By inheriting from ModelMayMissFields, the class UpdateUser can return a dict containing only values that are set with the method get_existing_fields.

@elsholz
elsholz / get_thermal_printer_info.md
Last active December 23, 2023 16:23
Find out the values you need to know to connect a thermal printer via USB from a python script.

Find EP-Ids and Device ID of Thermal Printer by name

When using the Python Library python-escpos to use a thermal printer via usb, you need the device id, vendor id, endpoint out id, and endpoint in id.

Finding these values took me some time, so here is a script that automates the process.

All you need to supply to the script is the name of the printer device. Find it out by running lsusb with the printer disconnected. Then connect the printer and run lsusb again. Look out for the device that has been added and remember its name (or some part of it, doesn't really matter).

Run ./get_thermal_printer_info.sh "device name" and there you'll find the values you need to create the escpos.printer.Usb object.

import RPi.GPIO as GPIO
from random import randrange
from time import sleep
import threading
# Set the time for the relays to be turned on, before being turned off again
SWITCH_TIME = 0.1
GPIO.setmode(GPIO.BCM)
@elsholz
elsholz / i3wm_media_lock.md
Last active January 15, 2023 10:58
How to create a transparent lock screen in i3wm. Locks screen, but shows no lock screen. Unlocks as usual, if correct password is entered.

i3wm Transparent Lock screen.

Warning: If executed multiple times, unlock isn't possible anymore, use with caution!

Description

Block computer for input, but remain graphical output as usual. Can be used for example to watch a movie on your laptop but forbid any input during that.

Downside

Not tested thouroughly yet, and only tested on Debian 9