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
Why am I facing this issue with CSRF ?

I do have decent experience in django but working first time on django+React, so couldn't get my head around this problem even after lot of research on internet.
I would be grateful if you guys can help me out on this one

So I have been trying to develop this Django + React app and deploy it on [repl.it](http://repl.it)

The URL for my hosted frontend is of form "SomethingFrontend.replit.app"
and for backend, it would be "SomethingBackend.replit.app"

below are the relevant settings from my settings.py:

ALLOWED_HOSTS = [".replit.dev", ".replit.app"]
CSRF_TRUSTED_ORIGINS = [
"https://SomethingFrontend.replit.app",
"https://*.replit.dev", "https://*.replit.app"
]

CORS_ALLOWED_ORIGINS = [
"https://SomethingFrontend.replit.app"
]
CORS_ALLOW_CREDENTIALS = True

SESSION_COOKIE_SAMESITE = 'None'
SESSION_COOKIE_SECURE = True
CSRF_COOKIE_SAMESITE = 'None'
CSRF_COOKIE_SECURE = True
SESSION_COOKIE_DOMAIN = ".replit.app"
CSRF_COOKIE_DOMAIN = ".replit.app"



I am also using django all-auth headless for social authentication via google and linkedIn
so

/r/django
https://redd.it/1j1jc4l
TIL you can use else with a while loop

Not sure why I’ve never heard about this, but apparently you can use else with a while loop. I’ve always used a separate flag variable

This will execute when the while condition is false but not if you break out of the loop early.

For example:

Using flag

nums = [1, 3, 5, 7, 9]
target = 4
found = False
i = 0

while i < len(nums):
if nums[i] == target:
found = True
print("Found:", target)
break
i += 1

if not found:
print("Not found")


Using else

nums = [1, 3, 5, 7, 9]
target = 4
i = 0

while i < len(nums):
if nums[i] == target:
print("Found:", target)
break
i += 1
else:
print("Not found")


/r/Python
https://redd.it/1j1axht
What algorithm does math.factorial use?

Does math.factorial(n) simply multiply 1x2x3x4…n ? Or is there some other super fast algorithm I am not aware of? I am trying to write my own fast factorial algorithm and what to know it’s been done

/r/Python
https://redd.it/1j1r2j7
I Built a Localization Helper Tool for Localizers/Translators

Hey everyone,

Last month, while localizing a game update, I found it frustrating to track which keys still needed translation. I tried using various AI tools and online services with massive token pools, but nothing quite fit my workflow.

So, I decided to build my own program, a Localization Helper Tool!

What My Project Does: This app detects missing translation keys after a game update and displays each missing key. I also added an auto-machine translation feature, but most won't need that, I assume (you still need a Google Cloud API key for that).

Target Audience: This tool is primarily for game developers and translators who work with localization files and need to quickly identify missing translations after updates.

Comparison: Unlike general translation services or complex localization platforms, my tool specifically focuses on detecting missing keys between versions. Most existing solutions I found were either too complex (full localization suites) or too basic (simple text comparison tools). My tool bridges this gap.

It's my first app, and I've made it with the help of GitHub Copilot, so I don't know if the file structure and code lengths for each file are good or not, but nevertheless, it works as it should.

I'd love to hear your thoughts

/r/Python
https://redd.it/1j1s5zt
Visualizating All of Python

What My Project Does: I built a visualization of the packages in PyPi here, and found it pretty fun for discovering packages. For the source and reproducing it, see here. Hope you get a kick out of it, too!

Target Audience: Python Devs

Comparison: I didn't find anything like it out there, although I'm sure there must be something like it out there.

/r/Python
https://redd.it/1j1vpng
Making image text unrecognizable to ocr with python.

Hello, I am a python learner. I was playing around with image manipulation techniques using cv2, pil, numpy etc similar. I was aiming to make an image that contains a text becomes unrecognizable by an OCR or ai image to text apps. I was wondering what techniques i could use to achieve this. I dont want to specifically corrupt just the image but want it to be manipulated such that human eye thinks its normal but ocr or ai thinks wtf is that idk. So what techniques can i use to achieve such a result that even if i paste that image somewhere or someone screenshots the image and puts in ocr, they cant extract text from it?
thanks :)

/r/Python
https://redd.it/1j206j0
How do I install tailwind version 4 with flask?

I found a lot of older versions that tell you how to setup tailwind. Will they work with tailwind version 4?
If not does anyone know how?

Also I am using blueprints in my flask app if that makes a difference.

Here is an example of something I found https://www.codewithharry.com/blogpost/using-tailwind-with-flask/

/r/flask
https://redd.it/1j1gr19
Django In Production Having Too Many Open Files

I have one VPS thats running about 5 Django servers behind nginx. All are using gunicorn and are somewhat complex. Celery tasks and management commands running on cron.

But i have one of them that is causing a huge problem.

Errno 24 Too many open files: 'myfile.pickle'

and

could not translate host name "my-rds-server-hostname"

When i run this one server the number of handles open when running

lsof | wc -l

Is 62,000 files / handles. When i kill this one gunicorn server, it goes down to 600 open files / handles.

I have no idea what could be causing this many open handles in this one server process. Each other gunicorn has a few hundred but this one has like 59,000 just by itself. These files are opened the SECOND the server starts so its not some kind of long term leak.

I was thinking maybe a stray import or something but no.

Cpu usage is like 4% for this one process and ram is only about 20% full for the entire system.

The hostname issue is intermittent but only happens when the other issue happens. It is not internet issues or something like that. It just seems

/r/django
https://redd.it/1j1zqet
Few years as a Django Developer but Still Feel Underqualified — Need Advice to gain Confidence

Hi everyone,

I have few years of experience as a Python Django developer, working from home since day one. I'm currently trying to switch jobs, but I feel like I don't know enough Django or I don't have enough confidence in it.

During this time, I've learned many things other than just django. I haven't built enough personal projects to showcase my skills. Whenever I try to build something, I end up relying heavily on ChatGPT — although I understand what the code does and why it's written that way. Most of my learning has come from YouTube tutorials, and I'm a quick learner, but I struggle with consistency.

One day I'm learning React, the next day something new, and by the end of the week, I'm exploring something entirely different. I feel like I'm all over the place and not mastering anything.

Is this common among self-taught developers? How can I gain real confidence in Django? Should I stick to a structured resource like a book or course? If yes, could you recommend one?

Any advice or personal experiences would be really helpful. Thank you!

/r/django
https://redd.it/1j1w4ca
Use DjangoModelFormMutation to update instance in Graphene-Django

Hello,

I am currently trying out graphql in my Django application. I have installed Graphene Django and tried out the first things. Now I want to implement the CRUD operations for my model as simply as possible.

I found in the documentation that you can use the Django Forms for the mutations. So for my model I have

class Category(models.Model):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    name = models.CharField(max_length=255)
    language = models.ForeignKey('company.Language', on_delete=models.CASCADE)

i have created a form:

class CategoryForm(forms.ModelForm):
class Meta:
model = Category
fields = ('name', 'language',)

And now I use this mutation

class CategoryMutation(DjangoModelFormMutation):
    category = graphene.Field(CategoryType)

    class Meta:
        form_class = CategoryForm


class Mutation(graphene.ObjectType):
    create_category = CategoryMutation.Field()

The creation with the following graphql

/r/django
https://redd.it/1j1o5za
Need Advise for deploying workers

Our client is currently using Render as a hosting service for the Django web app, 2 worker instances, one db instance and one redis instance. The client has a local server that they use for backups and store some information on site. I was thinking about moving the two workers and the redis instance to the NAS and connect them to the main server and the db.

From a cybersecurity perspective, I know it would be better to keep everything on Render, but the workers handle non-essential tasks and non-confidential information; so my take is that this could be done without severely compromising information for the client and reducing the montly costs on Render. I would obviously configure the NAS and the db so they only accept connections from one another and the NAS has decent cybersecurity protocols according to the client.

Am I missing something? Does anyone have any other suggestions?

/r/django
https://redd.it/1j2b9pw
D Self-Promotion Thread

Please post your personal projects, startups, product placements, collaboration needs, blogs etc.

Please mention the payment and pricing requirements for products and services.

Please do not post link shorteners, link aggregator websites , or auto-subscribe links.

\--

Any abuse of trust will lead to bans.

Encourage others who create new posts for questions to post here instead!

Thread will stay alive until next one so keep posting after the date in the title.

\--

Meta: This is an experiment. If the community doesnt like this, we will cancel it. This is to encourage those in the community to promote their work by not spamming the main threads.

/r/MachineLearning
https://redd.it/1j1hc0o
Monday Daily Thread: Project ideas!

# Weekly Thread: Project Ideas 💡

Welcome to our weekly Project Ideas thread! Whether you're a newbie looking for a first project or an expert seeking a new challenge, this is the place for you.

## How it Works:

1. **Suggest a Project**: Comment your project idea—be it beginner-friendly or advanced.
2. **Build & Share**: If you complete a project, reply to the original comment, share your experience, and attach your source code.
3. **Explore**: Looking for ideas? Check out Al Sweigart's ["The Big Book of Small Python Projects"](https://www.amazon.com/Big-Book-Small-Python-Programming/dp/1718501242) for inspiration.

## Guidelines:

* Clearly state the difficulty level.
* Provide a brief description and, if possible, outline the tech stack.
* Feel free to link to tutorials or resources that might help.

# Example Submissions:

## Project Idea: Chatbot

**Difficulty**: Intermediate

**Tech Stack**: Python, NLP, Flask/FastAPI/Litestar

**Description**: Create a chatbot that can answer FAQs for a website.

**Resources**: [Building a Chatbot with Python](https://www.youtube.com/watch?v=a37BL0stIuM)

# Project Idea: Weather Dashboard

**Difficulty**: Beginner

**Tech Stack**: HTML, CSS, JavaScript, API

**Description**: Build a dashboard that displays real-time weather information using a weather API.

**Resources**: [Weather API Tutorial](https://www.youtube.com/watch?v=9P5MY_2i7K8)

## Project Idea: File Organizer

**Difficulty**: Beginner

**Tech Stack**: Python, File I/O

**Description**: Create a script that organizes files in a directory into sub-folders based on file type.

**Resources**: [Automate the Boring Stuff: Organizing Files](https://automatetheboringstuff.com/2e/chapter9/)

Let's help each other grow. Happy

/r/Python
https://redd.it/1j25eaj
What Are Your Favorite Python Repositories?

Hey r/Python!

I’m always on the lookout for interesting and useful Python repositories, whether they’re libraries, tools, or just fun projects to explore. There are so many gems out there that make development easier, more efficient, or just more fun.

I'd love to hear what repositories you use the most or have found particularly interesting. Whether it's a library you can't live without, an underappreciated project, or something just for fun, let your suggestions be heard below!

Looking forward to your recommendations!


/r/Python
https://redd.it/1j2ev5f
Why is there no standard implementation of a disjoint set in python?

We have all sorts of data structure implemented as part of the standard library. However disjoint set or union find is totally missing. It's super useful for bunch of things - especially detecting relationships, cycles in graph etc.

Why isn't there an implementation of it? Seems fairly straightforward to write one in python - but having a platform backed implementation would do wonders for performance? Especially if the set becomes huge.


Edit - the contributing guidelines - Adding to the stdlib

/r/Python
https://redd.it/1j20l34
I need help on deploying Django Channels

I wanted to deploy django channels Asgi on a server that has a free tier like pythonanywhere and I don't know one.

and Deploying Django channels requires Redis that is also a problem.
I appreciate any help on this

/r/django
https://redd.it/1j2qs5j
How to enable reCAPTCHA v3 in Flask? I've been working on this literally for days... please help.

I'm at my wits end. The process seem so obvious, but it never works.

I have google cloud set up with keys. I've tried to set it up with the Python backend prebuild... which for some reason was deprecated in 2018 and they haven't updated the code. I've tried to set it the HTML button with their REST API, but that seems to only bet integrated for the non-button format.

I just want to stop bots from creating thousands of fake users on my database... please help.

/r/flask
https://redd.it/1j2zjje
R Had a paper accepted at CVPR, should I put it in arvix first ?

Hello,
So my first paper was accepted at CVPR.
Apparently the paper will be made available by the Computer Vision Foundation around the first of June. So I’m wondering if I should put it in arvix first !


/r/MachineLearning
https://redd.it/1j2epr9
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/1j2xevt