Python Daily
2.57K subscribers
1.48K photos
53 videos
2 files
38.9K links
Daily Python News
Question, Tips and Tricks, Best Practices on Python Programming Language
Find more reddit channels over at @r_channels
Download Telegram
Monkey patching contenttypes to register millions of models

I'm building a Notion/Airtable like application where a User(Workspace) would create tables dynamically during runtime - which means migrations will also need to happen during runtime(using SchemaEditor API).

I'm new to Django and would love to understand what's the best way to handle the model registry. The scale that I'm designing for is - 500k workspaces * 5 tables per ws(avg) = 2.5 M tables in my postgres DB.

I checked out the contenttypes source code and they are loading an in-memory cache for fast lookups. My current solution is to monkey-patch The `ContentTypeManager` to use in-memory(limited)+Redis cache.

However, I'm not confident if this is the best approach or would it cause unintended side-effects for django-admin, permissions, etc.

Thank you!

/r/django
https://redd.it/1nccuk8
Is Django (DRF) actually RESTful?

I’ve been using Django REST Framework to build my first single-page application after having worked mostly with traditional server-side rendered Django apps. But I’ve noticed that Django, by default, has many features that don’t seem to align with RESTful principles, like the session middleware that breaks everything if you don't use it and django-allauth’s reliance on sessions and SSR patterns, even when used in “headless” mode. These features feel so deeply ingrained in Django’s architecture that making a DRF API fully RESTful feels clunky to me.

Since I’m new to SPAs and the general architecture of them, I’m wondering if I might be approaching this the wrong way, or if I’ve misunderstood DRF’s purpose. Am I doing something wrong in development to make DRF APIs so clunky, or is it just better suited for hybrid SSR/SPA apps?

/r/django
https://redd.it/1ncjj9c
Flask Self Hosted Portfolio Project With Interactive Screen and Servo on Raspberry Pi Pro

/r/flask
https://redd.it/1ncnlwf
I created a pretty-printed dir function to make debugging complex classes easier

What My Project Does

You can check it out on github: https://pypi.org/project/pretty-dir/

This library generates a better dir output for debugging. For a quick example, check out the with dir and with ppdir outputs using a simple pydantic model.


Target Audience

This is mainly aimed at developers who are debugging code that uses any libraries that have large, complex, deeply nested classes. Libraries such as pydantic, dataclasses, and openpyxl.

Comparison

It exists in a similar niche as icecream and rich.inspect where it's meant to improve the debugging experience. Unlike similar libraries, this only shows the structure, not the values themselves. This is valuable in pydantic environments, where instances can be too verbose to be meaningful when printed to the console.

Details

The library uses the output of the dir(obj) function as a baseline, but improves the output in a number of ways:

Visually groups the methods and attributes by the classes they were defined on. Therefore, if you're subclassing the [pydantic.BaseModel](https://docs.pydantic.dev/latest/api/base_model/) class, it separates the generic basemodel methods from the subclass' specific methods.
Pulls the first line of the docstrings for the class, all methods, and all class attributes.
Can enable showing the function signature for all class methods
By default, hides private and and dunder methods

/r/Python
https://redd.it/1nd1go9
This site is run on a flask backend

https://cognity.space/

Optimized as much as I can. I'd like to hear your thoughts.

/r/flask
https://redd.it/1ncsuef
How to deploy Flask and React+Vite web app - newbie

Hi! I've watched a lot of YT video tutorials on how to deploy and I'm still lost. Most of them are just quick demonstrations with one page and some are just hard to follow. My web app is developed using Flask for the backend and React+Vite for the frontend. Initially, the plan is to deploy the backend on Render and the frontend on Vercel but I saw a tutorial that you can bundle both so it only runs on one server although I can't follow the tutorial because mine has multiple pages and has no database (I tried to use In-memory). To be honest with ya'll, this is my first time doing web development and I had fun doing the project -- I just want to try it out and see it through from start to finish.

Any help is appreciated. Videos, articles,, github repos, or maybe a simple comment here but highly appreciate a step-by-step instructions because like I said just a newbie.

Thank you in advance!

/r/flask
https://redd.it/1ncfjua
D SOTA modern alternative to BertScore?

Hi everyone,
I’m looking for an embedding-based metric to score text generation. BertScore is great, but it’s a bit outdated. Could you suggest some modern state-of-the-art alternatives?



/r/MachineLearning
https://redd.it/1ndaesz
I decoupled FastAPI dependency injection system in pure python, no dependencies.

What My Project Does

When building FastAPI endpoints, I found the dependency injection system such a pleasure to use that I wanted it everywhere, not just in my endpoints. I explored a few libraries that promised similar functionality, but each had drawbacks, some required Pydantic, others bundled in features beyond dependency injection, and many were riddled with bugs.

That's way I created PyDepends, a lightweight dependency injection system that I now use in my own projects and would like to share with you.

Target Audience
This is mainly aimed at:

FastAPI developers who want to use dependency injection in the service layer.

Domain-Driven Design practitioners who want to decouple their services from infrastructure.

Python developers who aren’t building API endpoints but would still like to use dependency injection in their projects.
It’s not production-grade yet, but it’s stable enough for everyday use and easy to extend.

Comparison

Compared to other similar packages, it does just that, inject dependencies, is not bloated with other functionalities.

FastDepends: I started out with this for another library I was using but had to ditch it because of the bugs. I even opened a pull request fixing the issue, but it wasn’t taken into account. It also

/r/Python
https://redd.it/1ndj5vz
A Complete List of Python Tkinter Colors, Valid and Tested

I needed a complete list of valid color names for Python's Tkinter package as part of my ButtonPad GUI framework development. The lists I found on the internet were either incomplete, buried under ads, and often just plain wrong. Here's a list of all 760 color names (valid and personally tested) for Python Tkinter.

https://inventwithpython.com/blog/complete-list-tkinter-colors-valid-and-tested.html

/r/Python
https://redd.it/1ndnusy
Manager wants me to present a “deep dive” learning module for Django

So I’ve recently started to learn and work with Django and I’ve learned enough to get by and work on features.

But now my manager wants me to dive in and present more in depth concepts of Django that my peers can learn from, I’d appreciate some articles or resources that are outside the surface level documentation that I’ve read upon.

This is what he has written in my goals sheet:

“Complete a deep-dive learning module on Django internals or system-level design”

Any help/guidance will be appreciated!

/r/django
https://redd.it/1ndghdj
Flask-React: Server-Side React Component Rendering Extension

I'd like to share a Flask extension I've been working on that brings server-side React component rendering to Flask applications with template-like functionality.

**Flask-React** is a Flask extension that enables you to render React components on the server-side using Node.js, providing a bridge between Flask's backend capabilities and React's component-based frontend approach. It works similarly to Jinja2 templates but uses React components instead.

### Key Features

- **Server-side React rendering** using Node.js subprocess for reliable performance
- **Template-like integration** with Flask routes - pass props like template variables
- **Jinja2 template compatibility** - use React components within existing Jinja2 templates
- **Component caching** for production performance optimization
- **Hot reloading** in development mode with automatic cache invalidation
- **Multiple file format support** (.jsx, .js, .ts, .tsx)
- **CLI tools** for component generation and management

### Quick Example

```python
from flask import Flask
from flask_react import FlaskReact

app = Flask(__name__)
react = FlaskReact(app)

@app.route('/user/<int:user_id>')
def user_profile(user_id):
user = get_user(user_id)
return react.render_template('UserProfile',
user=user,
current_user=g.current_user,
can_edit=user_id == g.current_user.id
)
```

```jsx
// components/UserProfile.jsx
function UserProfile({ user, current_user, can_edit }) {
return (
<div>


/r/flask
https://redd.it/1ndrhnk
Confused in queryset

Well I am new in django... And learning about queryset..... But don't know how the relationship and access field is working....


Kindly provide some blogs , links


/r/djangolearning
https://redd.it/1ndhcuq
Thursday Daily Thread: Python Careers, Courses, and Furthering Education!

# Weekly Thread: Professional Use, Jobs, and Education 🏢

Welcome to this week's discussion on Python in the professional world! This is your spot to talk about job hunting, career growth, and educational resources in Python. Please note, this thread is not for recruitment.

---

## How it Works:

1. Career Talk: Discuss using Python in your job, or the job market for Python roles.
2. Education Q&A: Ask or answer questions about Python courses, certifications, and educational resources.
3. Workplace Chat: Share your experiences, challenges, or success stories about using Python professionally.

---

## Guidelines:

- This thread is not for recruitment. For job postings, please see r/PythonJobs or the recruitment thread in the sidebar.
- Keep discussions relevant to Python in the professional and educational context.

---

## Example Topics:

1. Career Paths: What kinds of roles are out there for Python developers?
2. Certifications: Are Python certifications worth it?
3. Course Recommendations: Any good advanced Python courses to recommend?
4. Workplace Tools: What Python libraries are indispensable in your professional work?
5. Interview Tips: What types of Python questions are commonly asked in interviews?

---

Let's help each other grow in our careers and education. Happy discussing! 🌟

/r/Python
https://redd.it/1ndua5j
Streamlit for python apps

i’ve been using streamlit lately and honestly it’s pretty nice, so just wanted to share in case it helps someone.

if you’re into data analysis or working on python projects and want to turn them into something interactive, streamlit is definitely worth checking out. it lets you build web apps super easily — like you just write python code and it handles all the front-end stuff for you.

you can add charts, sliders, forms, even upload files, and it all works without needing to learn html or javascript. really useful if you want to share your work with others or just make a personal dashboard or tool.

feels like a good starting point if you’ve been thinking about making web apps but didn’t know where to start.

/r/Python
https://redd.it/1ndsuud
Python VS Power BI

Why use python (streamlit =(easy but limited), dash=(complex)) for data visualization when there is power bi and tableau ?

/r/Python
https://redd.it/1ne2g15
Need help for integrating python model to mern stack project

Hello, I am building a ai therapist as my college project and for that I want to integrate python sentiment analysis model into my application.The idea of my webapp is that users can ask a therapy query to ai and the sentiment analysis model will identify the user sentiment and sent the query to gpt model which will then send the response back in chat.Can someone please guide me on the integration.

/r/flask
https://redd.it/1ndbvqa
How to use JWT tokens stored in cookies for evey API requests

I'm using Django template and htmx for the frontend. I'm facing an issue of getting the tokens stored in the cookies to the API. The cookies are stored, but the API doesn't get them. I checked the internet, but I couldn't find one that explains it.

class CustomTokenObtainApiView(TokenObtainPairView):
    def post(self, request, *args, **kwargs):
        serializer = self.get_serializer(data = request.data)
        serializer.is_valid(raise_exception = True)
        tokens = serializer.validated_data

        response = Response({'details': 'login successful'})

        response.set_cookie(
            'access_token', tokens['access'], httponly=True, secure=False, samesite='lax'
        )
        response.set_cookie(
            'refresh_token', tokens['refresh'], httponly=True, secure=False, samesite='lax'
        )
        response["HX-Redirect"] = "/homepage/"
        return response



Here

/r/django
https://redd.it/1ne37xz
detroit: Python implementation of d3js

Hi, I am the maintainer of detroit. detroit is a Python implementation of the library d3js. I started this project because I like how flexible data visualization is with d3js, and because I'm not a big fan of JavaScript.

You can find the documentation for detroit here.

Target Audience

`detroit` allows you to create static data visualizations. I'm currently working on [detroit-live](
https://github.com/bourbonut/detroit-live) for those who also want interactivity. In addition, `detroit` requires only [lxml](https://lxml.de/) as dependency, which makes it lightweight.

You can find a gallery of examples in the [documentation](
https://detroit.readthedocs.io/en/latest/#gallery). Most of examples are directly inspired by [d3js examples on observablehq](https://observablehq.com/@d3/gallery).

Comparison

The API is almost the same:

// d3js
const scale = d3.scaleLinear().domain(0, 10).range(0, 920);
console.log(scale.domain()) // 0, 10

# detroit
scale = d3.scalelinear().setdomain(0, 10).setrange([0, 920])
print(scale.get
domain()) # 0, 10

The difference between d3js/detroit and matplotlib/plotly/seaborn is the approach to data visualization. With matplotlib, plotly, or seaborn, you only need to write a few lines and that's it - you get your visualization. However, if you want to customize some parts, you'll have to add a couple more lines, and it can

/r/Python
https://redd.it/1ne4t1d
DNVIDIA Blackwell Ultra crushes MLPerf

NVIDIA dropped MLPerf results for Blackwell Ultra yesterday. 5× throughput on DeepSeek-R1, record runs on Llama 3.1 and Whisper, plus some clever tricks like FP8 KV-cache and disaggregated serving. The raw numbers are insane.

But I wonder though . If these benchmark wins actually translate into lower real-world inference costs.

In practice, workloads are bursty. GPUs sit idle, batching only helps if you have steady traffic, and orchestration across models is messy. You can have the fastest chip in the world, but if 70% of the time it’s underutilized, the economics don’t look so great to me. IMO

/r/MachineLearning
https://redd.it/1ndo5md