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
How do you make a non-unique, repeating id in flask?

I am making a notes-type app, and there are three database models-the user, documents, and chapters. Chapters have a parent Document and Documents have a parent User.

If I want to print the id's of one users documents, I would like it to start from 1,2,3,etc, for EACH user. If I have 3 users, and user 3 only has 1 document, I would like the id to be 1, and the next 2, etc, but instead it starts from like, 5, because it's including the other users. Does that make sense?

​

My Models

class Document(db.Model, UserMixin):
id = db.Column(db.Integer, primary_key=True)
user_id = db.Column(db.Integer, db.ForeignKey('user.id'))

class User(db.Model, UserMixin):
id = db.Column(db.Integer, primary_key=True)
documents = db.relationship('Document')

​

This User has only three documents, and I would like the id to start from 1, not continue from previous users.

I have the same issue with chapters. Any help would be greatly greatly appreciated!! I am very new to Flask.

/r/flask
https://redd.it/13meib0
Saturday Daily Thread: Resource Request and Sharing! Daily Thread

Found a neat resource related to Python over the past week? Looking for a resource to explain a certain topic?

Use this thread to chat about and share Python resources!

/r/Python
https://redd.it/13mc34l
I want to host my django application on Ubantu. Any good blogs?

I want to host my django application on Ubantu VPS, can anyone link me to a blog that shows what configurations I have to do as well as how to actually host?

/r/djangolearning
https://redd.it/13iyhz0
PromptOptimizer -- Save Money on OpenAI (and more) LLM API costs by Minimizing the Token Complexity

LLMs work by breaking down text into tokens. Their computational complexity is usually quadratic in terms of token length.
**Why bother?**

* **Minimize Token Complexity:** Token Complexity is the amount of prompt tokens required to achieve a given task. Reducing token complexity corresponds to linearly reducing API costs and quadratically reducing computational complexity of usual transformer models.
* **Save Money:** For large businesses, saving 10% on token count can lead to saving 100k USD per 1M USD.
* **Extend Limitations:** Some models have small context lengths, prompt optimizers can help them process larger than context documents.


This project is completely written in python and is easily extendable to include more custom optimizers for experiments: [https://promptoptimizer.readthedocs.io/en/latest/extend/custom\_optims.html](https://promptoptimizer.readthedocs.io/en/latest/extend/custom_optims.html)


Open source code: [https://github.com/vaibkumr/prompt-optimizer/](https://github.com/vaibkumr/prompt-optimizer/)
Documentations: [https://promptoptimizer.readthedocs.io/en/latest/](https://promptoptimizer.readthedocs.io/en/latest/)

Please consider contributing and let me know your thoughts on this!

/r/Python
https://redd.it/13m75f9
Django agGrid

Hello r/django,

I'm new to Django and would like to get some advise on a project I'm working on.

My table returns a list of hotels with CRUD functionality via modal forms utilizing django forms. The problem is that scrolling is quite slow (overflow-auto was used to make the table scrollable). I intend to use agGrid to output the list, but it only accepts JSON response. Is it a bad idea to have a separate view for handling JSON response? Is it possible to just create an app using drf and have separate app for html views that output the forms and send the post to the view created from drf?

Here's the html table.

<tbody>
{% for hotel in hotels %}
<tr class="border-b dark:border-gray-700">
<th scope="row" class="px-4 py-2 font-medium text-gray-900 whitespace-nowrap dark:text-white">{{ hotel.name }}</th>
<td class="px-4 py-2 whitespace-nowrap">{{ hotel.rating }}</td>


/r/djangolearning
https://redd.it/13mytbu
I want to build a chatbot with Openai API

Hello guys! Does someone have a tutorial or an example?

/r/flask
https://redd.it/13n0hly
This media is not supported in your browser
VIEW IN TELEGRAM
[R] Video Demo of “Drag Your GAN: Interactive Point-based Manipulation on the Generative Image Manifold”

https://redd.it/13mpxbw
@pythondaily
Sunday Daily Thread: What's everyone working on this week?

Tell /r/python what you're working on this week! You can be bragging, grousing, sharing your passion, or explaining your pain. Talk about your current project or your pet project; whatever you want to share.

/r/Python
https://redd.it/13nd675
JIRA <3 Django ?

Is there a way to use JIRA as a bug-reporting system for the users of my Django app ? How can I do this integration ? If not - how is everyone handling bug reporting from user side for SaaS apps ?

/r/django
https://redd.it/13nk7mj
Discover Awesome Python projects

www.awesomepython.org is an app with useful, hand-picked packages and libraries

Each project links to its GitHub repo and makes it easy to discover new trending projects, quality established projects and other statistics (e.g. that auto-gpt is growing by \~13k stars per week!)

screenshot

I posted this last year and have added a lot of new functionality since then: category filtering, similar libraries, pypi & arxiv links, an "importance" score (based on the OpenSSF criticality score), and many more useful libraries

It has many recently created libraries too, for example, it's got a comprehensive list of repos in the large language model/chatgpt category: www.awesomepython.org/?c=llm

The full list, code and json data is available on GitHub: https://github.com/dylanhogg/awesome-python

Package/library suggestions welcome, I hope you find it useful

/r/Python
https://redd.it/13nrf87
Simple flask get and post messenger

Hi there am new in flask and I want to create a Flask server that handles GET and POST requests. In this case, the server will wait for a specific GET request and won't respond until it receives a corresponding POST request. Once the POST request is received, the server will use the data from the POST request to respond to the pending GET request.

Simply put, the server waits for a POST request to arrive before answering a specific GET request with the data from the POST request
Look i make the script i ask if there more professional way to do it look
''from flask import Flask, request, jsonify
import threading

app = Flask(__name__)
pending_request = None
event = threading.Event()

@app.route('/data', methods=['GET', 'POST'])
def handle_data():
global pending_request

if request.method == 'GET':
event.wait() # Wait until the event is set (POST request received)
data = pending_request
pending_request = None
event.clear() # Reset the event for the next round
return jsonify({'status': 'Data received', 'data': data})



/r/flask
https://redd.it/13nle2r
Serve static files with compression/decompression?

I have a flask app that will serve static swf and mp3 files. Some of them are ~25 each. They are served as a batch. What options do I have to speed up the transfer via compression on flask side and definition at the endpoint?

/r/flask
https://redd.it/13nzge5
Most efficient way of using cursor connections

I have a database and have multiple endpoints where each endpoint makes a specific DB query of its own. Now if we open and close connections on each endpoint, that would be too resource heavy.

Is there a way where we can open a connection for each user once and let him visit all the endpoints without re-opening/closing cursors? Like so:

conn = connection.open()

@app.route('/')
def home():
# some db execution

@app.route('/new', methods='POST')
def new():
# some other db execution

# and then close the cursor once a user is not there any longer

or we need to open and close cursors on every endpoint?

If there is a library to do so, then too I would like to know how it is handling cursors


# Edit:

I just learned about connection pooling. That answers everything

/r/flask
https://redd.it/13mnpro
How do I avoid MySQL/SQLAlchemy connection timeouts on a production server?

I have a Flask application server running on A2Hosting. An SQLAlchemy engine is created upon application launch:

engine = create_engine("mysql+pymysql://{}:{}@{}:{}/{}".format(
db_uname, db_pswd, db_host, "3306", db_name))

As a consequence, every day I'll be greeted with this error in my logs when I access the Website:

sqlalchemy.exc.OperationalError: (pymysql.err.OperationalError) (2006, "MySQL server has gone away (ConnectionResetError(104, 'Connection reset by peer'))")

I deduce that this error is probably due to a connection timeout, although I cannot confirm this.

It's only mildly annoying because when I try my backend call again, everything proceeds as normal.

Obviously, it'd be nice if this didn't happen when the app is released to the public.

What should I do instead?

/r/flask
https://redd.it/13l8fw7