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
Best approach to allowing only the staff users to have the access

I have two snippets here and which one is the best approach/practice for only allowing staff users have the access to certain data. In my case accessing user profile. Any suggestion will be greatly appreciated. Thank you very much.

example 1:

@api_view(['GET'])
@authentication_classes[TokenAutentication]
def get_profile_view(request):
if request.user.is_staff:
profiles = Profile.objects.all()
serializer = ProfileSerializer(profiles, many=True)
return Response(serializer.data, status=status.HTTP_200_OK)
return Response({'error': 'Not allowed'}, status=status.HTTP_400_BAD_REQUEST)


example 2:

@api_view(['GET'])
@permission_classes([IsAdminUser])
@authentication_classes[TokenAutentication]
def get_profile_view(request):
profiles = Profile.objects.all()
serializer = ProfileSerializer(profiles, many=True)
return Response(serializer.data, status=status.HTTP_200_OK)

/r/django
https://redd.it/1fajw75
First website

Hi everyone, I have created my first website and wanted to share it with you all
It is a website for my brother who owns his own carpentry business.
https://ahbcarpentry.com/

I used plain js, css, html and of course flask.

I hope you like it

Any criticism is appreciated

/r/flask
https://redd.it/1fal6l0
What is the purpose for Middleware and when should I use it (or not)?

I'm not sure I fully understand the purpose of how/when to use Middleware.

One of the things I am looking to do is to take input from a user from a django front end and pass it to just straight python scripts to do some things on the backend, and then pass stuff back to the django front end.
Is that how/where I would use Middleware? (I have read the django docs for middleware but they are not always the most clear, or I'm not that smart.)



/r/djangolearning
https://redd.it/1fajavz
PyJSX - Write JSX directly in Python

Working with HTML in Python has always been a bit of a pain. If you want something declarative,
there's Jinja, but that is basically a separate language and a lot of Python features are not available.
With PyJSX I wanted to add first-class support for HTML in Python.

Here's the repo: https://github.com/tomasr8/pyjsx

## What my project does

Put simply, it lets you write JSX in Python.
Here's an example:

# coding: jsx
from pyjsx import jsx, JSX
def hello():
print(<h1>Hello, world!</h1>)

(There's more to it, but this is the gist). Here's a more complex example:

# coding: jsx
from pyjsx import jsx, JSX

def Header(children, style=None, rest) -> JSX:
return <h1 style={style}>{children}</h1>

def Main(children, rest) -> JSX:
return <main>{children}</main>

def App() -> JSX:
return (
<div>
<Header style={{"color": "red"}}>Hello,

/r/Python
https://redd.it/1falc1s
How to handle JSON data received from API calls in relation to my Django models/database?

I've recently started working in web development and specifically with Django as the backend. When dealing with JSON responses from external API calls, I always wonder how to store and handle this data efficiently in my database.

Should I:

- Store the entire JSON response in a JSONField in my model, and then parse the JSON when I need specific fields by accessing the relevant keys?

OR

- Parse the JSON upon receiving it and store each key/value pair in separate fields in my model?

What are the pros and cons of each approach, and when would one method be preferable over the other? I thought that I maybe can learn from your best practices :)

/r/django
https://redd.it/1faj6nw
Saturday Daily Thread: Resource Request and Sharing! Daily Thread

# Weekly Thread: Resource Request and Sharing 📚

Stumbled upon a useful Python resource? Or are you looking for a guide on a specific topic? Welcome to the Resource Request and Sharing thread!

## How it Works:

1. Request: Can't find a resource on a particular topic? Ask here!
2. Share: Found something useful? Share it with the community.
3. Review: Give or get opinions on Python resources you've used.

## Guidelines:

Please include the type of resource (e.g., book, video, article) and the topic.
Always be respectful when reviewing someone else's shared resource.

## Example Shares:

1. Book: "Fluent Python" \- Great for understanding Pythonic idioms.
2. Video: Python Data Structures \- Excellent overview of Python's built-in data structures.
3. Article: Understanding Python Decorators \- A deep dive into decorators.

## Example Requests:

1. Looking for: Video tutorials on web scraping with Python.
2. Need: Book recommendations for Python machine learning.

Share the knowledge, enrich the community. Happy learning! 🌟

/r/Python
https://redd.it/1fatupz
Django app vs Django plugin?

Is there any difference between a Django app that can be used within your website and a Django plugin or they are both the same thing?

How to create a simple Django app?

How to create a simple Django plugin?

Thank you so much!

/r/djangolearning
https://redd.it/1f8nwqp
My first framework, please judge me

Hi all! First post here!

I'm excited to introduce LightAPI, a lightweight framework designed for quickly building API endpoints using Python's native libraries. It streamlines the process of creating APIs by reducing boilerplate code while still providing flexibility through SQLAlchemy for ORM and aiohttp for handling async HTTP requests.

I've been working in software development for quite some time, but I haven't contributed much to open source projects until now. LightAPI is my first step in that direction, and I’d love your help and feedback!

What My Project Does:
LightAPI simplifies API development by auto-generating RESTful endpoints for SQLAlchemy models. It's built around simplicity and performance, ensuring minimal setup while supporting asynchronous operations through aiohttp. This makes it highly efficient for handling concurrent requests and building fast, scalable applications.

Target Audience:
This framework is ideal for developers who need a quick, lightweight solution for building APIs, especially for prototyping, small-to-medium projects, or situations where development speed is critical. While it’s fully functional, it’s not yet intended for production-level applications—though with the right contributions, it can definitely get there!

Comparison:
Unlike heavier frameworks like Django REST Framework, which provides many advanced features but requires more setup, LightAPI focuses on minimalism and speed.

/r/Python
https://redd.it/1fayfdi
My first framework, please judge me

Hi all! First post here!

I'm very new in terms of open source contributions, but anyway, what Im trying to do is the LightAPI, a lightweight framework designed for quickly building API endpoints using Python's native libraries. It streamlines the process of creating APIs by reducing boilerplate code while still providing flexibility through SQLAlchemy for ORM and aiohttp for handling async HTTP requests.

I've been working in software development for quite some time, but I haven't contributed much to open-source projects until now. LightAPI is my first step in that direction, and I’d love your help and feedback!

What My Project Does:

LightAPI simplifies API development by auto-generating RESTful endpoints for SQLAlchemy models. It's built around simplicity and performance, ensuring minimal setup while supporting asynchronous operations through aiohttp. This makes it highly efficient for handling concurrent requests and building fast, scalable applications.

Target Audience:

This framework is ideal for developers who need a quick, lightweight solution for building APIs, especially for prototyping, small-to-medium projects, or situations where development speed is critical. While it’s fully functional, it’s not yet intended for production-level applications—though with the right contributions, it can definitely get there!

Comparison:

Unlike heavier frameworks like Django REST Framework (that I love

/r/django
https://redd.it/1fayb0j
EasySubber: Automatic subtitles for your videos

I’d like to showcase EasySubber, a tool I developed to automatically generate subtitles from video files. If you’ve ever spent hours manually creating subtitles, this project could save you time.

# What My Project Does:

EasySubber uses Whisper (OpenAI's speech recognition model) for transcription and FFmpeg for audio processing. It supports video files like .mkv, .mp4, and .avi, and automatically generates .srt subtitle files. The program includes a simple GUI (built with Tkinter) to ensure accessibility for users who may not be familiar with the command line.

# Target Audience:

EasySubber is primarily aimed at video creators and content developers who need to generate subtitles quickly and easily. However, it’s also suitable for hobbyists or anyone working with video/audio who wants to automate the transcription process. This is not yet intended for production but is a stable and functional tool that anyone can try out.

# Comparison with Existing Alternatives:

Compared to existing alternatives like Aegisub or commercial subtitle tools, EasySubber focuses on automating the subtitle generation process. It uses Whisper’s advanced speech recognition for accuracy and simplicity. While other tools require manual intervention or editing, EasySubber minimizes the need for human input, especially for straightforward transcription tasks.

# Demo Video:

If you're interested in seeing how it

/r/Python
https://redd.it/1fanpww
Native bit size, Arbitrary-Precision Arithmetic

Okay so I have a homework question to compare the int factorial and the float factorial of 200 and to explain what I find. For reference 200! results in a answer and 200.0! results in ∞. I’m like 90% sure the professor want an answer along the lines of “the calculated value exceeds (overflows) the maximum value that can be represented by the data type.” Especially given this is not a compsci class. Great, that’s easy. BUT I was like why, and so it took me a while because I’m a pretty new to programming and struggle with a lot of the terminology but I ended up coming across bignum. Now, the general idea of bignum makes sense to me… I understand how the arrays are structured beyond the bit size of the cpu, what I don’t understand is where the bit size comes in. Here’s my thought process: I understand that python uses the bit size to binarily encode the output - I think this is our base array and each individual 0 or 1 is an array. In order to maximize performance python can assign anywhere from 0 to 1073741823 = 2^30 digits to each array… ie

/r/Python
https://redd.it/1fb1yg5
PyBay 2024 - September 21 - San Francisco, CA

PyBay 2024 is coming up in San Francisco on Saturday, September 21, 2024. Join us for our 9th annual regional Python conference—a one-day, two-track event packed with insightful talks, great networking, and community connections.

Your ticket includes access to all sessions, networking opportunities with sponsors, lunch, and all-day coffee. If you're in the SF Bay Area or can make it to San Francisco on the 21st, we’d love to see you there!

Date: September 21, 2024 (Saturday)

Location: San Francisco, CA

More Info: https://pybay.org/
Speakers: https://pybay.org/speaking/
Tickets: https://pretix.eu/bapya/pybay-2024/

We hope to see you at PyBay 2024!

/r/Python
https://redd.it/1fan40b
ecommerce inventory data

curious to know if anyone here knows the architecture used to store inventory data of millions of products which is accessed by millions of users via frontend who shop at large ecommerce websites like amazon?

note that the inventory count field of these products is continually updated on the backend to reflect the most up to date information and data.

users shopping online via the frontend web or mobile app get the product data back instantly to add to their carts.

i was wondering what's the magic used to achieve this kind of performance for data that is also being constantly updated.

/r/flask
https://redd.it/1fb26q5
Streaming output from a chat-bot

I’m trying to make a Flask interface for an assistant I have created.

The assistant is setup correctly and streams output to a console perfectly. However, I am having a lot of trouble figuring out how to set up a Flask-app to stream the output for the chat bot correctly.

Does anyone have any examples of a Flask-interface with streaming that I could follow?

Here is the code that I have. It is working, but the streaming functionality is not. Instead of posting a chunk every time the assistant output is updated, it only posts chunks when the buffer limit is reached (several hundread words). Additionally, I have no idea how to integrate the streaming output into a typical chat-interface that shows the last few back-and-forths.

def chatstream():


# the chat
session contains assistantid, thread, and client instances
chat
session = currentapp.config['chatsession']

# using the stock event handler suggested here; https://platform.openai.com/docs/assistants/quickstart
handler = EventHandler()



/r/flask
https://redd.it/1farjm2
"detail": "No DocumentComment matches the given query." Django Rest Framework issue

In my modelviewset, I tried destroy function but it was not working, but when i tried to get object from id, it works, weird,. This is my viewset class.

class DocumentCommentView(viewsets.ModelViewSet):
   
    permissionclasses = (AdminStaffPermission,)
    queryset = DocumentComment.objects.all()
    serializer
class = DocumentCommentSerializer
   
    def getqueryset(self):
       
        document
id = self.kwargs.get('pk')
        if documentid :
            # print("ok ia m get")
            # breakpoint()
            return DocumentComment.objects.filter(document
id=documentid)
        return DocumentComment.objects.all()
   
    # def perform
destroy(self, instance):
    #     print("iam here")
    #     breakpoint()
    #     user = self.request.user
   

/r/django
https://redd.it/1faw8fr
Yes another question

when i try to run this command :
for label in labels:
!mkdir {'Tensorflow/workspace/images/collectedimages//'+label}
cap = cv2.VideoCapture(0)
print('Collecting images for {}'.format(label))
time.sleep(5)
for imgnum in range(numberimgs):
ret, frame =
cap.read()
imagename = os.path.join(IMAGES
PATH, label, label+'.'+'{}.jpg'.format(str(uuid.uuid1())))
cv2.imwrite(imgname, frame)
cv2.imshow('frame', frame)
time.sleep(2)

if cv2.waitKey(1) & 0xFF == ord('q'):
break
cap.release()

it shows this error:
The syntax of the command is incorrect.

Does anyone know why?

/r/IPython
https://redd.it/1fb6v04
Astral.sh (the company behind uv) paid product: is it going to be a Heroku replacement?

As you might know Astral, the company behind uv and ruff, are a small company but have venture capital funding. And right now they are not making money at all (but of course they're building awesome tools!)

I listened to the Talk Python podcast episode 476 where u/mikeckennedy & Charlie Marsh discuss the new capabilities uv has.

And it got me thinking, since uv is now able to install specific python versions, and since they stated they don't want to charge for features in uv ever, but are planning on charging for features adjacent to it that you might need to get your code up and running, could it be they'll be building a Heroku replacement? Certainly when you're wanting to build a Heroku-like thing it can be beneficial to allow users to specify their exact python version and have ways to install it.

I think it might be very cool and I'm sure there's a lot of opportunity in that space.

Does anybody know if Charlie Marsh or other Astral people ever discussed their plan to make money in more detail?

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