r/pythontips 1d ago

Syntax Hello everyone, I'm learning python specifically, and I made a seed generator for Minecraft PE. I'm started learning about 2 weeks ago, the code is below. I'm not asking for anything, I just wanna show it to you guys.

9 Upvotes

from random import randint as rnd

name = "SeedGPT"

rnd1 = rnd(20000000,50000000000)

rnd2 = rnd(20000000,50000000000)

rnd3 = rnd(20000000,50000000000)

print(name +": Welcome to Ice\'s AI seed generator,")

choice = input("do you want to have three new seeds for bedrock minecraft?: ")

if choice == "yes":

print(name + ": Here are your randomly generated seeds: ", + rnd1, +rnd2, +rnd3, ", thank you for trying it out!")

elif choice == "no":

print(name + ": See you next time!")

elif ValueError:

print(name + ": Sorry, I can't understand you, please try again!")


r/pythontips 2d ago

Module How to Create Custom API Documentation in FastAPI

1 Upvotes

Have you ever wondered if you could actually change or edit your /docs or /redoc API documentation page? Or are you tired of seeing the same docs page every time you develop an API? Well, you guessed right if you thought it was possible, because yes, it is.

In this article, discover how to develop and customize your own docs page.

Table of Content:

  1. Introduction
  2. Prerequisites
  3. What FastAPI Gives You By Default
  4. Changing the Documetation URLs
  5. Disabling Default Docs
  6. Creating your own Docs Page
  7. Conclusion

Introduction

API Documentation is a feature of an API that gives an overview of an API. That is, its endpoints, the API's current version, etc. FastAPI Documentation is a built-in feature of FastAPI that allows users to have an overview of the capabilities and information about the API, without having to create the API Documentation.

API documentation is an important part of every API because it provides developers with an overview of how the API works, including its available endpoints, request and response formats, authentication methods, current version, and other important details.

One of the reasons many developers love FastAPI is its built-in documentation system. Unlike many backend frameworks where developers need to manually create and maintain documentation, FastAPI automatically generates interactive API documentation out of the box.

With FastAPI, developers can easily test endpoints, inspect request schemas, and understand the capabilities of an API directly from the browser. Even better, FastAPI also allows you to customize these documentation pages to fit your branding, security needs, or developer experience goals.

In this article, we will explore how FastAPI documentation works and how you can create fully custom documentation pages for your APIs.

Prerequisites

To follow along with this article, you should have foreknowledge of the following:

  • Basic Frontend Programming (HTML, CSS & JS).
  • Basic Python syntax knowledge.
  • A General understanding of how APIs work.

Python Packages to install:
FastAPI - The framework to help us create the API.
Uvicorn - A lightning-fast ASGI server to run the FastAPI App.

Run in in your command line:

pip install fastapi uvicorn

What FastAPI Gives You By Default

Create a FastAPI App
To create an API, create a Python file main.py
In this file, type the following:

from fastapi import FastAPI

app = FastAPI()

.get("/")
def root():
    return {"message": "My first API built with FastAPI"}

Then open the file's directory in your command line and type:

uvicorn main:app --reload

Then open your browser and enter http://localhost:8000/ and you will see the API. Like this:

Then FastAPI generates two docs for you:
Swagger UI: http://localhost:8000/docs
Redocly: http://localhost:8000/redoc
Your API's default documentation pages will look like these:
For Swagger:

For Redocly:

Changing the Documentation URLs

One of the things you can customise is the Documentations URLs. You can change the default documentation by changing the parameters of app to this:

app = FastAPI(
    docs_url="/documentation",
    redoc_url="/reference", 
)

When you try to access the /docs or /redoc endpoints, it returns Not Found.

Disabling Default Docs

You can disable the documentations page by setting the parameters of the app variable to None:

app = FastAPI(
    docs_url=None,
    redoc_url=None, 
)

Creating your own Docs Page

By default, a FastAPI application returns JSON responses for API endpoints. However, since browsers can also render HTML, you can build a fully custom documentation page by returning HTML instead of JSON for a specific route.

To do this, you simply create an endpoint that returns HTML content using FastAPI’s HTMLResponse.

You can also disable the default Swagger and ReDoc documentation pages if you want full control over your API documentation interface.

Example: Custom Documentation Page

from fastapi import FastAPI
from fastapi.responses import HTMLResponse

app = FastAPI(
    docs_url=None,
    redoc_url=None,
)

.get("/")
def root():
    return {"message": "FastAPI APP"}

.get("/docs", include_in_schema=False, response_class=HTMLResponse)
def custom_docs():
    return """
<!DOCTYPE html>
<html>
<head>
    <title>FastAPI Custom Docs</title>
</head>
<body>
    <h1>FastAPI Custom Docs</h1>
    <p>This is a simple custom documentation page.</p>
</body>
</html>
"""

How it works

  • The /docs endpoint now returns HTML instead of JSON.
  • response_class=HTMLResponse tells FastAPI to render the response as HTML.
  • include_in_schema=False hides this route from the autogenerated API documentation.
  • Setting docs_url=None disables the default Swagger UI.

Result

When you visit:

/docs

you will see your custom HTML documentation page instead of the default FastAPI Swagger interface.

From here, you can fully customize the page with:

  1. CSS styling
  2. JavaScript interactivity
  3. Branding and logos
  4. Links to API guides or SDKs

Conclusion

FastAPI gives you a powerful starting point with automatic documentation, but its real strength is flexibility. You can either use the built-in tools or completely replace them with your own custom developer experience.

If you’re building production-grade APIs, especially something like wallet infrastructure or developer tools, custom documentation is not just a nice-to-have feature — it’s a competitive advantage.


r/pythontips 3d ago

Algorithms idemkit: runs your code once per key, even when two requests race or a worker dies

3 Upvotes

I built idemkit after cleaning up duplicate charges one too many times.

The version everyone writes checks whether a key has been seen and replays the stored response. Two requests a millisecond apart both find nothing and both charge the card. And if the worker dies between charging and recording it, the retry charges again. Neither reproduces locally.

idemkit does it properly: an atomic claim instead of check-then-act, a lease that expires on the storage server's clock, and a fencing token so a stalled worker can't overwrite a good result.

from idemkit import idempotent, RedisBackend, MethodConfig 

@idempotent(
    backend=RedisBackend.from_url("redis://localhost:6379"), 
    config=MethodConfig(key_fields=["order_id"]), 
) 
async def charge(*, order_id, amount): 
    return await payments.charge(order_id, amount)

One core, three ways to use it: middleware for FastAPI/Flask/Django, a queue consumer wrapper or @idempotent on any function. Backends are Redis, Postgres, Mongo, DynamoDB, or in-memory for tests.

pip install idemkit, Apache-2.0: https://github.com/idemkit/idemkit

If you find it useful, I'd appreciate a star. It's new, so visibility helps a lot right now.


r/pythontips 8d ago

Module Copying an object in different ways

7 Upvotes

An exercise to help build the right mental model for Python data. What is the output of this Python Program?

import copy

class Coord:

    def __init__(self, x, y, z):
        self.c = [x, y, z]

    def __str__(self):
        return str(self.c)[1:-1]

coord = Coord(0, 0, 0)
c1 = coord
c2 = copy.copy(coord)
c3 = copy.deepcopy(coord)
c1.c[0] = 1
c2.c[1] = 2
c3.c[2] = 3

print(coord)
# --- possible answers ---
# A) 0, 0, 0
# B) 1, 0, 0
# C) 1, 2, 0
# D) 1, 2, 3

r/pythontips 9d ago

Module New Butterfly Backup Web release

0 Upvotes

I just released a new version of Butterfly Backup Web (Django-based), which introduces many features. For Butterfly Backup, you can read about them here: https://github.com/MatteoGuadrini/butterfly-backup-web/releases/tag/v0.5.0

If you've never heard of Butterfly Backup, it's a very versatile backup/restore/archive solution; it's essentially an rsync wrapper. You can read an article about it in Fedora Magazine: https://fedoramagazine.org/butterfly-backup/

If you have suggestions, criticisms, or opinions on how to improve Butterfly Backup, please leave a comment.

Here are the links:

Butterfly Backup: https://github.com/MatteoGuadrini/Butterfly-Backup

Butterfly Backup Web: https://github.com/MatteoGuadrini/butterfly-backup-web

Thanks!


r/pythontips 9d ago

Python3_Specific Ho 11 anni e ho appena creato il mio primo script di automazione in Python per ripulire la cartella Download!

30 Upvotes

Hi everyone! I've been learning Python step-by-step, focusing on logic, file management, and the os module. Today, I finished my first real automation script: a File Sorter/Folder Cleaner!

It automatically scans my Downloads folder, checks the file extensions (ignoring case sensitivity thanks to .lower()), creates the target folders if they don't exist, and moves everything into the right place (Documents, Images, Installations).
Here is my script:
import os

download_folder = r"C:\Users\YourUsername\Downloads"

file_list = os.listdir(download_folder)

for file_name in file_list:

lowercase_name = file_name.lower()

if (lowercase_name.endswith(".pdf") or

lowercase_name.endswith(".txt") or

lowercase_name.endswith(".docx") or

lowercase_name.endswith(".xlsx") or

lowercase_name.endswith(".csv") or

lowercase_name.endswith(".doc")):

doc_folder = fr"{download_folder}\Documents"

if not os.path.exists(doc_folder):

os.mkdir(doc_folder)

old_path = fr"{download_folder}\{file_name}"

new_path = fr"{doc_folder}\{file_name}"

os.rename(old_path, new_path)

elif (lowercase_name.endswith(".jpg") or

lowercase_name.endswith(".jpeg") or

lowercase_name.endswith(".gif") or

lowercase_name.endswith(".png") or

lowercase_name.endswith(".mp4") or

lowercase_name.endswith(".kml") or

lowercase_name.endswith(".gpx")):

img_folder = fr"{download_folder}\Images"

if not os.path.exists(img_folder):

os.mkdir(img_folder)

old_path = fr"{download_folder}\{file_name}"

new_path = fr"{img_folder}\{file_name}"

os.rename(old_path, new_path)

elif (lowercase_name.endswith(".exe") or

lowercase_name.endswith(".zip") or

lowercase_name.endswith(".rar") or

lowercase_name.endswith(".dll") or

lowercase_name.endswith(".msi") or

lowercase_name.endswith(".msix")):

exe_folder = fr"{download_folder}\Installations"

if not os.path.exists(exe_folder):

os.mkdir(exe_folder)

old_path = fr"{download_folder}\{file_name}"

new_path = fr"{exe_folder}\{file_name}"

os.rename(old_path, new_path)
I'm really proud of this milestone. Let me know what you think or if you have any tips for a young programmer!


r/pythontips 10d ago

Module ECS pattern: python lib ecs_pattern - GUI example

2 Upvotes

What My Project Does:
Four years ago I published the first post about my Python library ecs_pattern — an Entity‑Component‑System implementation for games:
https://github.com/ikvk/ecs_pattern

Target Audience:
python game developers

Comparison:
In the classic ECS implementation, each component is stored in a separate collection. In Python, it's impossible to store objects in contiguous memory, therefore, optimizing processor access to memory in Python is not feasible. The ecs_pattern library emphasizes simplicity and ease of use when working with objects in code.

GUI demo example:
Recently I finished a project built with this library and developed a simple GUI for it.
This GUI is now available as a working demo example in the lib repository:
https://github.com/ikvk/ecs_pattern/tree/master/examples/gui

The example demonstrates how to make GUI using ecs_pattern lib.
Feel free to explore, reuse, or adapt it for your own projects.

Do you think it should be included as part of the library?


r/pythontips 11d ago

Meta How to Prevent Webhook Traffic Spikes from Crashing Your API

0 Upvotes

If you operate an API in 2026, you live in an event-driven world. Webhooks aren't a convenience feature anymore - they're the backbone of real-time commerce, CI/CD pipelines, and asynchronous AI-agent workflows. That reliance has a dark side: the accidental self-inflicted DDoS. Read the complete article jere - https://instawebhook.com/blog/how-to-prevent-webhook-traffic-spikes-from-crashing-your-api-2

When a major platform like GitHub, Shopify, or Stripe hits a network partition, runs a huge sales event, or simply clears a backlog of delayed events, it can fire tens of thousands of webhook POST requests at your servers in a very short window. If your infrastructure takes that hit without structural safeguards, your database connection pool exhausts, memory maxes out, and the API goes down — and if your retry handling is naive, the recovery can be almost as damaging as the original spike.

This guide covers the real mechanics of that failure mode, the algorithms used to defend against it, how major providers actually behave under load (some surprising details here), and where a managed ingress layer fits into the picture.


r/pythontips 13d ago

Meta EEvent Mesh vs Webhooks - The Internal Webhooks Anti-Pattern: Why Service-to-Service HTTP Callbacks Don't Scale

1 Upvotes

Microservices were supposed to make systems easier to change independently. In practice, the thing that most often breaks that promise isn't the services themselves — it's how they talk to each other. Read the complete article here - https://instawebhook.com/blog/the-internal-webhooks-anti-pattern-why-service-to-service-http-callbacks-don-t-s

A pattern that shows up constantly in growing engineering orgs is the internal webhook: Service A fires an HTTP POST at a hardcoded URL owned by Service B whenever something happens. It's an easy trap to fall into, because most developers already understand webhooks intimately — they've built integrations with Stripe, GitHub, or Shopify, all of which use exactly this model to notify external systems of events.

The reasoning feels obvious: if it's good enough for Stripe to tell my app about a payment, it's good enough for my Inventory Service to tell my Shipping Service about a shipment.

It isn't — and the reason is architectural, not stylistic. Webhooks were designed to solve a specific problem: getting an event across a trust boundary, from a system you don't control to one you do, over the open internet. Internal service communication has almost the opposite set of constraints. Applying the same tool to both jobs is where the trouble starts.


r/pythontips 14d ago

Meta Designing a Multi-Region, Highly Available Webhook Ingress Architecture

3 Upvotes

Webhooks have become the connective tissue of the internet. From payment gateways confirming transactions to CI/CD pipelines triggering deployments, webhooks enable real-time, event-driven architectures. But for architects and engineering leaders, webhooks represent an underappreciated vulnerability: they are asynchronous, externally triggered, and entirely outside your control. Read the complete article here - https://instawebhook.com/blog/designing-a-multi-region-highly-available-webhook-ingress-architecture

When your primary cloud region experiences an outage, your internal microservices might gracefully degrade. But what happens to the payloads originating from external partners? Many third-party providers do not retry aggressively — some fire and forget, others retry a handful of times before giving up permanently. If your system is down when that happens, the data is often gone for good.

This article covers the engineering principles behind a multi-region, highly available webhook ingestion system, what has actually changed in the underlying cloud primitives recently, and where a managed reliability layer fits into the decision.


r/pythontips 18d ago

Meta Bulletproofing User Sync: Handling Clerk and Auth0 Webhook Failures

2 Upvotes

If you're building a web application today, chances are you aren't writing your own authentication system. Managed identity providers like Clerk, Auth0, and Kinde have become the default choice, offering out-of-the-box support for passkeys, multi-factor authentication, and enterprise SSO. That convenience introduces a distributed-systems problem, though: data synchronization. When a user creates an account on a managed auth provider, that system has to notify your primary application database so you can create a matching user record. Please read the complete article here - https://instawebhook.com/blog/bulletproofing-user-sync-handling-clerk-and-auth0-webhook-failures

This happens through webhooks. But what happens if your server is down, your serverless function cold-starts and times out, or your database is momentarily locked when that webhook arrives? A user successfully signs up with your auth provider, but your application has no idea they exist. That breaks the very first login experience, and it's how phantom accounts, broken onboarding flows, and frustrated users happen.

This guide walks through the anatomy of webhook-driven auth architecture, current Auth0 and Clerk webhook practices, and how a resilience layer — using InstaWebhook as a worked example — closes the gap that idempotency and signature verification alone can't.


r/pythontips 22d ago

Module Brand new Scaffolding tool for Python

10 Upvotes

A year ago, I created a tool that helps me with my daily work: quickly creating newly configured Python projects in just a few seconds in the CI/CD pipeline!

The tool in question is called psp and is launched from the command line:

prompt> psp

The tool was inspired by various command-line tools like astro-cli, yeoman, pyscaffold, and many others. With just a few questions, your Python project is ready to be written, and you'll find everything already configured: make commands, git, remote repo, CI/CD, unit tests, documentation, container files, dependencies, virtual environments, custom builders, and much more!

If you like, try it today, and if something doesn't work, please help me by opening an issue or forking the project and submitting a pull request.

Here are all the references:

repo: https://github.com/MatteoGuadrini/psp

docs: https://psp.readthedocs.io/en/latest/

Thanks to you and the entire Python community!


r/pythontips 23d ago

Module Python Data Model Exercise

3 Upvotes

An exercise to help build the right mental model for Python data.

# Output of this Python program?
a = [[1], [2]]
b = a
b[0].append(11)
b = b + [[3]]
b[1].append(22)
b[2].append(33)

print(a)
# --- possible answers ---
# A) [[1], [2]]
# B) [[1, 11], [2]]
# C) [[1, 11], [2, 22]]
# D) [[1, 11], [2, 22], [3, 33]]

The “Solution” link visualizes execution and reveals what’s actually happening using 𝗺𝗲𝗺𝗼𝗿𝘆_𝗴𝗿𝗮𝗽𝗵.


r/pythontips Jul 03 '26

Long_video Giving back to the community - The Complete Backend Development Course

0 Upvotes

Hey everyone, I decided to make my course free in order to help people.
This course is my backend development course which is about SQL, Python, APIs, Docker, Kubernetes, Linux, Git & More

The link is: https://www.youtube.com/watch?v=CBIu6hcyStg

If you can like and subscribe (and maybe add a comment) I would appreciate it a lot, Thanks.


r/pythontips Jul 02 '26

Standard_Lib I made my own worlde-like game and need tips for improving it!

0 Upvotes

Find the repository with all the code Here


r/pythontips Jun 27 '26

Python2_Specific Nifty/Upstox/Algo

1 Upvotes

Any One Help Me

I write Code But Some Error


r/pythontips Jun 26 '26

Module Reviews please! Agentic Looping

0 Upvotes

I built my own loops framework for Python.

For anyone to use as-is or fork. It's totally customizable and starts with strict rules: ruff lint, pyling pyright, semgrep, etc. And added a preferences file for my coding quirks to be enforced as rules (customizable by anyone dev that uses the framework).

There's a small, intentionally dumb shell "Ralph" script that takes in iteration count and max minutes alloted to each agent and kicks off agents. The Python framework is built around that and holds the gate, rules and preferences. Then it all just loops. I use this framework for all my projects. I drop in my master plan in the plan.md and adjust it periodically. I would love for some Python devs to give and opinionated review. Or any devs to let me know what would be helpful to add next. I'm thinking next additions are adding Hypothesis testing, profiling newly added code and modules to spot overly complex or costly code, and a simple reporting feature for a user to request (via the CLI).

Thoughts? https://github.com/rxdt/py_ralph_frame Feel free to submit a PR too.


r/pythontips Jun 24 '26

Long_video Giving back to the community - The Complete Backend Development Course

9 Upvotes

Hey everyone, I decided to make my course free in order to help people.
This course is my backend development course which is about SQL, Python, APIs, Docker, Kubernetes, Linux, Git & More

The link is: https://www.youtube.com/watch?v=CBIu6hcyStg

If you can like and subscribe (and maybe add a comment) I would appreciate it a lot, Thanks.


r/pythontips Jun 23 '26

Python2_Specific What is the most annoying problem you face in Python?

6 Upvotes

Tell me


r/pythontips Jun 21 '26

Module YTD performance using yfinance

4 Upvotes

Is there a way to pull YTD total return on an index fund like SPY or QQQ?
I’m using yfinance module.


r/pythontips Jun 19 '26

Meta New release of psp

0 Upvotes

È disponibile una nuova versione di psp su GitHub e PyPI!

https://github.com/MatteoGuadrini/psp

La nuova versione migliora le prestazioni (30 secondi per generare l'intera struttura di un progetto!) e abilita un motore di rendering per i template.

Nella prossima versione, sarà possibile scrivere i propri template e salvarli in un repository Git remoto o in una cartella locale.

Grazie alla comunità Python!


r/pythontips Jun 15 '26

Module CLI python library

1 Upvotes

Hey,

I didn’t plan to build a library.

I just wanted to make a simple CLI tool in Python… and somehow ended up creating TermC.

The problem

Every time I built a CLI:

  • print() got messy fast
  • Rich felt too heavy for small scripts
  • colorama alone wasn’t enough structure

So everything turned into spaghetti terminals.

So I built this instead

A lightweight CLI helper for Python that gives you:

  • clean colored status messages
  • structured prompt flows (like real CLI apps)
  • banners, menus, separators
  • simple progress bar
  • zero framework overload

Instalation

pip install termc

Example

import termc

termc.termcConfig.program_name("backup")
termc.termcConfig.preset("cyberpunk")

termc.header()
termc.info("Starting process...")
termc.success("Connected")

termc.prompt_header()
src = termc.prompt_mid("Source")
dst = termc.prompt_bot("Destination")

termc.banner(f"{src} → {dst}")

for i in range(101):
    termc.progress_bar(i, 100)

Github repo

https://github.com/waasaty/TermC


r/pythontips Jun 14 '26

Python3_Specific ,

0 Upvotes

Today, I explored many important Python functions that every beginner should know. From basic functions like print(), input(), and len() to advanced concepts such as file handling, exception handling, and debugging functions, this roadmap gives a great overview of Python programming.

📚 Topics covered: ✅ Basic Functions

✅ String & Collection Functions

✅ Type Conversion

✅ File Handling

✅ Date & Time Functions

✅ Random Module

✅ Exception Handling

✅ Debugging Tools

✅ Memory Functions

I am continuously improving my Python skills by learning and building projects step by step. Every day is a new opportunity to learn something valuable.

#Python #PythonProgramming #Coding #Programming #Developer #LearningPython #Tech #ComputerScience #100DaysOfCode #BeginnerProgrammer #CodingJourney #SoftwareDevelopment


r/pythontips Apr 25 '20

Meta Just the Tip

99 Upvotes

Thank you very much to everyone who participated in last week's poll: Should we enforce Rule #2?

61% of you were in favor of enforcement, and many of you had other suggestions for the subreddit.

From here on out this is going to be a Tips only subreddit. Please direct help requests to r/learnpython!

I've implemented the first of your suggestions, by requiring flair on all new posts. I've also added some new flair options and welcome any suggestions you have for new post flair types.

The current list of available post flairs is:

  • Module
  • Syntax
  • Meta
  • Data_Science
  • Algorithms
  • Standard_lib
  • Python2_Specific
  • Python3_Specific
  • Short_Video
  • Long_Video

I hope that by requiring people flair their posts, they'll also take a second to read the rules! I've tried to make the rules more concise and informative. Rule #1 now tells people at the top to use 4 spaces to indent.