You're browsing snippets anonymously. Log in or create an account to save and manage your own snippets.
Public Snippets
Showing
7 snippets
using
language:
Python
Create safe filename string
def safe_filename(s: str, replacement: str = "_") -> str:
"""
Convert a string to a safe filename by replacing unsafe characters.
Args:
s (str): The input string to be conver...
By
xtream1101
•
•
Updated
2025-10-15 14:35
Django Query Stats per request
# stats.py
import time
from django.db import connection
from loguru import logger
class StatsMiddleware:
def __init__(self, get_response):
self.get_response = get_response
...
By
xtream1101
•
•
Updated
2025-05-11 00:04
Reset default python log handlers
import logging
formatter = logging.Formatter('FOO: %(message)s')
root_logger = logging.getLogger()
root_logger.setLevel(logging.INFO)
# This is the key line that removes the double logging
...
By
xtream1101
•
•
Updated
2025-03-04 18:33
Django graphene mutation input validation
import graphene
class ScratchpadMutation(graphene.relay.ClientIDMutation):
class Input:
created_by = graphene.String(required=True)
foobar = graphene.String()
test = g...
By
xtream1101
•
•
Updated
2025-02-06 14:13
Try, try again - Multiple try/except blocks in a flat format
data = {'some_key': 'key value'}
key_data = None
for _ in range(1):
try:
key_data = data['someKey']
except Exception: pass
else: break # It worked
try:
key_d...
By
xtream1101
•
•
Updated
2025-02-06 13:43
Multi key sort on a list of dicts
data = [
{'name': 'Alice', 'age': 25, 'city': 'New York'},
{'name': 'Bob', 'age': 30, 'city': 'London'},
{'name': 'Charlie', 'age': 20, 'city': 'New York'}
]
# Sort by 'city' first,...
By
xtream1101
•
•
Updated
2025-02-06 13:27
Showing
7 snippets
Snippet
def safe_filename(s: str, replacement: str = "_") -> str:
"""
Convert a string to a safe filename by replacing unsafe characters.
Args:
s (str): The input string to be converted.
replacement (str): The character to replace unsafe characters with. Default is "_".
Returns:
str: A safe filename string.
"""
keep_chars = (" ", ".", "_", "-")
safe_name = "".join(c if c.isalnum() or c in keep_chars else replacement for c in s)
safe_name = safe_name.strip().strip(".")
return safe_name
if __name__ == "__main__":
test_cases_safe_filename = [
("example<file>name.txt", "example_file_name.txt"),
("unsafe:/\\|?*name.doc", "unsafe______name.doc"),
("normal_filename.pdf", "normal_filename.pdf"),
(" leading and trailing spaces ", "leading and trailing spaces"),
("file.name.with.many.dots...", "file.name.with.many.dots"),
("control\x00char\x1fname", "control_char_name"),
]
# Test safe_filename function
print("Testing safe_filename function:")
for input_str, expected_output in test_cases_safe_filename:
result = safe_filename(input_str)
assert result == expected_output, (
f"Failed for input '{input_str}': got '{result}', expected '{expected_output}'"
)
print("\nAll tests passed!")
By
xtream1101
•
•
Updated
2025-10-15 14:35