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
Trying to use Google Drive to Store Media Files, But Getting "Service Accounts do not have storage quota" error when uploading

I'm building a Django app and I'm trying to use Google Drive as storage for media files via a service account, but I'm encountering a storage quota error.

# What I've Done

Set up a project in Google Cloud Console
Created a service account and downloaded the JSON key file
Implemented a custom Django storage backend using the Google Drive API v3
Configured GOOGLE_DRIVE_ROOT_FOLDER_ID in my settings

# The Error

When trying to upload files, I get:

HttpError 403: "Service Accounts do not have storage quota. Leverage shared drives
(https://developers.google.com/workspace/drive/api/guides/about-shareddrives),
or use OAuth delegation instead."

# What I've Tried

1. Created a folder in my personal Google Drive (regular Gmail account)
2. Shared it with the service account email (the client_email from the JSON file) with Editor permissions
3. Set the folder ID as GOOGLE_DRIVE_ROOT_FOLDER_ID in my Django settings

This is the code of the storage class:

```

# The original version of the code
# https://github.com/torre76/django-googledrive-storage/blob/master/gdstorage/storage.py
Copyright (c) 2014, Gian Luca Dalla Torre
All rights reserved.
"""

import enum
import json


/r/django
https://redd.it/1o5f3tr
gRPC: Client side vs Server side load balancing, which one to choose?

Hello everyone,
My setup: Two FastAPI apps calling gRPC ML services (layout analysis + table detection). Need to scale both the services.

Question: For GPU-based ML inference over gRPC, does NGINX load balancing significantly hurt performance vs client-side load balancing?

Main concerns:

* Losing HTTP/2 multiplexing benefits
* Extra latency (though probably negligible vs 2-5s processing time)
* Need priority handling for time-critical clients

Current thinking: NGINX seems simpler operationally, but want to make sure I'm not shooting myself in the foot performance-wise.

Experience with gRPC + NGINX? Client-side LB worth the complexity for this use case?

/r/Python
https://redd.it/1o5kwve
Parsegument! - Argument Parsing and function routing

Project Source code: https://github.com/RyanStudioo/Parsegument

Project Docs: https://www.ryanstudio.dev/docs/parsegument/

# What My Project Does
Parsegument allows you to easily define Command structures with Commands and CommandGroups.
Parsegument also automatically parses arguments, converts them to your desired type, then executes functions automatically, all with just one method call and a string.

# Target Audience
Parsegument is targetted for people who would like to simplify making CLIs. I started this project as I was annoyed at having to use lines and lines of switch case statements for another project I was working on

# Comparison
Compared to python's built in argparse, Parsegument has a more intuitive syntax, and makes it more convenient to route and execute functions.

This project is still super early in development, I aim to add other features like aliases, annotations, and more suggestions from you guys!

/r/Python
https://redd.it/1o5jkb9
Use cases of Django vs NodeJS

Hey I have only really done websites in React + NodeJS + “express” package in NodeJS. I know very little about Django.
I was wondering the use cases or the situations where Django would be better to use than NodeJs.
Also if you could explain the differences in performance btwn Django and NodeJs too.

I’d need the advice pretty soon like by one or two days from now

/r/djangolearning
https://redd.it/1o43b73
ChanX: The Django WebSocket Library I Wish Existed Years Ago

Django Channels is excellent for WebSocket support, but after years of using it, I found myself writing the same boilerplate patterns repeatedly: routing chains, validation logic, and documentation. ChanX is a higher-level framework built on top of Channels to handle these common patterns automatically.

# The Problem

If you've used Django Channels, you know the pain:

https://preview.redd.it/1uhc8l973xuf1.png?width=996&format=png&auto=webp&s=913508d7488031446d8c5044132d449ddd770c0f

Plus manual validation everywhere, no type safety, and zero automatic documentation. Unlike Django REST Framework, Channels leaves you building everything from scratch.

# The Solution

Here's what the same consumer looks like with ChanX:

https://preview.redd.it/ymmxw1f93xuf1.png?width=1036&format=png&auto=webp&s=9a156365fcfe57b9ebec78892454619ca47705aa

**What you get:**

* Automatic routing with Pydantic validation - no if-else chains
* Full type safety with mypy/pyright - catch errors before runtime
* Auto-generated AsyncAPI 3.0 docs - like Swagger for WebSockets
* Event broadcasting from anywhere - HTTP views, Celery tasks, etc.
* Built-in authentication with Django permissions
* Structured logging and comprehensive testing utilities
* Works with both Django Channels and FastAPI

**Comparison with other solutions:** See how ChanX compares to raw Django Channels, Broadcaster, and Socket.IO at [https://chanx.readthedocs.io/en/latest/comparison.html](https://chanx.readthedocs.io/en/latest/comparison.html)

# Tutorial for Beginners

I wrote a hands-on tutorial that builds a real chat app with AI assistants, notifications, and background tasks. It uses a Git repo with checkpoints so you can jump in anywhere or compare your code if you get stuck.

Tutorial:

/r/django
https://redd.it/1o5qvcj
Newbie question — which hosting is best for a small Django + Next.js e-commerce site?

Hi everyone, I’m a total newbie so please be kind if this is a basic question 😅

I’m currently learning Python Django from a book (I have zero coding background) and also experimenting with Claude-Code. My goal is to build and deploy a small e-commerce website using Django (backend) and Next.js (frontend). (Australia mel)

Here’s my situation:

Daily users: about 500

Concurrent users: around 100


I want to deploy it for commercial use, and I’m trying to decide which hosting option would be the most suitable. I’m currently considering:

DigitalOcean

Vercel + Railway combo

Google Cloud Run


If you were me, which option would you choose and why? I’d love to hear advice from more experienced developers — especially any tips on cost, performance, or scaling. 🙏

I'm considering price or easy use ai or easy deploy

Thanks for reading my long sentence post


/r/django
https://redd.it/1o5589y
Tuesday Daily Thread: Advanced questions

# Weekly Wednesday Thread: Advanced Questions 🐍

Dive deep into Python with our Advanced Questions thread! This space is reserved for questions about more advanced Python topics, frameworks, and best practices.

## How it Works:

1. **Ask Away**: Post your advanced Python questions here.
2. **Expert Insights**: Get answers from experienced developers.
3. **Resource Pool**: Share or discover tutorials, articles, and tips.

## Guidelines:

* This thread is for **advanced questions only**. Beginner questions are welcome in our [Daily Beginner Thread](#daily-beginner-thread-link) every Thursday.
* Questions that are not advanced may be removed and redirected to the appropriate thread.

## Recommended Resources:

* If you don't receive a response, consider exploring r/LearnPython or join the [Python Discord Server](https://discord.gg/python) for quicker assistance.

## Example Questions:

1. **How can you implement a custom memory allocator in Python?**
2. **What are the best practices for optimizing Cython code for heavy numerical computations?**
3. **How do you set up a multi-threaded architecture using Python's Global Interpreter Lock (GIL)?**
4. **Can you explain the intricacies of metaclasses and how they influence object-oriented design in Python?**
5. **How would you go about implementing a distributed task queue using Celery and RabbitMQ?**
6. **What are some advanced use-cases for Python's decorators?**
7. **How can you achieve real-time data streaming in Python with WebSockets?**
8. **What are the

/r/Python
https://redd.it/1o60ghk
ChanX: Type-Safe WebSocket Framework for Django and FastAPI

# What My Project Does

ChanX is a batteries-included WebSocket framework that works with both Django Channels and FastAPI. It eliminates the boilerplate and repetitive patterns in WebSocket development by providing:

Automatic message routing using Pydantic discriminated unions - no more if-else chains
Type safety with full mypy/pyright support and runtime Pydantic validation
Auto-generated AsyncAPI 3.0 documentation - like OpenAPI/Swagger but for WebSockets
Channel layer integration for broadcasting messages across servers with Redis
Event system to trigger WebSocket messages from anywhere in your application (HTTP views, Celery tasks, management commands)
Built-in authentication with Django REST framework permissions support
Comprehensive testing utilities for both frameworks
Structured logging with automatic request/response tracing

The same decorator-based API works for both Django Channels and FastAPI:

from typing import Literal
from chanx.messages.base import BaseMessage
from chanx.core.decorators import wshandler, channel
from chanx.channels.websocket import AsyncJsonWebsocketConsumer # Django
# from chanx.fast
channels.websocket import AsyncJsonWebsocketConsumer # FastAPI

class ChatMessage(BaseMessage):
action: Literal"chat" = "chat"
payload: str

(name="chat")


/r/Python
https://redd.it/1o5ro8i
Pyrefly eats CPU like nobodies business.

So I recently tried out the pyrefly and the ty typecheckers/LSPs in my project for ML. While ty wasn't as useful with it's errors and imports, pyrefly was great in that department. Only problem with the latter was that it sent CPU use to near 100% the whole time it ran.

This was worse than even rust-analyzer, notorious for being a heavy-weight tool, which only uses a ton of CPU on startup but works on low CPU throughout but using a ton of RAM.

Is there some configuration for pyrefly I was missing or is this a bug and if it's the latter should I report it?

Or even worse, is this intended behavior? If so, pyrefly will remain unusable to anyone without a really beefy computer making it completely useless for me. Hopefully not thought, cause I can't have an LSP using over 90% CPU while it runs in background running on my laptop.

/r/Python
https://redd.it/1o66tho
I built JSONxplode a complex json flattener

I built this tool in python and I hope it will help the community.

This code flattens deep, messy and complex json data into a simple tabular form without the need of providing a schema.

so all you need to do is: from jsonxplode import flatten flattened_json = flatten(messy_json_data)

once this code is finished with the json file none of the object or arrays will be left un packed.

you can access it by doing: pip install jsonxplode

code and proper documentation can be found at:

https://github.com/ThanatosDrive/jsonxplode

https://pypi.org/project/jsonxplode/



in the post i shared at the data engineering sub reddit these were some questions and the answers i provided to them:

why i built this code? because none of the current json flatteners handle properly deep, messy and complex json files without the need of having to read into the json file and define its schema.

how does it deal with some edge case scenarios of eg out of scope duplicate keys? there is a column key counter that increments the column name if it notices that in a row there is 2 of the same columns.

how does it deal with empty values does it do a none or a blank string? data is returned as a list of dictionaries

/r/Python
https://redd.it/1o69cvi
How to use annotate for DB optimization

Hi, I posted a popular comment to a post a couple days ago asking what some advanced Django topics to focus on are: https://www.reddit.com/r/django/comments/1o52kon/comment/nj6i2hs/?utm\_source=share&utm\_medium=web3x&utm\_name=web3xcss&utm\_term=1&utm\_content=share\_button

I mentioned annotate as being low hanging fruit for optimization and the top response to my comment was a question asking for details about it. Its a bit involved to respond to that question, and I figured it would get lost in the archive, so this post is a more thorough explanation of the concept that will reach more people who want to read about it.

Here is an annotate I pulled from real production code that I wrote a couple years ago while refactoring crusty 10+ year old code from Django 1.something:

def cities(self, location=None, filtervalue=None):
entity
locationlookup = {f'{self.cityfieldlookup()}id': OuterRef('pk')}
cities = City.objects.annotate(
has
activeentities=Exists(
self.get
queryset().filter(entitylocationlookup),
),
).filter(hasactiveentities=True)



/r/django
https://redd.it/1o6jepy
How to prevent TransactionTestCase from truncating all tables?

For my tests, I copy down the production database, and I use the liveserver test case because my frontend is an SPA and so I need to use playwright to have a browser with the tests.

The challenge is that once the liveserver testcase is done, all my data is blown away, because as the docs tell us, "A TransactionTestCase resets the database after the test runs by truncating all tables."

That's fine for CI, but when testing locally it means I have to keep restoring my database manually. Is there any way to stop it from truncating tables? It seems needlessly annoying that it truncates *all* data!

I tried serialized_rollback=True, but this didn't work. I tried googling around for this, but most of the results I get are folks who are having trouble because their database is *not* reset after a test.

/r/django
https://redd.it/1o6ky68
Tutorial: Building Real-Time WebSocket Apps with Django Channels and ChanX

Hi everyone, I created a hands-on tutorial for learning how to build WebSocket applications with Django Channels using modern best practices. If you're interested in adding real-time features to your Django projects or learning about WebSockets, this might help.

# What You'll Build

The tutorial walks you through building a complete real-time chat application with multiple features:

Real-time chat functionality with message broadcasting
AI assistant chat system with streaming responses
Notification system that updates in real-time
Background task processing with WebSocket notifications
Complete testing setup for WebSocket endpoints

# What You'll Learn

Throughout the tutorial, you'll learn:

Setting up Django Channels with Redis
Creating WebSocket consumers with automatic message routing
Using Pydantic for type-safe message validation
Broadcasting messages to groups of users
Handling channel layer events
Testing WebSocket consumers properly
Generating automatic API documentation for WebSockets

# Tutorial Structure

The tutorial uses a Git repository with checkpoints at each major step. This means you can:

Start from any point if you're already familiar with basics
Compare your code with the reference implementation
Reset to a checkpoint if you get stuck
See exactly what changes at each step

Tutorial link: https://chanx.readthedocs.io/en/latest/tutorial-django/prerequisites.html

# About ChanX

The tutorial uses ChanX, which is a framework I built on top of Django Channels to

/r/djangolearning
https://redd.it/1o5rgd5
D Only 17 days given to review 5 papers in ICLR 2026...

The paper assignments for ICLR 2026 are in today and I was assigned 5 papers to review. The review deadline is 31st October. I am not sure if this is the normal time period but seems very little. Last year I was assigned 2 papers and was able to write detailed and constructive reviews.

/r/MachineLearning
https://redd.it/1o6hs2w
Fermi Paradox Flask App

I was going through some older GitHub repos last week and found an early python program I put together. It was a tutorial from a book. It was on Fermi's Paradox. As I looked through it, it was TERRIBLE!!! No imports, not modular, completely done in the CLI. It was cool to see how far I have come. So, I decided to refactor into a flask app. I have it at MVP right now. Still a work in progress, but would love to hear what people think!!

Live App: https://fermi-paradox-project.com/

/r/flask
https://redd.it/1o6j7uy
D Why are Monte Carlo methods more popular than Polynomial Chaos Expansion for solving stochastic problems?

I feel like MC methods are king for reinforcement learning and the like, but PCE’s are often cited as being more accurate and efficient. Recently while working on some heavy physics focused problems I’ve found a lot of the folks in Europe use more PCE. Anyone have any thoughts as to why one is more popular? If you want to do a fun deep dive - polynomial chaos (or polynomial chaos expansion) have been a fun random stats deep dive.

/r/MachineLearning
https://redd.it/1o62zfe
starting a new project with flasksecurity and flasksqlalchemylite

I have done several flask projects in the past, so I am not a rookie. I recently started a new project that requires role-based access control with fine-grained permissions, so I naturally thought about using flask\
security now that it is a pallets project. I am also planning to use flask_sqlalchemy_lite (NOT flask_sqlalchemy). I've built some parts of it, but when I went to build tests I could not get them to work so I went looking for examples in github of real world applications that use flask_security with roles and I found precisely none. I spent an hour or so trying to get copilot to construct some tests, and it was completely confused by the documentation for flask_sqlalchemy and flask_sqlalchemy_lite so it kept recommending code that doesn't work. The complete lack of training data is probably the problem here and the confusingly close APIs that are incompatible.

This has caused me to question my decision to use flask at all, since the support libraries for security and database are so poorly documented and apparently have no serious apps that use them. I'm now thinking of going with django instead. Does anyone know of a real-world example that uses the combination of

/r/flask
https://redd.it/1o6w7e6
kernel dying

/r/JupyterNotebooks
https://redd.it/1o6za17