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
Facing problem with sending JWT cookie to frontend

So, I have this login view,

     


@apiview(['POST'])
def login(request):
    username = request.data.get('username')
    password = request.data.get('password')


    user = authenticate(username=username, password=password)


    if user is not None:
        refresh = RefreshToken.for
user(user)


        response = Response({
            "user": {
                "id": user.id,
                "username": user.username,
                "email": user.email,
                "name": user.name  # Assuming your User model has 'name'
            },
            "success":

/r/django
https://redd.it/1iw7t5y
Learn concepts and ideas easily with my new web app

Hi guys,


Feel free to take a look at my new web app that is designed to help people quickly and easily understand concepts or terms that they hear.


Check it out at https://teachmelikefive.com/

thanks

/r/flask
https://redd.it/1iw8gds
I Built an Open-Source Algo Trading Framework for Instant Backtests & Live Deployment

Github : https://github.com/himanshu2406/Algo.Py

# What My Project Does

So I've been working on a framework made in Python that makes live trading incredibly easy, and even almost no-code !

It seamlessly integrates with any preset backtesting strategy, allowing you to take them straight to live trading with minimal effort.

Dashboard Overview : https://youtu.be/OmlaBnGcUi4?si=e1aizaIaYpRNMHFd

One-Click Backtest Deployment Overview : https://youtu.be/T\_otTHdLCCY?si=A7ujRzV6I5ESfgEQ

It's still in very early beta, but I’ve packed in as many functional features as possible, including:

# Key Features

Intuitive Dashboard
Easily backtest, view results, save and deploy in a single click.
Auto-Detects Your Strategy – If your function generates valid entry/exit signals, the framework will automatically detect and integrate it.
Scheduler for Automation – Run your entire pipeline at custom fixed intervals or specific times
Custom Data Layer (Finstore):
Stores and streams data using a Parquet-based data lake, making it much faster than traditional databases.
Multi-Broker Support – Execute across multiple brokers with real-time debug logs via Telegram.
End-to-End Pipelines – Effortlessly fetch, store, and stream data for crypto, equities, and more.
Multi-Asset Backtests :
Backtest a strategy across an entire market across hundreds of symbols and thousands of data

/r/Python
https://redd.it/1iwccvr
The pitfalls of benchmarking your package like numpy does

Recently I decided to use [asv (Airspeed Velocity)](https://asv.readthedocs.io/en/latest/) for benchmarking performance of [django-components](https://django-components.github.io/django-components) (we want to be faster than Django templates). asv is used by numpy, scipy, or astropy.

With asv, we are able benchmark render time and memory consumption.

There was a lot of pitfalls and even a couple of bugs I had to fix to get things working. I've documented them all in [this PR](https://github.com/django-components/django-components/pull/999) (also contains screenshots).

The PR covers these use cases:

* Performance report on pull requests.
* Benchmarking the package across releases.
* Displaying performance results on a website.

I'm not big on writing blogs and tutorials (at least not by myself), so I hope to share resources at least this way. The PR is still very informative if you want to introduce benchmarking to your project.

If you find this useful and you'd want to make this into a more human-digestible format, send me a message!

/r/Python
https://redd.it/1iw96ed
Made a Python library for simulating the combined effect of different time-series patterns

GitHub: https://github.com/TimoKats/pylan

PyPi: https://pypi.org/project/pylan-lib/

# What My Project Does

Python library that can be used to simulate the combined effect of financial patterns (e.g. salary, inflation, investment gains, etc) over time so you can plan your finances better.

# Target Audience

Personal usage for now.

# Comparison

\- SaaS financial planning tools (like ProjectionLab) work through a webUI, whereas here you have access to all the Python magic in the same place as you do your simulation.

\- Excel....

\- Write your own code for this is not super difficult, but this library does provide a good framework of dealing with various schedule types (some of which cron doesn't support) to get to your analysis more quickly.

/r/Python
https://redd.it/1iwk95c
Flask partitioned cookies problems

I am working on a flask backend and I have a problem with the cookies, specifically with the partitioned cookies.When I config the session cookie here:

def create_app():
app = Flask(__name__)
app.config['SECRET_KEY'] = 'chamba machamba'
# Configure session cookies for local development
# Make sure that domains are the same (for example localhost)
app.config['SESSION_COOKIE_SAMESITE'] = None # Allow cross-site cookies
app.config['SESSION_COOKIE_SECURE'] = True
app.config['SESSION_COOKIE_PARTITIONED'] = True
app.config.update()

I get the error:

`Cookie “session” has been rejected because it is foreign and does not have the “Partitioned“ attribute`

So I did a little digging and tried to add the cookies when I log in / sign up. So I deleted this part and added this to my sign up and log in:

response = make_response(jsonify({'message': 'User created successfully'}))

response.headers.add('session',

/r/flask
https://redd.it/1iw8vkb
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/1iwogfe
Django app deletion from a django project

I need to remove a Django app from my project. This app has ForeignKey relationships with models in other apps. Several migrations involving this app have already been applied to the database. I'm concerned about data loss in the related models of other apps if I simply delete the app.
- What's the safest and most recommended way to remove an app, considering the existing ForeignKey relationships and migrations?
- What are the best practices, and what should I avoid doing to prevent data corruption or loss?
- Is it possible to keep the old data of deleted models?

---


I have tried these steps but face some dependency issues which need manual intervention. I want to know the recommended ways.

1. Delete dependent migrations for dependent_app
`rm -rf dependent_app/migrations`

2. Make necessary changes for the models of dependent_app
3. Recreate migrations
`python manage.py makemigrations dependent_app`

4. Delete all migrations for the my_app
`rm -rf my_app/migrations`


5. Apply fresh migrations
`python manage.py migrate --fake`


6. Remove imports, urls and other associations

7. Remove from INSTALLED_APPS

```
INSTALLED_APPS = [
#Other apps
'my_app', # Remove this line
]
```


/r/djangolearning
https://redd.it/1iw2ned
D.O. litespeed droplet with django

Hello I just fired up a droplet with openlitespeed and django. So it comes preinstalled with an app and a project right? So I put in my model into models.py and receive this error when trying to migrate:
from django.core.management import execute_from_command_line

ModuleNotFoundError: No module named 'django'



The above exception was the direct cause of the following exception:



Traceback (most recent call last):

File "/usr/local/lsws/Example/html/demo/manage.py", line 22, in <module>

main()

File "/usr/local/lsws/Example/html/demo/manage.py", line 13, in main

raise ImportError(

This is prebuilt image with django i suppose. Ihave the virtualenvironment activated. Why is this error coming out ? Thanks to those who can help



/r/djangolearning
https://redd.it/1ivlyg5
How can I retain django form data after a user is redirected

I am trying to create a complicated form set up that has the user authenticate with google as part of the steps to the form.

I'm currently using django-formtools library and what I want is:

1. User fills out data in form 1
2. Based on data filled in form 1, have them authenticate with google on step 2.
3. Once authentication is done, redirect them back to the form, but on to the next step.

I'm currently using the SessionWizardView, but what is happening is that after Google auth is done, it redirects back to the form page but its back on Step 1 of the form, and not the correct 3rd step that I would want it to be on, and it doesn't seem to have record of what the user has already submitted.

Is there a better way to do this without using the django-formtools library? Seemed like a match for the workflow I want, but I need a way to get back in the form flow after the redirect is done.













/r/django
https://redd.it/1iwm4jc
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/1iwdbgs
Shareable product or platform to demonstrate coding project skills?

Does anyone have any recommendations for a platform or product (paid or free) that lets you record yourself coding on a moderately complex project?

Basically, I'm aiming for something that would obsolete doing toy exercises for every employer you interview with. Something you could slap on your resume and they just navigate to a link to view it. Ideally it includes AI completions or is compatible enough you could use an IDE with them.

By moderately complex I mean going many steps above LeetCode type problems. You would need to demonstrate that you can use tools to quickly navigate and understand a decent size codebase. It would need to be something you couldn't memorize.

/r/Python
https://redd.it/1iwwcjk
Open-Source MICT AI Ethics Toolkit: Practical Examples for Mitigating Bias and Hallucinations

Hey r/python,

I'm excited to share an open-source project I've been working on with the Boredbrains Consortium: the **MICT AI Ethics Toolkit**. It's designed to help developers build more responsible and trustworthy AI systems by providing practical tools and examples for addressing ethical concerns. The toolkit is built on the **Mobius Inspired Cyclical Transformation (MICT)** framework, which provides a structured, iterative process for integrating ethical considerations *throughout* the AI development lifecycle.

**What My Project Does:**

The MICT AI Ethics Toolkit provides reusable Python (and JavaScript) functions, classes, and example implementations for addressing common ethical challenges in AI development. It's *not* a standalone framework; it's a set of tools designed to be integrated *into* existing projects, using the MICT framework for a structured approach. Currently, the toolkit includes:

* **Bias Detection:** Functions to calculate disparate impact ratios for binary classification models, helping you identify and mitigate potential biases in your datasets and models.
* **Hallucination Detection:** Functions for detecting potential hallucinations in large language model outputs, using simple string-matching against a knowledge base. (More sophisticated methods to come!)
* **Example Implementations:** Runnable examples demonstrating how to use these tools within a MICT cycle

/r/Python
https://redd.it/1iwunjl
Should I use Flask or React

I currently have access to a server which provides API endpoints which I cannot modify. I want to create a UI for it. Should I go for using Flask to fetch the data from the API using the routes, or just go straight to React?

My biggest problem is that this server only accepts basic authentication. If I use flask, I can have a login page where I ask the user for a username and password, I then query my API endpoint to see if I have the correct combination of username and password, and then save this username and password in a database (in hashed format). If I use React, I need to ask the username and password from the user and I have to either store this locally or in cache. I am assuming that if I do this, it will be stored in plain text.

My questions are:

1. Which implementation would provide more security and convenience? Flask or React?
2. Is it even stupid of me to think of using Flask instead of React?

P.S. First time asking here, and I am at my wits end trying to figure out which of the two I should use.

/r/flask
https://redd.it/1iwtroa
I finally implemented auto-complete in my terminal based productivity managers code editor, Ticked!

**NEST+**

* Fixed various QOL issues and bugs pertaining to the general code and text editing experience
* Added support for general code completion via Jedi and a custom auto-completion popup
* **Only works in Python currently**
* Local variables, methods, etc. are stored and are automatically appended to the suggestion list.
* Python syntax instantly accessible; common decorators, standard libraries, operators, etc.

[Read the full release notes here](https://github.com/cachebag/Ticked/releases/tag/v0.3.1)

**Install with Homebrew:**

`brew tap cachebag/ticked`
`brew install ticked`

**Install via Pypi:**

`pip install ticked`

I appreciate everyone being so patient and continuing to suggest improvements. School and work has been crazy so far this year, but this project is going to be fleshed out in great detail in the coming months. I'm working on a lot of revamping of the system and continuously improving upon existing features instead of falling to scope creep.

/r/Python
https://redd.it/1iwghxb
Django Template not working as expected

Hello everyone.

I have the following objects

```
class ManyToManyObjects(models.Model):
id
ObjectA = models.ForeignKey('A')
ObjectB= models.ForeignKey('A') #Different Objects, but for sake of argument lets say they are the same.
Objectmatch = models.CharField}
ObjectScore = models.IntegerField()

Class A(models.Models):
id
data
```
(Redacted some of it for simplicity, but these are the main fields for this interaction.)

And I have the following in my Django Template:
```
{% assign prevmatch '' %}
{% assign lastA ''%}
{% assign lastB ''%}
{% for match in ManyToManyObjects %}
{% if prevcod != match.Objectmatch %}
... //just some sort of header for the table


/r/djangolearning
https://redd.it/1iu2c47
I built a new playground for Python

https://codiew.io/ide?t=py

Playground (backend) based on Docker images with Google gVisor isolation.

It supports program arguments, pretty output for JSON and I will add a lot feature soon



/r/Python
https://redd.it/1ix0rf0
How do i resolve "Working out of context"?

/r/flask
https://redd.it/1iwzzk2
Open-source reverse proxy to remove sensitive data from OpenAI API calls

Hi, r/Python!

I'd like to share the project I've been working on during the last few weekends.

- Code: https://github.com/edublancas/sanitAI
- Video tutorial: https://youtu.be/bdA7T6Z6YQ4

What My Project Does

SanitAI is a reverse proxy that intercepts calls to OpenAI's API and removes sensitive data. You can add and update rules via an AI agent that asks a few questions, and then defines and tests the rule for you.

For example, you might add a rule to remove credit card numbers and phones. Then, when your users send:

> Hello, my card number is 4111-1111-1111-1111. Call me at (123) 456-7890

The reverse proxy will remove the sensitive data and send this instead:

> Hello, my card number is <VISA-CARD>. Call me at <US-NUMBER>


Target Audience

Engineers using the OpenAI at work that want to prevent sensitive data from leaking.

Comparison

There are several libraries to remove sensitive data from text, however, you still need to do the integration with OpenAI, this project automates adding, and maitaining the rules, and provides a transparent integration with OpenAI. No need to change your existing code.

/r/Python
https://redd.it/1ix4m99
Sparx automation hacks

It’s probably unlikely but i was wondering if anyone here could create a code that would automate your sparx homework and do it for you I’m not very technical in coding and i don’t know how but it would be something like from this yt video https://youtu.be/uu3VSDdSKCg?si=SlejJH9-soJ9Jydn

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