pythondaily | Образование

Telegram-канал pythondaily - Python Daily

1102

Daily Python News Question, Tips and Tricks, Best Practices on Python Programming Language Find more reddit channels over at @r_channels

Подписаться на канал

Python Daily

How can I change the name options of this selectField based on which table was selected earlier in the form?

Edit: I fixed this issue by setting name = (column name) in each of the classes

-------------



Pretty much I am using a tutorial to make a form that will change possible selection option based on a previous selection. eg. a user chooses to see data filtered based on site and then have another dropdown with the possible site options.

the tutorial I am using uses only one table (see image one) but I have three different tables that need to be available for selection.

so far I have tried using both a variable and a function to do this but neither have worked. (the variable returned multiple selections of sites.site_name for each id in the table and the function returned multiples of <function results.<locals>.tableOptionName at 0x10e386e50>.

If it helps, the column that contains the names I am trying to display is the the second column the table for all three.

what I have at the moment is in image 2

image 1

image 2

Thank you so much!

/r/flask
https://redd.it/1fbhsk1

Читать полностью…

Python Daily

Issues with Cloud Run Deployment

I've been trying to solve this deployment issue for 2 days now and am at my wits end. I've deployed on VPSs before but never a managed service like Cloud Run.

All of my request coming from the frontend are getting the Network Error: ERR\_TOO\_MANY\_REDIRECTS. From what I've gathered, there is likely and issue with the way django is processing the internal request from Cloud Run. The google documentation says that we need to add this to our settings.py:

CLOUDRUN_SERVICE_URL = env("CLOUDRUN_SERVICE_URL", default=None)
if CLOUDRUN_SERVICE_URL:
ALLOWED_HOSTS = [urlparse(CLOUDRUN_SERVICE_URL).netloc]
CSRF_TRUSTED_ORIGINS = [CLOUDRUN_SERVICE_URL]
SECURE_SSL_REDIRECT = True
SECURE_PROXY_SSL_HEADER = ("HTTP_X_FORWARDED_PROTO", "https")


I have added this and still continue to get these errors. I'm really not sure what else to look into or what could be causing this. I'm even will to pay you for your time if someone is willing to get on discord with me and help me work this out.

/r/django
https://redd.it/1fbcybz

Читать полностью…

Python Daily

Send self-destructible emails

I've recently built a small free project called DiscardDraft.

Built with Flask and Nextjs. It's a project that allows people to send emails that would be deleted right after being read.

Check it out here: https://discarddraft.me


/r/flask
https://redd.it/1fanapo

Читать полностью…

Python Daily

Announcing Djangonaut Space Session 3 Applications Open!
https://djangonaut.space/comms/2024-opening-session-3/

/r/django
https://redd.it/1faf7zz

Читать полностью…

Python Daily

"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

Читать полностью…

Python Daily

My first flask project, a code sharing app
https://snippy-share.vercel.app/

/r/flask
https://redd.it/1fanvzc

Читать полностью…

Python Daily

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

Читать полностью…

Python Daily

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

Читать полностью…

Python Daily

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

Читать полностью…

Python Daily

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

Читать полностью…

Python Daily

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

Читать полностью…

Python Daily

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

Читать полностью…

Python Daily

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

Читать полностью…

Python Daily

Desperate and Willing to pay for ALL-AUTH solution.

I have a problem. When a user signs up to my site using their email, then later logs in with email provider (eg. Google), all auth treats this like a new user and objects to them having the same email. How can I make it understand that it's the same user and give them access?

I've looked around for far too long and found nothing that solves this. I'm willing to pay for a solution, and I will make the answer public for all to benefit.

P.s apologies if I'm not allowed to solicit but after all, I am desperate.

/r/django
https://redd.it/1fac0m6

Читать полностью…

Python Daily

How To Perform Unit Testing in Flask
https://www.digitalocean.com/community/tutorials/unit-test-in-flask

/r/flask
https://redd.it/1fa9mno

Читать полностью…

Python Daily

Adding Python to Docker in 2 seconds using uv's Python command

Had great success speeding up our Docker workflow over at Talk Python using the brand new features of uv for managing Python and virtual environments. Wrote it up if you're interested:

https://mkennedy.codes/posts/python-docker-images-using-uv-s-new-python-features/

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

Читать полностью…

Python Daily

Python 3.13 RC2 Available Today - Python 3.13 available October 1st

Python 3.13 will drop on October 1st.

The second release candidate just dropped today.

Don't be afraid to upgrade.

Install the RC2 from here and run your regression tests for your applications, and be ready to upgrade to Python 3.13 the moment it becomes available on October 1st.

If any of your dependencies fail when running your application on the RC2, immediately raise an issue on their github and complain loudly that they need to make the changes to make it compatible as well as publish binary wheels.


https://www.python.org/downloads/release/python-3130rc2/

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

Читать полностью…

Python Daily

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

Читать полностью…

Python Daily

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

Читать полностью…

Python Daily

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

Читать полностью…

Python Daily

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

Читать полностью…

Python Daily

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

Читать полностью…

Python Daily

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

Читать полностью…

Python Daily

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

Читать полностью…

Python Daily

Djangonaut Space - New session 2024
https://www.djangoproject.com/weblog/2024/sep/06/djangonaut-space-new-session-2024/

/r/django
https://redd.it/1fao07b

Читать полностью…

Python Daily

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

Читать полностью…

Python Daily

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

Читать полностью…

Python Daily

Pass JSON to Templates using Include

How do I pass Json to Template from main Template where the variable gets defined not by view.py but main_template.html

template

main template

In the above example, I want to define the icon here itself in the main_template.html rather than the view.

/r/django
https://redd.it/1faee90

Читать полностью…

Python Daily

Need Help with Offline License System and Periodic Server Checks in Flask App

Hi everyone,

I’ve developed a local Flask app that uses SQLite and a Tkinter interface to run locally. I recently added a license system but think it could be improved, especially when it comes to managing license expiration and periodic checks.
Here’s how my current system works:

I have an admin dashboard (hosted on my server) where I generate and manage licenses.
Each license has a start date, end date, and activation_status (default = 0), and I generate an activation code for the user.
The user enters a username, password, and the activation code in the app, and the app sends a request to my server to verify the license and get the relevant dates and status.
If the license is valid, I store a hashed combination of the username, password, and hardware ID (HWID) in a file called license on the user's device. The start and end dates are also saved in a local SQLite database on the user’s device.
The app is mostly designed to work offline, but the activation process requires internet access.
I have a login_required decorator that checks the license status before allowing access to any protected route. If the license has

/r/flask
https://redd.it/1fa9g27

Читать полностью…

Python Daily

Django News - Django security releases issued: 5.1.1, 5.0.9, and 4.2.16
https://django-news.com/issues/249

/r/django
https://redd.it/1fac6s4

Читать полностью…
Подписаться на канал