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
React-native Expo Fetch, Network request failed. On android Flask Api

# Problem

I have a React Native Expo application where I successfully call my Node.js API using my local IP. The API works both in the emulator and on my physical Android device. However, when I try to call my Flask API, I get a Network Request Failed error.

I am running my Flask app on my local machine (http://192.168.x.x:5000), and my physical Android device is connected to the same WiFi network.

# Flask API (Python)

Here’s my Flask app, which is a simple speech transcription API. It receives an audio file in base64 format, decodes it, and transcribes it using speech_recognition.

from flask import Flask, request, jsonify
import base64
import tempfile
import speechrecognition as sr
from pydub import AudioSegment
from io import BytesIO
from flask
cors import CORS
import logging

app = Flask(name)
CORS(app, resources={r"/": {"origins": ""}}) # Allow all CORS requests

logging.basicConfig(level=logging.DEBUG)

def transcribeaudio(audiobase64):
try:


/r/flask
https://redd.it/1it221j
logging.getLevelName(): Are you serious?

I was looking for a function that would return the numerical value of a loglevel given as text. But I found only the reverse function per the documentation:

>logging.getLevelName(level) Returns the textual or numeric representation of logging level level.

That's exactly the reverse of what I need. But wait, there's more:

>The level parameter also accepts a string representation of the level such as ‘INFO’. In such cases, this functions returns the corresponding numeric value of the level.

So a function that maps integers to strings, with a name that clearly implies that it returns strings, also can map strings to integers if you pass in a string. A function whose return type depends on the input type, neat!

OK, so what happens when you pass in a value that has no number / name associated with it? Surely the function will return zero or raise a KeyError. But no:

>If no matching numeric or string value is passed in, the string ‘Level %s’ % level is returned.

Fantastic! If I pass a string into a function called "get..Name()" it will return an integer on success and a string on failure!

But somebody, at some point, a sane person noticed that this is a mess:

>Changed in version 3.4:

/r/Python
https://redd.it/1it29oi
What’s a Django Package That Doesn’t Exist Yet, But You Wish It Did?

Hey fellow Django devs,

I’ve been thinking a lot about how powerful Django is, but sometimes there’s something missing that could make our lives a whole lot easier.

So I wanted to ask:
What’s a Django package you wish existed, but doesn’t yet?

It could be anything—something that solves a common problem or just makes development smoother. No matter how big or small, if you could create the perfect Django package to fill a gap in the ecosystem, what would it be?

/r/django
https://redd.it/1it4z6o
What’s wrong with a classic server-side rendered (SSR) multi-page application (MPA) for most web apps? What’s so appealing about HTMX in early stages of development?

I recently built a web app with Django and used only a tiny bit of Alpine.js (less than 100 lines of JavaScript, in total). At first, I was excited about giving HTMX a try and adding it to the project, but the need never came. The UX feels good despite a full-page load on any navigation or form submission.

This makes me view HTMX as a nice-to-have thing or an optimization, so I’m a bit confused as to why people choose to use it so early in development.

In terms of UX, the experience HTMX provides is closer to a client-side rendered (CSR) web app than it is to a classic MPA SSR web app, so there is some sense in using HTMX if one wants to keep the UX.

As a user of the web (and a software engineer), I don’t care even a little about whether a web app is using CSR or SSR as long as it’s working and stable. In fact, in my experience, there’s a higher chance for me to have a worse UX when using a CSR web app, so I might even prefer classic SSR apps.

Obviously, there are valid use cases for various tools and technologies,

/r/django
https://redd.it/1it6f8b
D What is the future of retrieval augmented generation?

RAG is suspiciously inelegant. Something about using traditional IR techniques to fetch context for a model feels.. early-stage. It reminds me of how Netflix had to mail DVDs before the internet was good enough for streaming.

I just can’t imagine LLMs working with databases this way in the future. Why not do retrieval during inference, instead of before? E.g. if the database was embedded directly in the KV cache, then retrieval could be learned via gradient descent just like everything else. This at least seems more elegant to me than using (low-precision) embedding search to gather and stuff chunks of context into a prompt.

And FWIW I don’t think long context models are the future, either. There’s the lost-in-the-middle effect, and the risk of context pollution, where irrelevant context will degrade performance even if all the correct context is also present. Reasoning performance also degrades as more context is added.

Regardless of what the future looks like, my sense is that RAG will become obsolete in a few years. What do y'all think?

EDIT: DeepMind's RETRO and Self-RAG are some example implementations of learned retrieval that may be interesting.

/r/MachineLearning
https://redd.it/1itl38x
About using Django choices with Pydantic

I usually use pydantic in my Django program. I have always been troubled by the inability to apply Django choices to pydantic, so I wrote a Choices class for my Django program. I hope you can help me see if this is a good way to do it, or if there is a more convenient way to achieve the same effect.

Defining my Choices class:
https://melodious-condor-d48.notion.site/django-choices-1a061f9ffe6280ff9eabc172cb852cd8?pvs=4

Use it in model:

from django.db import models

from .choices import Choices, ChoiceField

class DataScore(Choices):
INCORRECT = ChoiceField(value=-1, label="错误")
UNKNOWN = ChoiceField(value=0, label="未知")
CORRECT = ChoiceField(value=1, label="正确")

class Data(models.Model):
# ... Some content is omitted
score = models.IntegerField(default=DataScore.UNKNOWN.value,
choices=DataScore.choices,


/r/django
https://redd.it/1itnjfu
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/1itkpfl
Happy Birthday, Python! 🎉🐍

Guido van Rossum began working on Python language in the late 1980s as a successor to the ABC programming language. The first version, Python 0.9.0, was released on this day, February 20, 1991.

/r/Python
https://redd.it/1itu5mn
My Ever-Expanding Python & Django Notes

Hey everyone! 👋

I wanted to share a project I've been working on: **Code-Memo** – a personal collection of coding notes. This is NOT a structured learning resource or a tutorial site but more of a living reference where I document everything I know (and continue to learn) about Python, Django, Linux, AWS, and more.

Some pages:
📌 **Python Notes**
📌 **Django Notes**

The goal is simple: collect knowledge, organize it, and keep expanding. It will never be "finished" because I’m always adding new things as I go. If you're a Python/Django developer, you might find something useful in there—or even better, you might have suggestions for things to add!

Would love to hear your thoughts.

/r/django
https://redd.it/1itzskt
How to simply add a blog, without a giant framework?

Does anyone know of a lib I can use to do the following:


1. I have an existing Django project

2. I want to write blog posts as markdown, put them in a folder

3. Django publishes them automatically, reading those files


Thanks

/r/django
https://redd.it/1ittqo2
What the hell is going on with type hinting these days

When I first learned python back in versions 3.6 and 3.7 I regarded type hinting as a purely styling feature. It was well rooted in my mind that python code with or without type hinting will run the same and it is used only for readability -- basically just us developers being kind to each other.

Nowadays more and more packages are using type hinting for core functions. SQLAlchemy is using it to declare SQL column types (Mapped), FastAPI + Pydantic is using it for HTTP payloads and auto-documentation, and dataclasses uses it to construct (shockingly) data classes.

Don't get me wrong, I'm supportive of type hinting\\annotations. I'm also well aware that all of these packages will execute just fine without it. But maybe it's fair to say that in modern python applications type hinting is a core feature and not just for styling and garnishing.

Edit: I actually find type annotations very useful, I'm not against it. I wanted to discuss whether it's really "optional" due to its widespread integration in libraries. I like u/all4Nature point: I'm thinking on it from a software engineer prespective, data analysts will probably disagree that type hinting is as widespread as I thought.

/r/Python
https://redd.it/1itzac1
My Ever-Expanding Python & Django Notes

Hey everyone! 👋

I wanted to share a project I've been working on: **Code-Memo** – a personal collection of coding notes. This is NOT a structured learning resource or a tutorial site but more of a living reference where I document everything I know (and continue to learn) about Python, Django, Linux, AWS, and more.

Some pages:
📌 **Python Notes**
📌 **Django Notes**

The goal is simple: collect knowledge, organize it, and keep expanding. It will never be "finished" because I’m always adding new things as I go. If you're a Python/Django developer, you might find something useful in there—or even better, you might have suggestions for things to add!

Would love to hear your thoughts.

/r/Python
https://redd.it/1itzsnz
Affordable database options

Coming from the enterprise world, I am used to just spinning up an AWS RDS instance (or similar) for a project to use as a database. The nice thing about that is they have all the backups, metrics and everything nicely done for you. But for a personal project or micro SaaS, paying even $20 per month for a micro instance seem excessive to me.

I heard some people go as simple as using a sqlite in a small project. I was also thinking just a VPC where I have Django and Postgres in docker-compose. Naturally I can make my own backups from the docker instance. But using postgres in docker-compose just feels a bit "flying blind" sort of thing as I do not have metrics.

But in an optimal situation I would have the following:
- cheap
- some way to visualize if database performance is a bottleneck
- possibility to grow the instance to give it better performance if user count grows

Any recommendations?

/r/django
https://redd.it/1iu8eho
Friday Daily Thread: r/Python Meta and Free-Talk Fridays

# Weekly Thread: Meta Discussions and Free Talk Friday 🎙️

Welcome to Free Talk Friday on /r/Python! This is the place to discuss the r/Python community (meta discussions), Python news, projects, or anything else Python-related!

## How it Works:

1. Open Mic: Share your thoughts, questions, or anything you'd like related to Python or the community.
2. Community Pulse: Discuss what you feel is working well or what could be improved in the /r/python community.
3. News & Updates: Keep up-to-date with the latest in Python and share any news you find interesting.

## Guidelines:

All topics should be related to Python or the /r/python community.
Be respectful and follow Reddit's Code of Conduct.

## Example Topics:

1. New Python Release: What do you think about the new features in Python 3.11?
2. Community Events: Any Python meetups or webinars coming up?
3. Learning Resources: Found a great Python tutorial? Share it here!
4. Job Market: How has Python impacted your career?
5. Hot Takes: Got a controversial Python opinion? Let's hear it!
6. Community Ideas: Something you'd like to see us do? tell us.

Let's keep the conversation going. Happy discussing! 🌟

/r/Python
https://redd.it/1iudeoy
In 2025 will there be a viable freelance market for Python developers other than Fiver or UpWork

Posted this question a few weeks ago but I guess it was on the wrong day. Since it free text Friday I will try again.

Are companies looking for freelance Python developers for hourly or statement of work, fixed price scripting work from places other than Upwork or Fiver or similar sites?

/r/Python
https://redd.it/1iudwva
Django for beginners - William Vincent

Everything is good with this book. I am able to understand easily but the only problem i am facing rn is ,at some points , after copying the exact code from the book the code isn't working.
Please help

/r/django
https://redd.it/1iu6yyn
R Detecting LLM Hallucinations using Information Theory

LLM hallucinations are a major challenge, but what if we could predict when they happen? Nature had a great publication on semantic entropy, but I haven't seen many practical guides on detecting LLM hallucinations and production patterns for LLMs.

Sharing a blog about the approach and a mini experiment on detecting LLM hallucinations. BLOG LINK IS HERE

1. Sequence log-probabilities provides a free, effective way to detect unreliable outputs (\~LLM confidence).
2. High-confidence responses were nearly twice as accurate as low-confidence ones (76% vs 45%).
3. Using this approach, we can automatically filter poor responses, introduce human review, or iterative RAG pipelines.

https://preview.redd.it/zu9u6q7n1dke1.png?width=1436&format=png&auto=webp&s=73473fc975f900a27c0d1a64d020efca2f415ba0

Love that information theory finds its way into practical ML yet again!

Bonus: precision recall curve for an LLM.

https://preview.redd.it/rbne2tjj2dke1.png?width=1432&format=png&auto=webp&s=72c5754f932daa7a632d6e0d9c0ed17e54530965

/r/MachineLearning
https://redd.it/1iu9ryi
Appreciation post for PyCharm

I spent the entire day today working on some complex ETL. So many hours spent building, testing, fine-tuning. Once I got it working I was updating the built in sphinx documentation, running the ‘make html’ command several times in the terminal. Turns out I had at one point in this active terminal, done a ‘git reset —hard’ command. While pressing up to cycle through commands, I accidentally ran git reset hard. All my work for the entire day was GONE. I have f’d up at work before, but never this bad. I was mortified.

I had a moment of panic, and then asked chatGPT if there was any way to recover. The git log options it gave did not work. I then asked if PyCharm had any solutions for this. THERE IS A LOCAL HISTORY FEATURE THAT SAVED ME. It saves your changes and I was able to recover it all. Thank you to JetBrains for this amazing product. Four years with this product and I’m still learning about amazing features like this.

/r/Python
https://redd.it/1iume26
Login Functionality not working

I'm making a password manager app for my school project. So i decided to use SQLite since the project is small scale, and I'm hashing my passwords too. When i try to login the browser returns an error, which says :

" user_id = session['user'\]['id'\]

\^\^\^\^\^\^\^\^\^\^\^\^\^\^\^\^\^\^\^\^\^

KeyError: 'id'
"
I've tried using ChatGPT, and other chat bots to see how I can fix the code but I've been stuck on this for three hours now. The function where the error is being returned from is this, and there's the login function too :

Any help would be greatly appreciated.

@app.route('/dashboard')
def dashboard():

    if 'user' not in session:

        print("User not found!!")
        return redirect(urlfor('login'))
   
    print(session)
   
    user
id = session'user''id'

    with sqlite3.connect('database.db') as conn:
        cursor = conn.cursor()


/r/flask
https://redd.it/1iuqtth
Follow the yearly PyCon if you want to get better at using Python

One very under-appreciated advice I'm often giving to people starting with Python (or wanting to dive much deeper) is to follow the annual Python Conference (PyCon) and watch a few talks.

By far not all of them are relevant for most people. Some thing go very deep in how the language works intrinsically, or marginal optimizations for machine-learning stacks, but by and large it's really one of the best ways to keep up with the language and the community.


Just search "PyCon 20xx" (e.g 2024) on Youtube and you'll find most/all of them there.


For example, one talk I absolutely love from the PyCon 2018 (yes, 2018!) is a talk by Hillel Wayne on testing better: https://www.youtube.com/watch?v=MYucYon2-lk

Some things get old, deprecated, some things are just making you a better dev.

/r/Python
https://redd.it/1iurnjd