TG Telegram Group Link
Channel: Python Daily
Back to Bottom
Error thrown by VS Code when Main.py is Run

Dear team,

Error : raise AssertionError(

AssertionError: View function mapping is overwriting an existing endpoint function: form

Code:

from flask import Flask, render_template,request
import joblib
model=joblib.load('E:\\Courses\\LearnBay\\Deployment\\Pickle\\diabetic_joblib.pkl')
app=Flask(__name__)
u/app.route('/')
def hello():
return render_template("main.html")
u/app.route('/ConsellingForm')
def form():
return render_template("form.html")
u/app.route('/SubmitForm',methods=['post'\])
def SubmitForm():
pregnancies=int(request.form.get('Pregnancies'))
Glucose=int(request.form.get('Glucose'))
BloodPressure=int(request.form.get('BloodPressure'))
SkinThickness=int(request.form.get('BloodPressure'))
Insulin=int(request.form.get('Insulin'))
Age=int(request.form.get('Age'))
BMI=int(request.form.get('BMI'))
DiabetesPedigreeFunction=int(request.form.get('DiabetesPedigreeFunction'))
prediction=model.predict([pregnancies,Glucose,BloodPressure,SkinThickness,Insulin,Age,BMI,DiabetesPedigreeFunction\])
if prediction[0\]==1:
return 'You are diabetic'
else:
return 'You are Non diabetic'
app.run(debug=True)

​

please guide on how to resolve the error.

/r/flask
https://redd.it/1cghpzv
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/1cgem9q
What is the best way to deploy flask app that takes uploaded image and renders?

I work in image quality team and I have a flask application that allow users to upload images and saves it to static folder and renders from there for comparison. I sometimes used 'session' to store it temporarily too. The way images are loaded is referring the exact path name of image in 'static' folder.

For now, I need to deploy this app on cloud or intranet or something else (need to figure out which is the best). I want this app to be used across other teams just by accessing web url and let them upload images.

Since this is my first time deploying web app handling file uploads, I'm not sure how it works. Could you please share your good experience with me?

thank you :)

/r/flask
https://redd.it/1cg9xc7
How to set foreign key to str method of a model without making alot of db calls?

I'm having two models
class A(models.Model):
name = models.CharField()


class B(models.Model):
model_a = models.ForeignKey(A)

def __str__(self):
return self.model_a.name



This is making alot of db calls. how to fix it?

​

/r/django
https://redd.it/1cglc6y
Model Setup Help

I’m fairly new to Django framework but I understand the basics. I am currently trying to create a model system that allows me (admin) to create services for my business. My business performs Home Services such as home cleaning, handyman, furniture assembly etc.

My issue comes when creating a model where two goals are met:

1. Allow for creation of Services so I can dynamically load the data on the website.

2. Allow user to select a service, a sub service, and the sub service required fields.

Example. User wants to book a home cleaning Standard cleaning. If they select this service, the required fields appear, which would be Number of Rooms and Bathrooms. This service also as Additional Services ( laundry, dishes etc.)

Or they select Handy man Hourly and the required field is number of hours.

Then they book this service. I want the details ( required fields to appear as well for each service)

I got this so far:

Service model:
- Name
- description
- total-price

Now this is where I kinda get lost. There’s really no tutorials and ChatGPT gives me several options and they all differ exponentially.

Should I create another model for each service? Or can I create a model where

RequiredFields
- 1-M Services
-

/r/djangolearning
https://redd.it/1cgjpqj
Working on a Django Project Each Month For Six Months to build a Resume

Hello, I've been learning the basics of Django since the beginning of 2024. And I've built a range of simple apps like Todo's and others. Now I want to step up the level of projects and build and start on with real projects.

Please can you help me propose robust type of projects people want to use out there.

/r/django
https://redd.it/1cgpnhd
tach - a Python tool to enforce modular design

https://github.com/Never-Over/tach

What My Project Does

tach is a lightweight Python tool that enforces boundaries and dependencies in your Python project. Inspired by nx, tach helps you maintain a decoupled and modular Python codebase.

An earlier version of this tool was called modguard, which we shared here.


By default, Python allows you to import and use anything, anywhere. Over time, this results in modules that were intended to be separate getting tightly coupled together, and domain boundaries breaking down. We experienced this first-hand at a unicorn startup, where the eng team paused development for over a year in an attempt to split up packages into independent services. This attempt ultimately failed.

This problem occurs because:
- It's much easier to add to an existing package rather than create a new one

- Junior devs have a limited understanding of the existing architecture

- External pressure leading to shortcuts and overlooking best practices


Efforts we've seen to fix this problem always came up short. A patchwork of solutions would attempt to solve this from different angles, such as developer education, CODEOWNERs, standard guides, refactors, and more. However, none of these addressed the root cause.

With tach, you can:

1. Declare your packages (package.yml)

2. Define dependencies between packages (tach.yml)

3. Enforce those dependencies (tach check)


You

/r/Python
https://redd.it/1cgsopt
Analyzing Python Compression Libraries: zlib, LZ4, Brotli, and Zstandard

Source Code: [https://github.com/dhilipsiva/py-compress-compare](https://github.com/dhilipsiva/py-compress-compare)

# Analyzing Python Compression Libraries: zlib, LZ4, Brotli, and Zstandard

When dealing with large volumes of data, compression can be a critical factor in enhancing performance, reducing storage costs, and speeding up network transfers. In this blog post, we will dive into a comparison of four popular Python compression libraries—zlib, LZ4, Brotli, and Zstandard—using a real-world dataset to evaluate their performance in terms of compression ratio and time efficiency.

## The Experiment Setup

Our test involved a dataset roughly 581 KB in size, named sample_data.json. We executed compression and decompression using each library as follows:

* Compression was performed 1000 times.
* Decompression was repeated 10,000 times.

This rigorous testing framework ensures that we obtain a solid understanding of each library's performance under heavy load.

## Compression Ratio

The compression ratio is a key metric that represents how effectively a compression algorithm can reduce the size of the input data. Here’s how each library scored:

* Zlib achieved a compression ratio of 27.84,
* LZ4 came in at 18.23,
* Brotli impressed with a ratio of 64.78,
* Zstandard offered a ratio of 43.42.

From these results, Brotli leads with the highest compression ratio, indicating its superior efficiency in data size reduction. Zstandard also shows strong performance, while LZ4, though lower,

/r/Python
https://redd.it/1cgk4xi
How to build single query in Django with related models and count

I did not use the Django for a years and tried to modify some old codebase today.

I have models:

class MetaTemplate(CreatedModifiedBase):
type = models.CharField(max_length=200)

class Project(CreatedModifiedBase):
name = models.CharField(max_length=200, unique=True)
members = models.ManyToManyField( User, through=ProjectMembership, related_name="annotation_projects_as_member", blank=True, )
metatemplate = models.ForeignKey( MetaTemplate, on_delete=models.SET_NULL, related_name="project", null=True )

class Dataset(CreatedModifiedBase):
name = models.CharField(max_length=200)
project = models.ForeignKey( Project, related_name="datasets", on_delete=models.CASCADE )

class Task(CreatedModifiedBase):
dataset = models.ForeignKey( Dataset, related_name="tasks", on_delete=models.CASCADE, null=True )

class Completion(CreatedModifiedBase):
task = models.ForeignKey(Task, related_name="completions", on_delete=models.CASCADE)
annotator = models.ForeignKey( User, on_delete=models.SET_NULL, related_name="annotation_completions", null=True, )

I have a method which returns number of incomplete Tasks.

def get_incomplete_tasks(self, user, project_id, target_completion_count) -> int:
return (
Task.objects.annotate(counts=Count("completions"))
.filter(


/r/djangolearning
https://redd.it/1cg77rr
Need help with my application idea

Recently I have been taking 100 Days of Python by Angela Yu and have been making good progress (\~Day 20). This has lead me to accumulating a bunch of 'mini projects' that I would like some way to show off on my website. Essentially I would like to have a list of all my projects and when a user clicks a button they will get a popup or modal of that python script running. I would like the user experience to be similar to similar to if I ran 'python main.py' in my terminal to run the application.

Has anyone ever done something similar to this? I would like to have a way to present my progress in this course that goes above and beyond just linking to my GitHub. I hope this is enough information to get across my goal. Please let me know if I can provide more info.

/r/flask
https://redd.it/1cgyfxz
Managing Oauth logins for local testing

I have a Flask app which I've got up and running in pythonanywhere, but I want to develop it locally.

All the functionality is behind a Google Oauth login, but since the credentials for that are set to the web address, I can't use it locally.

How do people typically manage this? I was wondering about setting some sort of local environment variable that skips the login, but that feels like bad practice.

/r/flask
https://redd.it/1ch14bh
R CRISPR-GPT: An LLM Agent for Automated Design of Gene-Editing Experiments

A new paper introduces CRISPR-GPT, an AI-powered tool that streamlines the design of CRISPR-based gene editing experiments. This system leverages LLMs and a comprehensive knowledge base to guide users through the complex process of designing CRISPR experiments.

CRISPR-GPT integrates an LLM with domain-specific knowledge and external tools to provide end-to-end support for CRISPR experiment design.

The system breaks down the design process into modular subtasks, including CRISPR system selection, guide RNA design, delivery method recommendation, protocol generation, and validation strategy.

CRISPR-GPT engages users in a multi-turn dialogue, gathering necessary information and generating context-aware recommendations at each step.

Technical highlights:

1. The core of CRISPR-GPT is a transformer-based LLM pretrained on a large corpus of scientific literature related to gene editing.
2. Task-specific modules are implemented as fine-tuned language models trained on curated datasets and structured databases.
3. The system interfaces with external tools (e.g., sgRNA design algorithms, off-target predictors) through APIs to enhance its capabilities.
4. A conversational engine guides users through the design process, maintaining coherence and context across subtasks.

Results:

1. In a trial, CRISPR-GPT's experimental designs were rated superior (see the human evals section of the paper for more).
2. The authors successfully used CRISPR-GPT to design a gene knockout experiment targeting four cancer genes in a human

/r/MachineLearning
https://redd.it/1cgyccx
Need Help!

So, I am trying to animate a list of .fits files.
Like, fits = ‘1.fits’, ‘2.fits’, ‘3.fits’, ……., ‘30.fits’

But I am get an error as list out of range or doesn’t have ‘writer’ method.

How can I fix this?

/r/IPython
https://redd.it/1cghsdl
Where should my code logic go? Help me structure my project

Hi everyone,


I am learning django for the first time and built a more or less stable website that I am working on (not deployed yet). The website is related to the automotive industry where a user asks for a model of a car and it shows him some specs and some calculation from my side.


The flow of info is like this:

(if the model has never been asked for) User inputs model of car -> My fetches some info using an API -> Makes calculations on this info -> Creates models -> View shows the info using templates


Now, the issue I have is that while starting this project I didnt use the fat-models way of working, so the API fecther is in a file called api_fetch.py and my calculations once the API is fecthed are done from another python file called calc_methods.py, so the flow is like this:

Django view (views.py) -> Fetch API (api_fetch.py) -> Calculate (calc_methods.py) -> Back to views -> Create Models


The file calc_methods.py has become so big (around 700 lines of code) that I am not in control anymore (maybe because I am a noob programmer too).


What would

/r/djangolearning
https://redd.it/1ch2r2i
AWS S3

Not sure if this is best place to ask this. However i wasnt sure where else to post it and this is my go-to for development help.

Im planning to use an S3 bucket to store user uploaded images. Ive heard loads of stories about people setting it up wrong or something and getting billed thousands. I have a friend whos going to help me set it up, more or less. just wanted to know if there is anything important i should be aware of...?

Ive set up stuff like rate limiting to the route which allows the use to upload an image. Im also planning to setup some form of image compression to minimize storage use.

Is there anything I should be aware of in regards to S3?

/r/flask
https://redd.it/1ch127t
Learning flask for intership

ok so i will be doing an intership during the last year of my university and for that

i choose flask over django/fast api


do you think its the better choice as i will only be doing this while i am still a student and ML is my main thing in future which i am doing alonside it?


or should i focus on django/fast api?

/r/flask
https://redd.it/1cgmmwu
Wednesday Daily Thread: Beginner questions

# Weekly Thread: Beginner Questions 🐍

Welcome to our Beginner Questions thread! Whether you're new to Python or just looking to clarify some basics, this is the thread for you.

## How it Works:

1. Ask Anything: Feel free to ask any Python-related question. There are no bad questions here!
2. Community Support: Get answers and advice from the community.
3. Resource Sharing: Discover tutorials, articles, and beginner-friendly resources.

## Guidelines:

This thread is specifically for beginner questions. For more advanced queries, check out our [Advanced Questions Thread](#advanced-questions-thread-link).

## Recommended Resources:

If you don't receive a response, consider exploring r/LearnPython or join the Python Discord Server for quicker assistance.

## Example Questions:

1. What is the difference between a list and a tuple?
2. How do I read a CSV file in Python?
3. What are Python decorators and how do I use them?
4. How do I install a Python package using pip?
5. What is a virtual environment and why should I use one?

Let's help each other learn Python! 🌟

/r/Python
https://redd.it/1ch7whw
ConfigClass - simple dataclass inspired configuration

**What My Project Does**

I'm making a simple configclass for handling configuration in smaller projects and scripts. Goal is to be as simple to start with as creating a dataclass.

The module itself works off dataclass and when you use it you just define a dataclass as normal, but decorate it with @configclass() instead.

Example:

from configclass import configclass

@configclass()
class Settings:
foo: bool = False
url: str = ""
footoo: bool = True
my_model: str = "model.pt"

setting = Settings.load()

print(setting.foo, setting.footoo, setting.my_model)

From that you got

JSON config file support (config.json)
YAML config file support (config.yaml)
Command line support (argparse)
Env variables support (CONFIG_SETTINGNAME)

It also support nested structures via nested dataclass classes.

**Comparison**

It's meant as a quick and lightweight alternative to larger and more comprehensive config systems, for the small programs and scripts where you'd just use a dataclass, and maybe load the values from a config file.

**Target Audience**

Since it's pretty new and raw I wouldn't recommend it for heavy production settings or complex projects. That said, it should work fine for most cases.

While I've worked with python for quite some time, this is

/r/Python
https://redd.it/1chhm8x
sqlalchemy.exc.OperationalError: (sqlite3.OperationalError) no such table: Note

sqlalchemy.exc.OperationalError: (sqlite3.OperationalError) no such table: Note

\[SQL: SELECT "Note".id AS "Note\_id", "Note".title AS "Note\_title", "Note".text AS "Note\_text", "Note".created\_date AS "Note\_created\_date", "Note".importance AS "Note\_importance"

FROM "Note"\]

https://preview.redd.it/rugdz7astsxc1.png?width=320&format=png&auto=webp&s=5bd6238bcb9745243876ccdffb7651b1043d99a2

import flask
from flask import Flask, render_template
from flask import request, redirect, url_for
from flask_sqlalchemy import SQLAlchemy
from sqlalchemy.testing import db
from datetime import datetime


app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///notes.db'
db = SQLAlchemy(app)

class Note(db.Model):
__tablename__ = 'Note'
id = db.Column(db.Integer, primary_key=True)
title = db.Column(db.String(100), nullable=False)
text = db.Column(db.Text, nullable=False)
created_date = db.Column(db.DateTime, nullable=False)
importance = db.Column(db.Integer, nullable=False)


def create_tables():
db.create_all()
@app.route('/')
def index():


/r/flask
https://redd.it/1chjm12
HTML Embed Code:
2024/05/01 11:55:36
Back to Top