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
Contact users via email

How do you send emails to your users with Django, be it account activation, information about upcoming maintenance work, news?

/r/django
https://redd.it/106gwis
edit multiple rows

i have a template in django which displays lets say some info abut a book in a tabular form.lets say there are 3 books,can i edit these book's info by clicking an edit button.remember this is to edit multiple values simultaneously much like a bulk edit.

/r/django
https://redd.it/106lukv
(Taggit Library) - Adding a foreign key to taggittag model. Should I create a new table, or extend Tag?

Hey!

Right now taggit\
tag comes with two fields: name and slug. This means all tags added to my application are global and can't be separated by the account that's using it. Therefore I'd like to add a foreign key to the model;account = models.ForeignKey("Account", on_delete=models.CASCADE)

​

Can anyone suggest ways of doing this? I think I need to make my own model that extends taggit-tag, with the same name and add the extra field. I can then also extend the save() method to ensure an account_id is being added (which I can derive from the object I'm tagging) .

Something like this:

from django.db import models
from taggit.models import Tag


class Tag(Tag):
account = models.ForeignKey("Account", on_delete=models.CASCADE)
super()


​

But I could be waaaay off. Can anyone provide insights to this?

/r/django
https://redd.it/106eh9x
How to avoid circular reference to SQLAlchemy.db.Model?

I have a module "resources" that facades access to my SQLAlchemy db. It has an "open" function that assigns a global db variable (simplified):

db = None

def open():
global db
db = SQLAlchemy(app)

I also have a module "models" defining my models, which includes code like:

class thing(resources.db.Model):
__tablename__ = "thing_table"
...

When I run the code, I get an error because before the open() function is called, db = None, so resources.db.Model is undefined.

> AttributeError: 'NoneType' object has no attribute 'Model'

How can I get the references right?

/r/flask
https://redd.it/106wiqi
Deployed gunicorn flask app to Render.com but slow startup

Normally, it is pretty quick to load the website. But whenever I don’t access the website in awhile, the workers exit, and so when I try to access the website again, the workers have to boot up again and it takes much longer. Is this normal? How do I make it so the load time after inactivity is quicker?

/r/flask
https://redd.it/106uz8g
Datatype bug when trying to update database

Hello,

I am trying to make a route that will update my database. However, the data is somehow being changed into a tuple instead of being a string. The stored data is a string. The data from the form is a string. However, when I go to update the existing data it is somehow a tuple?

@app.route("/character/<int:characterid>/edit-core-details", methods=["GET", "POST"])
def edit
corecharacterdetails(characterid):
campaigns = Campaign.query.all()
requested
character = Character.query.get(characterid)
form = forms.EditNameRaceClass()
if form.validate
onsubmit():
print("Before")
print(type(
requestedcharacter.name))
requestedcharacter.name = form.name.data,
print("After")
print(type(
requestedcharacter.name))
print("form data")
print(form.name.data)


/r/flask
https://redd.it/106cv2n
Monday Daily Thread: Project ideas!

Comment any project ideas beginner or advanced in this thread for others to give a try! If you complete one make sure to reply to the comment with how you found it and attach some source code! If you're looking for project ideas, you might be interested in checking out Al Sweigart's, "The Big Book of Small Python Projects" which provides a list of projects and the code to make them work.

/r/Python
https://redd.it/106yoak
Fixing Python's "Cachetools" Library

"Cachetools" has become a cornerstone of Python cacheing libraries, but it has a few issues:

# 1. cachetools.LFUCache

Slow insertion times when the cache is full. When the cache is at capacity and a new item is inserted, the cache automatically handles eviction of the least frequently used item. Under the hood, cachetools uses a `Collections.Counter` object as it's interface to track item usage frequencies. When an item is evicted, Cachetools calls the `Counter.most_common()` API to retrieve the least frequently used item. This method creates a copy of the original underlying dictionary and sorts it by-key. Python uses `Timsort`, which is a O(n*logn) operation plus copy overhead. When the cache is large, this results in concerningly slow insertion times. With a cache size of 16384, median insertion times are \~0.6 microseconds (1e-6). When the cache is full, P90 and P99 insertion times are 540 and 600 microseconds (1e-6), a \~90,000% and \~100,000% increase from the median, respectively.

To solve this, `cacheing` implements an LFUCache API with O(1) insertions, deletions, and gets using a doubly linked list in the backend. This reduced P90 and P99 insertion times by \~45,000% and \~50,000%, respectively.

# 2. cachetools.TTLCache

This is a great time aware cache implementation. The issue is

/r/Python
https://redd.it/1077q6z
Thoughts on nested / inner functions in Python for better encapsulation and clarity?

Been loving Python for 7+ years not and still going strong. I recently found myself writing more and more inner functions to encapsulate logic easier and make otherwise rather polluting/dead functions stick out less.

I like it, because it allows me to write way cleaner and less bloated code – clustering helper-functions to only where they need to be. Also decreases cognitive load considerably by not having to keep track on where a helper function is being used.

But it has gotten to a point where I'm genuinely concerned, because I have also started defining lambdas in inner-functions too! I know lambda shouldn't be used and PEP checker complains too, but it's so handy when combined with list comprehensions…

What are your thoughts on this?
Do you use nested functions yourself or do you consider it bad practice? Where else do you put helpers?

---

An example would be the following code:

def sendmail(
*,
subject: str,
body
plain: str,
sendto: Union[List[str], str, List[User], User],
send
cc:

/r/Python
https://redd.it/106rsv8
High-Quality Numpy/PyTorch/Pandas Practice Problems

I've been finding Practice Probs an excellent resource for practice problems in Numpy over the last week after the creator u/neb2357's post about it here last week -- it's the closest thing I've found to LeetCode for data science. Thought I'd share in case others find it helpful to get a second opinion, and would love to hear if anyone knows of similar high-quality resources for these topics!

/r/Python
https://redd.it/106q8ux
Adding better DX to my package

After more than a year of active development, I finally publish my package to PyPI!

```bash
pip install socketify
```

After some people asks to also create a WSGI and ASGI server to improve projects using other frameworks, I worked hard to get it right.

But in the end, we outperform uvicorn and meinheld with Flask, Django, Emmett, FastAPI, and Falcon in TechEmPower plaintext with our WSGI and ASGI servers!

And we got the Top 1 with socketify itself!

https://www.techempower.com/benchmarks/#section=test&runid=7ce481b2-49ec-4a4d-952d-bb1334d4a4ad&test=plaintext&l=hra0hr-35r

Also added a CLI tool with very familiar options for uvicorn and gunicorn users

CLI: https://docs.socketify.dev/cli.html

Also added lifespan (start and shutdown) events to socketify itself, and added an improved DX for routing and support to Extensions/Plugins.


```python
# main.py
from socketify import App

def run(app: App):
@app.on_start
async def on_start():
# we can start connection pools here
pass

@app.on_shutdown
async def on_shutdown():
# and here we can clean connection pools
pass

router = app.router()
api = app.router(prefix="/api")
private =

/r/Python
https://redd.it/107abiy
My Improved Verlet Physics Engine is on Github!

Some of you may remember this post, in which I showcased a cloth simulation I made in pygame. Well, that physics engine is finally done, and I posted it on Github here!

The sandbox that comes with it requires pygame to run. As of now, there is a double pendulum demo, but if you read the documentation, you should be able to easily create a cloth.

Feedback is appreciated!

/r/Python
https://redd.it/106r96x
I am a beginner coder and I want to be a web developer but I'm in a bit of a financial crunch, so is it possible for me to learn enough within 4 months and get a developer job? Any company is fine.



/r/Python
https://redd.it/107bo4p
chafa.py - Terminal graphics with Python

Hello r/Python! I'm here to introduce you to a project I've been working on called chafa.py [source](https://github.com/GuardKenzie/chafa.py). These are Python bindings for the amazing terminal image visualizer [Chafa](https://github.com/hpjansson/chafa).

## What does it do?

Well, Take for example, this [image of a snake](https://raw.githubusercontent.com/GuardKenzie/chafa.py/main/examples/snake.jpg). With a few lines of Python, it is rendered to:

https://preview.redd.it/2av1zu75q0ba1.png?width=400&format=png&auto=webp&s=b9a9563ac30602e7d0b12a2313de0685cbf681cb

It takes image data and converts it to graphics formats (kitty/sixels) or ANSI/Unicode characters suitable for display in your favorite terminal emulator.

in reality, the first few lines of the image is just the following characters:

▂▂▃▃▀▅▁▃▀▅▆▆▆▁▃▃▀▘╴▝▖▃▃▀▆▆▆━▂▃▀▅━▀▂▂┷▆▆▅
▃▀▀▁▃▅▔▔▅▂▀▅▆▃▃▂▂▁▁▁▋▂▁╶━▂▃▀▀━━─━┷▀▅▆▔▔▔
▃▅▆▔▂▂▀▀▀▀▀▀▂▂▀▅▔▔▃▆▃╷▝▔▆▀▁▅▆▔━▀▅▆▔▅▆━▂▂
▀▃▀▃▀▃▅▀▅▃▃▀▊▔▌▊▖╵┕▃▅▆▖▖▅╸▘━━━━━━━━▅▅▅▅▅

along with some terminal escape sequences to set the background and foreground colors. This image was rendered with the few lines of code I have included at the end of this post.

## Where can you get it?

Check out the [installation](https://chafapy.mage.black/usage/installation.html) page in the docs for full, up-to-date instructions. Basically, this is what's up:

**Chafa.py depends on**

* [Chafa](https://hpjansson.org/chafa/download/)
* [MagickWand](https://imagemagick.org/index.php) if you want to use the included Loader class to load images.
* Python 3.5 or newer

Chafa.py is available on PyPi and can be installed with

pip install chafa.py

## How do you use it?

Check out the docs at [chafapy.mage.black](https://chafapy.mage.black). They include [more

/r/Python
https://redd.it/107e2j9
I have trouble reading the csv file.

I'm currently learning how to use Jupyter Notebook. I use Jupyterlite for practicing since i had trouble installing jupyter on my PC.

I wanted to try out the pandas.read_csv command but it has trouble finding the path to the csv file. I had uploaded it on /data but it didn't work.

I used the pwd command to see where the notebook was installed. (I don't know if the server installs them on the pc , couldn't find any information about that)

Does anyone know how to find the path so i can go back to practicing ?

&#x200B;

https://preview.redd.it/ufpchtpttzaa1.jpg?width=1704&format=pjpg&auto=webp&s=23c5eba4a9cc52541701ab5e854ccda5228ae688

/r/JupyterNotebooks
https://redd.it/107awrk