Daily Python News Question, Tips and Tricks, Best Practices on Python Programming Language Find more reddit channels over at @r_channels
Django 5.2 release candidate 1 released
https://www.djangoproject.com/weblog/2025/mar/19/django-52-rc1/
/r/django
https://redd.it/1jeuu38
Problema na View ou no HTML?
Fala galera, preciso de ajuda num projeto da faculdade. Criei uma view (nome da view - app) caso o usuário baba esteja logado apareça as infos do responsável e vice-versa;
Até então ok... as informações aparecem nos cards etc, mas ao clicar no botão de "Ver Perfil" o modal que abre é sempre do primeiro card; Alguem consegue me ajudar com isso?
HTML:
<div class="container">
{% if tipo_usuario == "baba" %}
<h5 class="mb-4">{{ usuarios|length }} Responsáveis disponíveis</h5>
{% else %}
<h5 class="mb-4">{{ usuarios|length }} Babás disponíveis</h5>
{% endif %}
<div class="row row-cols-1 row-cols-md-2 g-4">
{% for usuario in usuarios %}
<div class="col">
<div class="card h-100 d-flex flex-row shadow-lg">
/r/djangolearning
https://redd.it/1jeoepv
Flask Hosting: Cold starts and restarts
I built a small site with Flask and hosted it on Render’s free tier.
Initially, I had it on PythonAnywhere, but they didn’t seem to offer a way to add a custom domain on the free plan—or at least, it wasn’t straightforward.
Migrating to Render was easy, and setting up the domain was simple. But soon, I ran into two major problems.
Data Loss
I would save data to my database through the website, only to come back hours later and find it gone. I thought it was an issue with my commits and spent time troubleshooting, only to realize that Render frequently restarts services.
Why did this affect my database?
I was using SQLite. Since SQLite stores data in a file on the web service itself, every time the service restarted, it reverted to the last deployed state, wiping out any new data.
I eventually migrated to Postgres with Neon to fix this.
Cold Starts
Since my site only gets 3–4 visitors a day, it often sits idle. Naturally, I expected it to be put to sleep occasionally. But the real problem? It takes almost a full minute to wake up.
I don’t know about you, but if I visited a site called wisefool.xyz and it took that long
/r/flask
https://redd.it/1jd5t5o
Searching for a Coding Partner
Hi, I’m a 6+ yrs Python (main) developer and I have been working for several companies projects but always freelanced, I have experience in website automation, data scraping, network requests analysis, e-commerce, website creation, trading and more. I am looking for a well determined and motivated guy that wants to work with me to start a business and make some money together. Looking for opportunities
Regards
/r/Python
https://redd.it/1jesga2
Why drf not implemented schema into their api rather than use serialization who have performance issue?
I read some article about drf vs django ninja and find weird, If schema pydantic is better in term performance and validation, why drf implement serialization? Is there the info that I miss?
/r/django
https://redd.it/1jekc2g
Hypercorn VS Uvicorn VS Daphne+Gunicorn? (Behind Nginx)
Hi folks,
I have a setup with Websockets (HTMX and older code) that I'm progressively dumping for Server Sent events with HTMX.
One thing I realized when starting to use SSE is that the http/1.1 protocol seems to limit the number of open connections, so after i open a couple tabs, nothing loads in the newer tabs until I close the first ones. Using runserver in developement made me chase that bug for 2 days.
By using an http/2 compatible server like hypercorn, I was able to get rid of the issue.
Now, for production... I'm behind Nginx and I have http/2 working properly on it. Couple questions for experienced devops here:
\- Is there a performance difference between Nginx with http2 + an http/1.1 server behind like uvicorn? Should I aim for http2 all the way?
\- What are your general insights for performance when it comes to an app with SSE? Should I keep Gunicorn in WSGI and send SSE traffic to an ASGI server? Or should I just use nginx+uvicorn everywhere.
Any insight appreciated
/r/django
https://redd.it/1jegny2
R Jagged Flash Attention Optimization
Meta researchers have introduced Jagged Flash Attention, a novel technique that significantly enhances the performance and scalability of large-scale recommendation systems. By combining jagged tensors with flash attention, this innovation achieves up to 9× speedup and 22× memory reduction compared to dense attention, outperforming even dense flash attention with 3× speedup and 53% better memory efficiency.
Read the full paper write up here: https://www.shaped.ai/blog/jagged-flash-attention-optimization
/r/MachineLearning
https://redd.it/1je93sv
Just Built & Deployed a Video Platform MVP ( saketmanolkar.me ) — Looking for Feedback
https://redd.it/1je82un
@pythondaily
str2speech: A wrapper for all the new TTS models being released
GitHub: str2speech
# What my project does
Makes it easier to use all the latest TTS models.
I currently support:
- Zyphra Zonos
- Sesame CSM-1B
- Kokoro-82M
- Suno's Bark
- and a few older MMS-TTS models from Facebook
I'll be adding more models soon, like Spark TTS.
# Target Audience
Everyone who's interested in trying out/comparing TTS models. Could be used in production by YouTubers, podcasters, etc. Should work reasonably well in Shell scripts too.
# Comparison
The closest project I can think of is coqui-ai tts. It's a much larger project (supporting xtts, bark, tortoise, and many more models), but it seems to be abandoned. They haven't added support for any models released in the last couple of months.
My project tries to support more modern models. I try to focus on the CLI and ease of use on Google colab.
# Usage
Installation is easy:
pip install str2speech
str2speech --text "Kokoro is nice" --model "kokoro"
What is the convention for and when it comes to OOP?
Is it a convention in Python that \_ in class method or variable name signifies a private variable, while a _ signifies a protected variable?
I knew it was a convention to use it to signify that a variable or method wasn't to be used outside of the class, but I didn't know about this distinction of private and protected.
For context, I stumbled upon this question when Perplexity AI told me this was the case. I asked it to give me the sources for this but was unable to produce nothing outside a couple of blogs and articles.
So here I am asking the community, what do you think? I think it sounds interesting, to say the least. I have never though about using both __ and _ in the same piece of code, for the sake of consistency (I also thought it was discouraged), but now I am of the opinion that this distinction could actually be useful when designing more complex OOP systems.
/r/Python
https://redd.it/1jdtab6
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/1jdrtck
Looking for comments on a background task library I made
https://github.com/ross-sharma/django-task-queue
/r/django
https://redd.it/1jdr11d
To GeoDjango or not to GeoDjango
Hello everyone,
I need some insight here. I have an existing Django app using a MySQL database. One of the models that is defined here is called Location. To give you an idea, it just has a name (CharField) and description (TextField), so nothing fancy here.
I have the idea to extend the Location model with actual coordinates. The use case here would be to show where some objects are that have Location as foreign key, using spatial maps and interactive visualizations on the front-end.
I want to extend Location with both a single (x,y) coordinate and a field that defines some sort of bouding box like a polygon. The easiest way would be to use both PointFields and PolygonFields from GeoDjango. I found this implementation to be highly excessive for just the addition of two fields. Also, I'm unsure of changing my database engine django.db.backends.mysql to django.contrib.gis.db.backends.mysql just like that. I can see the benefits of using GeoDjango, but it feels overkill. On the other hand, using plain JSONFields or other fields that represent this data feels like a 'messy' way to solve this issue.
I'm wondering if anyone else has had the same or similar issue? What are your thoughts on this?
Thanks
/r/django
https://redd.it/1jdfzqm
VJUPYTER DOWNLODE AND RUN IN VISUAL STUDIO COMMUNITY 2022
HOW TO RUN AND INSTALL JUPYTYER IN VISUAL STUDIO COOMUNITY 2022 SAME AS VS CODE?
/r/IPython
https://redd.it/1jdagv6
Is asking for a walk through of a system when arriving in a new company a pipe dream
I have been blessed to have worked at 3 companies but in all 3 i never got a walk through of the system, i would arrive in my department get setup and get told what is done and required from the team ive been assigned too. As a fullstack dev i think it would be cool to get a short walkthrough what the frontend team work with or if im in the front, what the warehouse or backend team works with. Usually i have to figure who to asl and what they do once im assigned something.
So my question is, is it a pipe dream to think someone will give me that kind of deep rundown in my first day or week.
/r/django
https://redd.it/1jdeie6
Any good Python resume projects that AREN'T machine learning?
I'm seeking my first internship and i wanna make a project that showcases my python skills. I tried to get into machine learning using Andrew Ng's course but i wasn't really enjoying it at all i don't think it's for me, but I might pick it up again in the future.
So what are some good projects that recruiters/employers like to see? I won't be aiming for ML/data roles, at least for now
Edit: i have a couple fullstack apps with javascript, so im just tryna diversify my portfolio
/r/Python
https://redd.it/1jf4ce2
Is there something better than exceptions?
Ok, let's say it's a follow-up on this 11-year-old post
https://www.reddit.com/r/Python/comments/257x8f/honest\_question\_why\_are\_exceptions\_encouraged\_in/
Disclaimer: I'm relatively more experienced with Rust than Python, so here's that. But I genuinely want to learn the best practices of Python.
My background is a mental model of errors I have in mind.
There are two types of errors: environment response and programmer's mistake.
For example, parsing an input from an external source and getting the wrong data is the environment's response. You *will* get the wrong data, you should handle it.
Getting an n-th element from a list which doesn't have that many elements is *probably* a programmer's mistake, and because you can't account for every mistake, you should just let it crash.
Now, if we take different programming languages, let's say C or Go, you have an error code situation for that.
In Go, if a function can return an error (environment response), it returns "err, val" and you're expected to handle the error with "if err != nil".
If it's a programmer's mistake, it just panics.
In C, it's complicated, but most stdlib functions return error code and you're expected to check if it's not zero.
And their handling
/r/Python
https://redd.it/1jf3p1y
Just implemented my honeypots. Wish me luck!
I certainly hope Bingbot and Googlebot follow my robots.txt file 😬
/r/flask
https://redd.it/1jdsxhf
P Question about server GPU needs for for DeepLabCut for high throughput
Hi all,
Currently working on a project that uses DeepLabCut for pose estimation. Trying to figure out how much server GPU VRAM I need to process videos. I believe my footage would be 1080x1920p. I can downscale to 3fps for my application if that helps increase the analysis throughput.
If anyone has any advice, I would really appreciate it!
TIA
Edit:
From my research I saw a 1080ti was doing ~60fps with 544x544p video. A 4090 is about 200% faster but due to the increase in the footage size it only does 20 fps if you scale it relatively to the 1080ti w/ 544p footage size.
Wondering if that checks out from anyone that has worked with it.
/r/MachineLearning
https://redd.it/1jejg5d
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/1jejwwv
Python Quirks I Secretly Like
Hi there,
I’ve always wanted to create YouTube content about programming languages, but I’ve been self-conscious about my voice (and mic, lol). Recently, I made a pilot video on the Zig programming language, and afterward, I met a friend here on Reddit, u/tokisuno, who has a great voice and offered to do the voiceovers.
So, we’ve put together a video on Python — I hope you’ll like it:
https://www.youtube.com/watch?v=DZtdkZV6hYM
/r/Python
https://redd.it/1je98cv
PySide6 + Nuitka is very impressive (some numbers and feedback inside)
In preparation for releasing a new version of Flowkeeper I decided to try replacing PyInstaller with Nuitka. My main complaint about PyInstaller was that I could never make it work with MS Defender, but that's a topic for another time.
I've never complained about the size of the binaries that PyInstaller generated. Given that it had to bundle Python 3 and Qt 6, \~100MB looked reasonable. So you can imagine how surprised I was when instead of spitting out a usual 77MB for a standalone / portable Windows exe file it produced... a 39MB one! It is twice smaller, seemingly because Nuitka's genius C compiler / linker could shed unused Qt code so well.
Flowkeeper is a Qt Widgets app, and apart from typical QtCore, QtGui and QtWidgets it uses QtMultimedia, QtChart, QtNetwork, QtWebSockets and some other modules from PySide6_Addons. It also uses Fernet cryptography package, which in turn bundles hazmat. Finally, it includes a 10MB mp3 file, as well as \~2MB of images and fonts as resources. So all of that fits into a single self-contained 40MB exe file, which I find mighty impressive, especially if you start comparing it against Electron. Oh yes, and that's with the latest stable Python
/r/Python
https://redd.it/1je94cf
Building a Multi-Tenant Automation System in a Django CRM – Seeking Advice
Hi all,
I'm working on a SaaS CRM built with Django/DRF that centers around leads and deals, and I'm looking to implement a robust automation system. The idea is to allow for dynamic, multi-tenant automations that can be triggered by events on leads and deals, as well as scheduled tasks (like daily or weekly operations).
I'm using Django-tenants and django-q2
At a high level, the system should let users set up rules that include triggers, conditions, and actions, with everything stored in the database to avoid hardcoding. I'm considering a design that includes event-driven triggers (using Django signals or an equivalent) and a task queue for longer-running processes, but I'm curious about potential performance pitfalls and best practices when scaling these systems.
I'm interested in hearing from anyone who's built something similar or has experience with automations in a multi-tenant environment. Any advice, pitfalls to watch out for, or suggestions on design and architecture would be greatly appreciated!
Thanks in advance for your help.
/r/django
https://redd.it/1jdzkb8
I wrote a script to simulate this years March Madness
Here’s the code: https://gist.github.com/CoreyMSchafer/27fcf83e5a0e5a87f415ff19bfdd2a4c
Also made a YouTube walkthrough here: https://youtu.be/4TFQD0ok5Ao
The script uses the inverse of the seeds to weight the teams. There is commented out code that you can adjust to give seeds more/less of an advantage. If you’d like to weight each team individually, you could also add a power attribute to the Team dataclass and at those individually when instantiating the first round.
/r/Python
https://redd.it/1jdsi9u
[P] I fine-tuned Qwen 2.5 Coder on a single repo and got a 47% improvement in code completion accuracy
Hey all,
Just wanted to share an interesting experiment I ran to see what kind of performance gains can be achieved by fine-tuning a coding model to code from a single repo.
**Tl;dr**: The fine-tuned model achieves a 47% improvement in the code completion task (tab autocomplete). Accuracy goes from 25% to 36% (exact match against ground truth) after a short training run of only 500 iterations on a single RTX 4090 GPU.
https://preview.redd.it/3borsuk1bape1.png?width=1063&format=png&auto=webp&s=8d9510517f3d04163b3ac6b1de6765158886e489
This is interesting because it shows that there are significant gains to be had by fine-tuning to your own code.
**Highlights of the experiment**:
* Model: qwen2.5-coder 14b, 4-bit quantized
* Training data: Svelte source files from this repo: [https://github.com/hcengineering/platform](https://github.com/hcengineering/platform)
* Unsloth for LoRA training with rank 16, 4096 sequence length
* GPU: single RTX 4090
* 500 iterations with effective batch size 8
/r/MachineLearning
https://redd.it/1jdiafd
DRF API url location
In Django we typically define our DRF endpoints with a prefix of '/api/'. For a project with multiple DRF apps, where do you define these. Do you define them in the core project folder or do you define each on within it's respective app folder?
/r/django
https://redd.it/1jdj449
Feedback Wanted: GenAnalyzer - Web App for Protein Sequence Analysis & Mutation Detection
Hello everyone,
I created a web application called GenAnalyzer, which simplifies the analysis of protein sequences, identifies mutations, and explores their potential links to genetic diseases. It integrates data from multiple sources like UniProt for protein sequences and ClinVar for mutation-disease associations.
The application is built using Python Flask for the web framework and Biopython for protein sequence analysis, allowing users to compare sequences and detect mutations.
This project is my graduate project, and I would be really grateful if I could find someone who would use it and provide feedback. Your comments, ratings, and criticism would be greatly appreciated as they’ll help me improve the tool.
You can check out the app here: GenAnalyzer Web App
Feel free to explore the source code and contribute on the GenAnalyzer GitHub Repository
Feel free to leave any feedback, suggestions, or even criticisms. I would be happy for any comments or ratings.
Thanks for your time, and I look forward to hearing your thoughts.
/r/flask
https://redd.it/1jdlp5k
ETL completa com Python: Validando Dados e Planilhas de Excel para BI (Projeto end-to-end!)
Olá, pessoal!
Espero que todos estejam bem! Queria compartilhar um vídeo muito legal que pode ajudar a melhorar nossas habilidades em engenharia de dados. O vídeo é "ETL completa com Python: Validando Dados e Planilhas de Excel para BI (Projeto end-to-end!)". Confiram no link abaixo:
https://www.youtube.com/watch?v=JuOyNPjAer8
Aproveitem e bora aprender juntos!
/r/Python
https://redd.it/1jdkn65
Astrophysics - Earth's gravitational influence
Hey everyone,
I have a small "space science & astrophysics" Python tutorial series, and the corresponding code is freely available on my GitHub repo (stars are appreciated :-)). My recent "publication" is about the so called Hill-Sphere and Sphere-of-Influence, with our home planet as an example.
What are these concept?
Maybe you have heard in the past about some asteroids that become temporary moons of Earth, or some spacecraft mission that use so-called fly-bys to gain some speed for the outer planets.
In both cases these simple conceptual spheres are used to compute e.g. how stable an orbit is around our home planet.
Why this highly specific example?
Well I am preparing some future videos about these exact topics, so I am currently building up the basics :-). Hope you like it:
Link to the video
GitHub Repo
Cheers,
Thomas
/r/Python
https://redd.it/1jd9vp0
Best practices for handling third-party API credentials
Hi,
What are the best practices for handling third-party API credentials in full stack apps?
Example: let's say we're building a SaaS app that uses OpenAI API. The user is expected to provide their own api key (and potentially the base url if they want to use an openai compatible api).
The backend will need these credentials to make calls to the third party api so we will have to send them from the frontend to the backend. We also don't want the user to enter these credentials every time they run an action, so we will have to store them in the database.
What are best practices for handling these credentials? We can't just hash them and store the hash as we need to get the actual key to send it to the 3rd party api. Should we encrypt the key in the backend before storing them in the database? If we do this, where do we store the encryption key? Should it be an environment variable that is provided during runtime (e.g. stored in a password manager in the cloud provider)? But this key needs to be stored permanently, which means we cannot rotate it easily, right?
Also, what about the frontend
/r/Python
https://redd.it/1jdb9fu