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
Beginner learning - Function base or Class Base approach

English isn't my first language, so sorry about the grammar, and weird way organize sentence. I end up here is because after researching the community for Django I find out the English community were way more helpful.

Goal for learning Django : Planning to learn the Django fundamental and fully understand the idea of how it's work, not just using it by following other's tutorial making stuff. I want to reach the level that I can only using documents and my brain to create something I like.

Background :
\- 6 months in my self-taught journey, knowing all basic fundamental concepts and syntax of Python, HTML, CSS, Javascript. Mainly trying to focusing on the backend. For Django I had follow their tutorial, and recently I'm read the book "Django for Beginners(5th Edition)"

Problem:
\- I can see the benefit of Class-base approach more fit into DRY principle.

\- BUT ! I had a feeling that I'm not fully get the idea of class, class inheritance or the idea of OOP. I think I understand the concepts of class , but when come to using it. It's always had the unsure what I'm doing.

\- So, for beginning of the Django learning

/r/djangolearning
https://redd.it/1ixlqjb
Connecting a Ubuntu server to a webpage using flask

I’ve been trying to connect a python code on a web sever to a webpage, and the main way I’ve tried this was flask. I believe I set everything up correctly, but no luck. If anyone has a good tutorial on how to complete this properly it will be appreciated.

/r/flask
https://redd.it/1iwtccd
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/1ixh4qh
I made a script to download Spotify playlists without login

Repo link: https://github.com/invzfnc/spotify-downloader

What my project does
Hi everyone! I created a lightweight script that lists tracks from a public Spotify playlist and downloads them from YouTube Music.

Key Features

No premium required
No login or credentials required
Metadata is embedded in downloaded tracks
Downloads in higher quality (around 256 kbps)

Comparison/How is it different from other tools?
I found many tools requiring users to sign up for Spotify Developer account and setup credentials before everything else. This script uses the public Spotify API to retrieve track details, so there's no need to login or setup!

How's the music quality?
YouTube Music offers streams with higher bitrate (around 256 kbps) compared to YouTube (128 kbps). This script chooses and downloads the best quality audio from YouTube Music without taking up too much storage space.

Dependencies/Libraries?
Users are required to install innertube, SpotAPI, yt-dlp and FFmpeg for this script to work.

Target audience
Anyone who is looking to save their Spotify playlists to local storage, without wanting to login to any platform, and wants something with decent bitrate (\~256 kbps)

If you find this project useful or it helped you, feel free to give it a star! I'd really appreciate any feedback!

/r/Python
https://redd.it/1ixlsux
Anybody know how to add an Async view to a DRF project .

because simply declaring the @api_view function as async and awaiting statements inside it doesn't work and it clashes with event loops .

/r/djangolearning
https://redd.it/1ix63w0
Anyone used UV package manager in production

Is it reliable to use it in production as it is comparatively new in the market.

Also has it any disadvantages that i should be aware of before pitching it to my manager.

Help would be appreciated.

Any other tool suggestions also appreciated

/r/Python
https://redd.it/1ixryec
Session not being saved by the time a redirect happens

I have a React app that connects to a flask backend and I am trying to connect to the google calendar api. When I go to /login it redirects to /callback and I get the error: session state is missing. However, if I try to login after this, the login works. Does anyone have any advice on why the session is not being updated by the time the redirect happens?
Here are the functions in question:

app.config"SESSION_TYPE" = "filesystem"
app.config"SESSION_PERMANENT" = False
app.config"SESSION_USE_SIGNER" = True # Helps prevent tampering
app.config"SECRET_KEY" = secrets.tokenurlsafe(16)

Session(app)

@app.route("/login")
def login():
try:
authorization
url, state = getflow().authorizationurl()
print(f"Generated state: {state}")
session"state" = state
session.modified = True



/r/flask
https://redd.it/1iwr13r
Django is love, Django is life

College student here who has been using Django for almost 3 years now. I've built a couple solid projects, with one that has a healthy number of users (like 100-120 daily). Idk why, but I never meet other CS students at my school that use this framework. I go to an SEC school, though, so not like it's a bunch of serious development enthusiasts, but still. I preach it like it's my religion. I've gotten so invested in building little tools for it (e.g., base classes centered around general CRUD operations, dynamic serializers, etc.). I swear I'm a wizard at the ORM at this point, too (still have yet to see an ORM that I like even a fraction as much). I absolutely love this framework.

I routinely try to convince myself to branch out and try other things, but I just can't escape Django. I hate NextJS (I don't subscribe much to the JS-for-everything obsession) and most other things just have so little out-of-the-box functionality. The only other thing I've been able to truly appreciate is SpringBoot just due to its similar level of maturity, but I just don't feel like getting good at Java dependency management.



/r/django
https://redd.it/1ixn22y
Is Using Django with Vanilla JavaScript Unusual? Seeking Advice for Freelance Full Stack Development

Hey everyone!

I recently completed CS50 Web and decided to dive into my first freelance project using Django and vanilla JavaScript. My goal was to build a Single Page Application (SPA) with dynamic functionality, but as I progressed, I realized I might be taking an unconventional approach. Here’s what I’ve been doing:

No JavaScript Framework: I’m sticking to vanilla JavaScript instead of using React, Vue, or Angular.
No Django Rest Framework (DRF): I’m building my APIs without DRF, relying on Django’s built-in capabilities.
PDF Generation with `window.print`: Instead of using a library, I’m using `window.print` to generate PDFs.
Desktop App Conversion: Late in development, I decided to turn the web app into a desktop app using Electron and PyInstaller.

While this approach has been a great learning experience, I can’t help but wonder if I’m reinventing the wheel or missing out on best practices.

My Questions for the Community:

1. Is using vanilla JavaScript with Django a bad idea for SPAs, or is it a valid approach for smaller projects?
2. Should I reconsider using DRF for APIs, or is Django’s built-in functionality sufficient?
3. Are there better alternatives for PDF generation and desktop app conversion that I should explore?
4. As I aspire to become a decent Full Stack Web Dev for freelance

/r/django
https://redd.it/1iy17yb
Tach - Visualize + Untangle your Codebase

Hey everyone! We're building Gauge, and today we wanted to share our open source tool, [Tach](https://github.com/gauge-sh/tach), with you all.

**What My Project Does**

[Tach](https://github.com/gauge-sh/tach) gives you visibility into your Python codebase, as well as the tools to fix it. You can instantly visualize your dependency graph, and see how modules are being used. Tach also supports enforcing first and third party dependencies and interfaces.

Here’s a quick demo: [https://www.youtube.com/watch?v=ww\_Fqwv0MAk](https://www.youtube.com/watch?v=ww_Fqwv0MAk)

[Tach](https://github.com/gauge-sh/tach) is:

* Open source (MIT) and completely free
* Blazingly fast (written in Rust 🦀)
* In use by teams at NVIDIA, PostHog, and more

As your team and codebase grows, code get tangled up. This hurts developer velocity, and increases cognitive load for engineers. Over time, this silent killer can become a show stopper. Tooling breaks down, and teams grind to a halt. My co-founder and I experienced this first-hand. We're building the tools that we wish we had.

With [Tach](https://github.com/gauge-sh/tach), you can visualize your dependencies to understand how badly tangled everything is. You can also set up enforcement on the existing state, and deprecate dependencies over time.

**Comparison** One way [Tach](https://github.com/gauge-sh/tach) differs from existing systems that handle this problem (build systems, import linters, etc) is in how quick and easy it is to adopt incrementally. We provide a

/r/Python
https://redd.it/1ixz0tk
How to Learn Django for Backend Development & Valuable Project Ideas?

Hey everyone,

I'm a CS student interested in backend development and want to learn Django as quickly as possible. My goal is to build job-ready skills and work on projects that add real value to my CV.

I’d love to hear from experienced developers about:

1. The best way to learn Django efficiently (roadmaps, courses, or structured learning paths).
2. Project ideas that are impressive to recruiters and showcase real-world skills.
3. Skills beyond Django that I should focus on for backend development jobs.

I want to make sure I’m learning things that actually help in landing a job instead of just following random tutorials. Any insights would be super helpful!

Thanks in advance!

/r/django
https://redd.it/1ixys92
Wednesday Daily Thread: Beginner questions

# Weekly Thread: Beginner Questions 🐍

Welcome to our Beginner Questions thread! Whether you're new to Python or just looking to clarify some basics, this is the thread for you.

## How it Works:

1. Ask Anything: Feel free to ask any Python-related question. There are no bad questions here!
2. Community Support: Get answers and advice from the community.
3. Resource Sharing: Discover tutorials, articles, and beginner-friendly resources.

## Guidelines:

This thread is specifically for beginner questions. For more advanced queries, check out our [Advanced Questions Thread](#advanced-questions-thread-link).

## Recommended Resources:

If you don't receive a response, consider exploring r/LearnPython or join the Python Discord Server for quicker assistance.

## Example Questions:

1. What is the difference between a list and a tuple?
2. How do I read a CSV file in Python?
3. What are Python decorators and how do I use them?
4. How do I install a Python package using pip?
5. What is a virtual environment and why should I use one?

Let's help each other learn Python! 🌟

/r/Python
https://redd.it/1iy9wct
Codegen - Manipulate Codebases with Python

Hey folks, excited to introduce Codegen, a library for programmatically manipulating codbases.

What my Project Does

Think "better LibCST".

Codegen parses the entire codebase "graph", including references/imports/etc., and exposes high-level APIs for common refactoring operations.

Consider the following code:

from codegen import Codebase

# Codegen builds a complete graph connecting
# functions, classes, imports and their relationships
codebase = Codebase("./")

# Work with code without dealing with syntax trees or parsing
for function in codebase.functions:
# Comprehensive static analysis for references, dependencies, etc.
if not function.usages:
# Auto-handles references and imports to maintain correctness
function.remove()

# Fast, in-memory code index
codebase.commit()

Get started:

uv tool install codegen
codegen notebook --demo

Learn more at docs.codegen.com!

Target Audience

Codegen scales to multimillion-line codebases (Python/JS/TS/React codebases supported) and is used by teams at

/r/Python
https://redd.it/1iy0i35
New side project is up. JOAT.tools (Jack Of All Trades) built on Django Ninja

Hey, I'm embarrassed to release this often, which is kind of the mantra around here, right?

Long story short is that I've decided to build an API service that wraps many of the most useful libraries and other services, even those "one-feature" SaaS offerings.

Be gentle, I'm sharing it to poke and critique.

I have some colleagues in F50 companies who asked to have a service like this deployed internally because of a number of bureaucratic reasons.

It is easier to get an internal API approved than it is to add it to the existing compiled/deployed software stacks. (weird, but it is what it is -- mostly about software supply chains)

Anyway, go look at the openapi spec and see that it is mostly just about scraping and format conversions (for now).

EDIT: LOL, forgot the link:

https://joat.tools

/r/django
https://redd.it/1ixz2nu
Built an ORM: A Minimal Asynchronous ORM for Python and PostgreSQL

- What My Project Does: ORM (Object-Relation Mapping)
- Target Audience: Production usage
- Comparison: It demonstrate a minimal* implementation based on asyncio and type hinting achieving rich feature ORM implementation. Compared to Django, SQLAlchemy and other ORMs, it provides better developer experience in the projects applied with type-checking (e.g. Pyright) and asyncio.

\*AST statements count (SQLAlchemy: 76,228 , Peewee: 5,451, orm1: 677)

[orm1](https://github.com/hanpama/orm1) is an asynchronous Object-Relational Mapping (ORM) library for Python and PostgreSQL.

**Features**

* Asyncio
* Auto-mapping with Type Hints
* DDD Aggregate Support
* Query Builder
* Raw SQL Queries
* Nested Transaction Management
* Composite Key Support

**Example**

Install orm1 using pip:

```sh
pip install orm1
```

Define your database models with type hints:

```python
from orm1 import auto

@auto.mapped()
class Post:
id: int
title: str
content: str
attachments: list["PostAttachment"]

@auto.mapped(parental_key="post_id")
class PostAttachment:
id: int
post_id: int
file_name: str
url: str
```

Perform CRUD operations using a session:

```python
# Create a new post with an attachment.
post = Post()
post.title = "Introducing orm1"
post.content = "orm1 is a lightweight asynchronous ORM for Python."

attachment = PostAttachment()
attachment.file_name = "diagram.png"
attachment.url = "http://example.com/diagram.png"

post.attachments = [attachment]

# Save the post (and cascade save the attachment as part of the aggregate).
await session.save(post)
```

Update:

```python
# Update the post's title.
post.title = "Introducing

/r/Python
https://redd.it/1iy9q5f
Kreuzberg: Next Steps

Hi Peeps,

I'm the author of kreuzberg - a text extraction library named after the beautiful neighborhood of Berlin I call home.

I want your suggestions on the next major version of the library - what you'd like to see there and why. I'm asking here because I'd like input from many potential or actual users.

To ground the discussion - the main question is, what are your text extraction needs? What do you use now, and where would you consider using Kreuzberg?

The differences between Kreuzberg and other OSS Python libraries with similar capabilities (unstructured.io, docking, markitdown) are these:

- much smaller size, making Kreuzberg ideal for serverless and dockerized applications
- CPU emphasis
- no API round trips (actual of the others as well in some circumstances)

I will keep Kreuzberg small - this is integral for my use cases, dockerized rag micro services deployed on cloud run (scaling to 0).

But I'm considering adding extra dependency groups to support model-based (think open-source vision models) text extraction with or without GPU acceleration.

There is also the question about layout extraction and PDF metadata. I'd really be interested in hearing whether you guys have use for these and how you actually use them.

/r/Python
https://redd.it/1iyhjax
Looking for Inspiration & Recommendations for My Upcoming POS Project

Hey everyone! 👋

I'm planning to build a Point of Sale (POS) system using Django, and I’m looking for recommendations and inspiration. I want to make it efficient, user-friendly, and scalable.

Are there any open-source POS projects in Django that you'd recommend for reference?

/r/django
https://redd.it/1iyks73
Advice on model designs

Hello good people of Django-land!

I need some help with designing my models.

I'm building a web app where people can submit structured poetry called "pantun" where the number of lines must be even. So you can submit poems having from 2 up to 16 lines.

My question is which design is better?

My interests are keeping the database size as small as possible for as long as possible, ease of adding features and also ease of code maintainability.

1. Have a BasePantun model and then create descendants inheriting from it?
2. Have a monolith Pantun model where you keep fields named "Line10", "Line11" etc. empty? (This is my current implementation)

My current observation from users using the app is that most of them tend to submit mostly 4-line pantuns.

Another question I have is that I'm planning to implement an award system. For certain achievements, users can get certain awards.

Again same interests as above, which design is better?

1. My current implementation

​

class Award(models.Model):
name = models.CharField(max_length=50)
winners = models.ManyToManyField(User, related_name="pemenang_anugerah", blank=True)
...

2. Another implementation idea

class Award(models.Model):


/r/django
https://redd.it/1iyl64y
After moving Database URI to an environment variable I get "Either 'SQLALCHEMY_DATABASE_URI' or 'SQLALCHEMY_BINDS' must be set."

My app was working fine before. I host it on Heroku.


I realized that hardcoding the database uri with password isn't the most secure thing. Heroku has a thing called Config Vars where you can put the URI there as an environment variable that is separate from your code.


I did it. and it worked. This is how my code looks like:




app = Flask(__name__)
app.config['SECRET_KEY'] = os.environ.get('SECRET_KEY')
app.config['SQLALCHEMY_DATABASE_URI'] = os.environ.get('SQLALCHEMY_DATABASE_URI')
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
app.config['pool_size']= 10
app.config['poolclass'] = QueuePool
app.config['pool_pre_ping'] = True
app.config['SQLALCHEMY_POOL_RECYCLE'] = 35
app.config['SQLALCHEMY_POOL_TIMEOUT'] = 7
mail = Mail(app)


db = SQLAlchemy(app)
ma = Marshmallow(app)
bcrypt=Bcrypt(app)
login_manager = LoginManager(app)
CORS(app)


As you can see I access the Config vars using os.environ.get.


This all worked fine. App works great. Later on I decided to add another table and then update it using alembic.

/r/flask
https://redd.it/1iymufo