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
Clerk React Django

I was using clerk auth with react with one of project where backend is Django. So I created a middleware to authenticate the clerk users and assign the user object to the requests. This is along with the default django auth.
Here is the github :- https://github.com/ravikrsngh/clerk-django-react


Clerk Middleware

​

new clerk permission

​

This is fine or we have better ways to do it ?

/r/django
https://redd.it/1c9pfjm
Understanding Flask-SQLalchemy lifecycle

I do a once a day maintenance job where I fetch all "parent" in db, and do some checking/updates on "children" and "grandchildren". Parents have grown and this operation has become quite time consuming, so I am looking into ways of speeding up, and one way is to reduce **write** transactions with DB.

Pseudo-code below shows a simplified pattern of how I do it currently: Get all parents, loop, do updates on children/grandchildren and commit on every loop.

Is there way I could move the commit to be done once instead of for each loop? If I move the commit to after the for loop (and remove the one inside update\_children), will it still catch the changes that have been done on children inside update\_children()?

Disregard legacy sqlalchemy syntax.

def daily_maintenance()
parents = Parents.query.all()
for parent in parents:
update_children(parent)

# Can I move db.session.commit() here?

def update_children(parent):


/r/flask
https://redd.it/1c9l1n8
Django Authentication

I'm still new and I've never built a site for a client only personal projects, I came across django-allauth is this a good way for authentication or I should stick to the default mode of authentication

/r/djangolearning
https://redd.it/1c9ojwt
Should I use pydantic for all my classes?

Pydantic makes your code safer by making it strongly typed. You can no longer input a wrongly typed argument without getting an error (if pydantic can't convert it). This is great but to me it seems that sometimes standard python classes still seem preferable.

Perhaps it's because I'm not using it correctly but my code for a pydantic class is much longer then for a normal class. Especially if you are working with computed attributes. Then you have to start using special decorators and for every computed attribute you have to declare a function with "def ..." Instead of in an init function just being able to write attribute_3 = attribute 1 + attribute 2.

So I'm just wondering are you using pydantic for all your classes? And how do you handle computed fields in pydantic especially upon instantiation I find it hard to implement.

/r/Python
https://redd.it/1c9h0mh
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/1c9wo8r
Jobs that utilize Jupyter Notebook?

I have been programming for a few years now and have on and off had jobs in the industry. I used Jupyter Notebook in undergrad for a course almost a decade ago and I found it really cool. Back then I really didn’t know what I was doing and now I do. I think it’s cool how it makes it feel more like a TI calculator (I studied math originally)

What are jobs that utilize this? What can I do or practice to put myself in a better position to land one?

/r/Python
https://redd.it/1c9u0qf
Scaling Django Channels when calling third party api

Hey,

I want to build a Django application that calls ChatGPT API with streaming and streams the ChatGPT response to the user in real time. I found this tutorial: Building a streaming ChatGPT clone, with Django, Channels, and HTMX (youtube.com) where this guy builds what I want to achieve.

My concern is he is using django-channels without async and calling the api like this:

class ChatConsumerDemo(WebsocketConsumer):
def connect(self):
self.user = self.scope"user"
self.messages =
if self.user.isauthenticated:
self.accept()
else:
self.close()

def disconnect(self, close
code):
pass



/r/django
https://redd.it/1c9o5j2
I suck at frontend, UI/UX, is there a GUI html drag and drop designer?

I'm learning Django, with htmx and alpine. But my sites are ugly, designing the site is, I think, the hardest bit about web dev. Django is awesome and I'm getting the hang of forms, models, etc, but man designing a good looking site is hard.

I think It would help me to have a kind of drag and drop UI designer, much like you can do it with android studio (I just tried it briefly).

I looked around and found bootstrap studio, which may be what I want but I'm not sure if the sites you do there are easy to set up with Django templates.

Do you know other alternatives? FOSS would be awesome.


/r/djangolearning
https://redd.it/1c9yy10
Help comunicating templates

I am inheriting from two html files una using extends (layout.html) and the other one using include, in this one i have a component, how can i make that when you click on a button in the component it chages the layout.html (i want to change the color of a element to make a notification)

/r/flask
https://redd.it/1ca1u9j
DRF JWT authentication with django-allauth Social logins

I want the social login of django-allauth to return a JWT in the response (Generated by me, not the social account provider's token). And also to redirect to a custom URL instead of the default "/accounts/profile" since I'm using this for a flutter mobile app.
I've tried using the signals "pre\_social\_login" and "social\_account\_added" but they never triggered.
I also couldn't do it with overriding the views.
Do you know of a better way or maybe there's something wrong with my implementation?
Here's the signal code:

@receiver(pre_social_login)
def generate_social_jwt(request, sociallogin, **kwargs):
user = sociallogin.user
refresh = RefreshToken.for_user(user)
logger.info(f"(PRE_LOGIN) Social JWT generated for user {user.username}")
return Response(
{"refresh": str(refresh.token), "access": str(refresh.access_token)}
)
pre_social_login.connect(generate_social_jwt)





/r/django
https://redd.it/1c9uclw
Tkinter Variable class C/Python garbage collection mismatch

Tkinter is going to drive me crazy.

Let me lay this out for you:

Tkinter is the GUI interface I am using, which is a python frontend for a C library

It holds "widgets" in a window.

Some widgets have variables (StringVar, BooleanVar, etc - not "variables" like code variables but a class of updatable data holders for the widgets to link to the Tcl backend)

The Vars have incremental names like PYVAR1, PYVAR93, etc by default.

Names can be provided to the Vars via keywords upon initialization. (Note I have not been able to find any reason to not do this - hence this post)

Names should absolutely not be provided to the Vars unless they are unique. Because on python garbage collection (or "del Var" command) the Vars are told to destroy() themselves and then this command is passed to C "destroy this Var."

But the garbage collection in C (or rather Tcl) is slightly delayed from Python...

So if I immediately I instantiate a different Var with a different value (or same value, who knows) but reusing the same name, the Var has been deleted in Python (yey!) but it has not been deleted in C yet (uh oh). C says to Python

/r/Python
https://redd.it/1ca1en9
Retrieve flask form from Session.get( )

I would like a third-party application to access and edit a flask form that is embedded within a flask endpoint in order to make amendments to it and send the amended flask form via Session.post ( )?

More generally how does flask handle flask forms that are simple local variables within a flask endpoint and how can they be accessed via the python requests package?

/r/flask
https://redd.it/1ca6j2o
I made my first package (please review)

I've been learning Django on my own for about 3 years now and today I created a package that optimizes images by converting them to WebP. You can then display these images using a template tag.

The only support I've had during my coding journey is this community (thank you so much!) so I'd really appreciate it if you could provide some feedback. I have no idea what level my coding is on or if my style meets professional standards.

It is also my first time uploading something to Github and PyPi, as well as writing tests for Github Actions. Using your feedback, I'm hoping to make it good enough to show a potential employer someday.

https://github.com/peterstavrou/django-img-optimizer

/r/django
https://redd.it/1ca4vxn
What is currently the fastest/state-of-the-art ODE solver in Python?

For my application, Scipy's solvers are not fast enough so I am looking to speed up by using another package. These are some packages I have found so far:

* [NumbaLSODA](https://github.com/Nicholaswogan/numbalsoda)
* [DifferentialEquations.jl](https://github.com/SciML/DifferentialEquations.jl)
* [Torchquad](https://github.com/esa/torchquad)
(Although doesn't solve ODEs, just integrates quickly, but that could be wrapped I guess)
* [Torchdiffeq](https://github.com/rtqichen/torchdiffeq)
* [PyDSTool](https://pydstool.github.io/PyDSTool/FrontPage.html)

I will be experimenting with these packages, but I was wondering whether anyone has experience with them and has done work on them before. Also, I am wondering whether there are any packages I should check out?

/r/Python
https://redd.it/1ca4bwy
D Simple Questions Thread

Please post your questions here instead of creating a new thread. 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.

Thanks to everyone for answering questions in the previous thread!

/r/MachineLearning
https://redd.it/1c9jy4b
My falsk app works fine when running using launch.sh file locally but when i route the traffic via proxy ( nginx ), i get 504 Gateway Time-out.

My falsk app works fine when running using launch.sh file locally but when i route the traffic via proxy ( nginx ), i get 504 Gateway Time-out.

Here is my current nginx config

server {
listen 80;
listen :::80;

servername ;

location / {
return 301 https://$host$requesturi;
}
}

server {
listen 443 ssl;

ssl
protocols TLSv1 TLSv1.1 TLSv1.2;
sslciphers HIGH:!aNULL:!MD5;

ssl
certificate /etc/ssl/certs/example.com.pem;


/r/flask
https://redd.it/1cafuij
D Llama-3 may have just killed proprietary AI models

Full Blog Post

Meta released Llama-3 only three days ago, and it already feels like the inflection point when open source models finally closed the gap with proprietary models. The initial benchmarks show that Llama-3 70B comes pretty close to GPT-4 in many tasks:

The [official Meta page](https://llama.meta.com/llama3/) only shows that Llama-3 outperforms Gemini 1.5 and Claude Sonnet.
Artificial Analysis shows that Llama-3 is in-between Gemini-1.5 and Opus/GPT-4 for quality.
On [LMSYS Chatbot Arena Leaderboard](https://arena.lmsys.org/), Llama-3 is ranked #5 while current GPT-4 models and Claude Opus are still tied at #1.

The even more powerful Llama-3 400B+ model is still in training and is likely to surpass GPT-4 and Opus once released.

## Meta vs OpenAI

Some speculate that Meta's goal from the start was to target OpenAI with a ["scorched earth"](
https://en.wikipedia.org/wiki/Scorched_earth) approach by releasing powerful open models to disrupt the competitive landscape and avoid being left behind in the AI race.

Meta can likely outspend OpenAI on compute and talent:

OpenAI makes an estimated revenue of $2B and is likely unprofitable. Meta generated a revenue of $134B and profits of $39B in 2023.
Meta's compute resources likely outrank OpenAI by now.
Open source likely attracts better talent and researchers.

One possible outcome could

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