How can we use the MVC pattern in flask?
I am interested in improving my programming in flask and I would appreciate some advice about how to conform to a model-view-controller (MVC) pattern in flask. I am unclear about which of the MVC components map to those that we commonly see in flask (views/routes, models, templates, etc.) and could use some feedback.
I was thinking of creating:
routes.py: where the `@bp.route` decorated functions go
controllers.py: functions that get called by the decorated route functions and bring together the views.py and models.py functionality to return a view to the front-end
views.py: for returning JSON representations and rendering HTML templates ready to hand back to the front end
models.py: for managing database models.
The following is an example - it isn't from a real app and probably won't work as it is. I am just using it to illustrate my thinking:
routes.py:
@peoplebp.route('/api/people')
def getpeople():
return controllers.getpeople()
controllers.py:
def getpeople():
people = models.Person.query.all()
return views.renderpeople(people)
views.py:
def renderpeople(people):
people = p.name for p in people
/r/flask
https://redd.it/134j8qw
I am interested in improving my programming in flask and I would appreciate some advice about how to conform to a model-view-controller (MVC) pattern in flask. I am unclear about which of the MVC components map to those that we commonly see in flask (views/routes, models, templates, etc.) and could use some feedback.
I was thinking of creating:
routes.py: where the `@bp.route` decorated functions go
controllers.py: functions that get called by the decorated route functions and bring together the views.py and models.py functionality to return a view to the front-end
views.py: for returning JSON representations and rendering HTML templates ready to hand back to the front end
models.py: for managing database models.
The following is an example - it isn't from a real app and probably won't work as it is. I am just using it to illustrate my thinking:
routes.py:
@peoplebp.route('/api/people')
def getpeople():
return controllers.getpeople()
controllers.py:
def getpeople():
people = models.Person.query.all()
return views.renderpeople(people)
views.py:
def renderpeople(people):
people = p.name for p in people
/r/flask
https://redd.it/134j8qw
Reddit
r/flask on Reddit: How can we use the MVC pattern in flask?
Posted by u/Emergency-Crab-354 - 5 votes and 8 comments
I'd like to look at well written Django projects.
I'm looking for really well built Django projects so I can analyze file structure and code to derive good practices.
Post some repos please :)
/r/django
https://redd.it/134ko4x
I'm looking for really well built Django projects so I can analyze file structure and code to derive good practices.
Post some repos please :)
/r/django
https://redd.it/134ko4x
Reddit
r/django on Reddit: I'd like to look at well written Django projects.
Posted by u/tea_lion - 25 votes and 10 comments
Flask-Session not working with 2.3 removing sessioncookiename
Like the title says sessioncookiename was removed from 2.3 and Flask-Session uses that, Flask-Session hasn't seen any updates in years so I don't think their gonna fix it on their end. I've seen a fork of it called flask-session2 but don't really know if it's trustworthy. Any ideas?
/r/flask
https://redd.it/1350zrm
Like the title says sessioncookiename was removed from 2.3 and Flask-Session uses that, Flask-Session hasn't seen any updates in years so I don't think their gonna fix it on their end. I've seen a fork of it called flask-session2 but don't really know if it's trustworthy. Any ideas?
/r/flask
https://redd.it/1350zrm
Reddit
r/flask on Reddit: Flask-Session not working with 2.3 removing session_cookie_name
Posted by u/Total_Adept - No votes and 1 comment
404 Errors from simple API project
Hi All,
Currently learning the basics of flask. Have got a local server up and running, but whenever I send it a get request I get a 404 error. Any idea of where Im going wrong here?
get request: http://127.0.0.1:5000/hello
from flask import Flask
from flaskrestful import Api, Resource
app = Flask(name)
api = Api(app)
class HelloWorld(Resource):
def get(self):
data={"data":"Hello World"}
return data
api.addresource(HelloWorld,'/hello')
if name=='main':
app.run(debug=True)
​
/r/flask
https://redd.it/134wssk
Hi All,
Currently learning the basics of flask. Have got a local server up and running, but whenever I send it a get request I get a 404 error. Any idea of where Im going wrong here?
get request: http://127.0.0.1:5000/hello
from flask import Flask
from flaskrestful import Api, Resource
app = Flask(name)
api = Api(app)
class HelloWorld(Resource):
def get(self):
data={"data":"Hello World"}
return data
api.addresource(HelloWorld,'/hello')
if name=='main':
app.run(debug=True)
​
/r/flask
https://redd.it/134wssk
Reddit
r/flask on Reddit: 404 Errors from simple API project
Posted by u/yewstreet - 1 vote and 12 comments
Use AWS Elasticache Redis as Celery Broker?
So we're using AWS to deploy our project, and using Celery for Event Driven Architecture, so celery workers are always up and running.
We wanted to use Redis as a broker, since SQS has no monitoring support from either Celery or Celery Flower. We tried using AWS MemoryDB Redis as broker, but were unsuccessful as Celery at the moment does not support clustered Redis architecture. So now we're using Elasticache Redis as the broker, but the AWS docs says that Elasticache is not persistent, and data loss might occur if the primary node fails, which means that some messages might be lost which would be really hard to recover.
So my question is that is Elasticache is a wise choice for using Redis as a broker, or we should look at something else?
Also, if someone here has used Elasticache Redis as their celery broker, please let me know your experience and if you would recommend it.
/r/django
https://redd.it/134z8ly
So we're using AWS to deploy our project, and using Celery for Event Driven Architecture, so celery workers are always up and running.
We wanted to use Redis as a broker, since SQS has no monitoring support from either Celery or Celery Flower. We tried using AWS MemoryDB Redis as broker, but were unsuccessful as Celery at the moment does not support clustered Redis architecture. So now we're using Elasticache Redis as the broker, but the AWS docs says that Elasticache is not persistent, and data loss might occur if the primary node fails, which means that some messages might be lost which would be really hard to recover.
So my question is that is Elasticache is a wise choice for using Redis as a broker, or we should look at something else?
Also, if someone here has used Elasticache Redis as their celery broker, please let me know your experience and if you would recommend it.
/r/django
https://redd.it/134z8ly
Reddit
r/django on Reddit: Use AWS Elasticache Redis as Celery Broker?
Posted by u/Deadpool5551 - 3 votes and 3 comments
Rendering child templates with context
I am using class based views and my problem is that I have a base template for cards, which provides the styling and functionality for them. I also have multiple card view classes (Card1, Card2, etc) which each have context, and set the template_name to the base template for the cards. I want to be able to call each card class inside my home template, instead of using {% include BaseCardTemplate with..... %} because there is a lot of context. Is there a standard Django way to do this?
​
And if there is a standard way to do this in Django is it also applicable including templates that rely on models? For example if I have a button that when clicked, I want to display a window that gets its information from the app's model using the button's data attribute as the primary key, how is this done?
/r/django
https://redd.it/1352tte
I am using class based views and my problem is that I have a base template for cards, which provides the styling and functionality for them. I also have multiple card view classes (Card1, Card2, etc) which each have context, and set the template_name to the base template for the cards. I want to be able to call each card class inside my home template, instead of using {% include BaseCardTemplate with..... %} because there is a lot of context. Is there a standard Django way to do this?
​
And if there is a standard way to do this in Django is it also applicable including templates that rely on models? For example if I have a button that when clicked, I want to display a window that gets its information from the app's model using the button's data attribute as the primary key, how is this done?
/r/django
https://redd.it/1352tte
Reddit
r/django on Reddit: Rendering child templates with context
Posted by u/JayaRobus - 1 vote and 3 comments
GeoDjango resources/ materials
May I please ask if you have any materials or resources on geoDjango that you would be willing to share? I am looking to expand my knowledge on this topic and any help would be greatly appreciated. Thank you!
/r/django
https://redd.it/134qcy5
May I please ask if you have any materials or resources on geoDjango that you would be willing to share? I am looking to expand my knowledge on this topic and any help would be greatly appreciated. Thank you!
/r/django
https://redd.it/134qcy5
Reddit
r/django on Reddit: GeoDjango resources/ materials
Posted by u/NoHistorian4672 - 3 votes and 1 comment
Tuesday Daily Thread: Advanced questions
Have some burning questions on advanced Python topics? Use this thread to ask more advanced questions related to Python.
If your question is a beginner question we hold a beginner Daily Thread tomorrow (Wednesday) where you can ask any question! We may remove questions here and ask you to resubmit tomorrow.
This thread may be fairly low volume in replies, if you don't receive a response we recommend looking at r/LearnPython or joining the Python Discord server at https://discord.gg/python where you stand a better chance of receiving a response.
/r/Python
https://redd.it/1355kwt
Have some burning questions on advanced Python topics? Use this thread to ask more advanced questions related to Python.
If your question is a beginner question we hold a beginner Daily Thread tomorrow (Wednesday) where you can ask any question! We may remove questions here and ask you to resubmit tomorrow.
This thread may be fairly low volume in replies, if you don't receive a response we recommend looking at r/LearnPython or joining the Python Discord server at https://discord.gg/python where you stand a better chance of receiving a response.
/r/Python
https://redd.it/1355kwt
Discord
Join the Python Discord Server!
We're a large community focused around the Python programming language. We believe that anyone can learn to code. | 412982 members
Load template tags inside model
I have html inside a body = model.TextField and with {{ body | safe }} i get the html code rendern but i would like to load Django template tags inside for images.
Any tips? I have not found a built-in template tag that support this.
/r/django
https://redd.it/134zin1
I have html inside a body = model.TextField and with {{ body | safe }} i get the html code rendern but i would like to load Django template tags inside for images.
Any tips? I have not found a built-in template tag that support this.
/r/django
https://redd.it/134zin1
Reddit
r/django on Reddit: Load template tags inside model
Posted by u/to_sta - 2 votes and 1 comment
Goodbye to Flake8 and PyLint: faster linting with Ruff
https://pythonspeed.com/articles/pylint-flake8-ruff/
/r/Python
https://redd.it/134zkvd
https://pythonspeed.com/articles/pylint-flake8-ruff/
/r/Python
https://redd.it/134zkvd
Python⇒Speed
Goodbye to Flake8 and PyLint: faster linting with Ruff
Ruff is a new linter that is vastly faster than PyLint and flake8—with many of the same checks.
Is there a way to integrate djdt results with tests?
The problem is djdt is not suitable to be active during tests because it significantly slows down the tests and is unnecessary. But this means that before committing, manual work has to be done to check for query efficiency which is a waste of time and is the whole purpose of tests. I'm thinking it would be nice if there's a way to set a maximum number of duplicate queries/any other metrics, for each view and have it checked by a test. It still would be inconvenient to enable djdt over the entire suite just to enable running just a few tests. How do you usually approach this? I'm using
/r/django
https://redd.it/135eqku
The problem is djdt is not suitable to be active during tests because it significantly slows down the tests and is unnecessary. But this means that before committing, manual work has to be done to check for query efficiency which is a waste of time and is the whole purpose of tests. I'm thinking it would be nice if there's a way to set a maximum number of duplicate queries/any other metrics, for each view and have it checked by a test. It still would be inconvenient to enable djdt over the entire suite just to enable running just a few tests. How do you usually approach this? I'm using
pytest + django test client + selenium fyi./r/django
https://redd.it/135eqku
Reddit
r/django on Reddit: Is there a way to integrate djdt results with tests?
Posted by u/shindigin - 3 votes and 2 comments
Introducing Grasshopper - An Open Source Python Library for Load Testing
https://innovation.alteryx.com/introducing-grasshopper-an-open-source-python-library-for-load-testing/
/r/Python
https://redd.it/135dcvs
https://innovation.alteryx.com/introducing-grasshopper-an-open-source-python-library-for-load-testing/
/r/Python
https://redd.it/135dcvs
Learning more about forward and reverse relationships.
Hello there, I am relatively new to django and came to know about forward and reverse relationships and wanted to craft a real world problem. Let's say I have the following classes
class User(AbstractBaseUser):
phone_number=models.CharField()
class ClientPackage(models.Model):
user = models.OnetoOneField(User,,related_name='user_client_package')
package = models.ForeignKey(Package,null=True, blank=True)
expiry_date = models.DateField()
class NotificationSettings(models.Model):
user = models.OneToOneField(User, related_name="user_notification_settings")
master = models.BooleanField(default=True, help_text='set false turn off notifications.')
Now to get all the user\_id and phone\_number of currently active users who have set the master control for notifications to be true I can do it in three ways
1. User.objects.filter(
user_client_package__pacakge__isnull=False,
user_client_package__expiry_date=date.today(),
user_notification_settings__master=True
).values_list('id', 'phone_number')
2. ClientPackage.objects.filter(
/r/django
https://redd.it/135k9s2
Hello there, I am relatively new to django and came to know about forward and reverse relationships and wanted to craft a real world problem. Let's say I have the following classes
class User(AbstractBaseUser):
phone_number=models.CharField()
class ClientPackage(models.Model):
user = models.OnetoOneField(User,,related_name='user_client_package')
package = models.ForeignKey(Package,null=True, blank=True)
expiry_date = models.DateField()
class NotificationSettings(models.Model):
user = models.OneToOneField(User, related_name="user_notification_settings")
master = models.BooleanField(default=True, help_text='set false turn off notifications.')
Now to get all the user\_id and phone\_number of currently active users who have set the master control for notifications to be true I can do it in three ways
1. User.objects.filter(
user_client_package__pacakge__isnull=False,
user_client_package__expiry_date=date.today(),
user_notification_settings__master=True
).values_list('id', 'phone_number')
2. ClientPackage.objects.filter(
/r/django
https://redd.it/135k9s2
Reddit
r/django on Reddit: Learning more about forward and reverse relationships.
Posted by u/RS2-CN3 - 4 votes and 1 comment
HTMX and Wagtail
Hi, has anyone used HTMX with wagtail, I’m very new to using both but I’ve dabbled with HTMX and would love to use it in a wagtail project.
How do HTMX requests work with wagtail page models? As the views are all handled for you.
How does the wagtail admin deal with editing the partial temples?
/r/djangolearning
https://redd.it/135o2m6
Hi, has anyone used HTMX with wagtail, I’m very new to using both but I’ve dabbled with HTMX and would love to use it in a wagtail project.
How do HTMX requests work with wagtail page models? As the views are all handled for you.
How does the wagtail admin deal with editing the partial temples?
/r/djangolearning
https://redd.it/135o2m6
Reddit
r/djangolearning on Reddit: HTMX and Wagtail
Posted by u/rob8624 - No votes and 1 comment
Streamsync: UI editor + Python
Hello everyone, I've just released Streamsync, an open-source, pip-installable data apps framework.
You build the UI using a visual editor, you write the backend code in Python. No HTML, JS or CSS required. It's an alternative to Streamlit and Dash.
https://i.redd.it/u4nazv8ohexa1.gif
https://github.com/ramedina86/streamsync
I'd really appreciate your feedback, thanks.
/r/Python
https://redd.it/135i584
Hello everyone, I've just released Streamsync, an open-source, pip-installable data apps framework.
You build the UI using a visual editor, you write the backend code in Python. No HTML, JS or CSS required. It's an alternative to Streamlit and Dash.
https://i.redd.it/u4nazv8ohexa1.gif
https://github.com/ramedina86/streamsync
I'd really appreciate your feedback, thanks.
/r/Python
https://redd.it/135i584
Convolutional Neural Network for Reverse Engineering
Hey everyone,
I created a project that uses machine learning for reverse engineering compiled binaries and identifing function boundaries: https://github.com/alonstern/function-identification.
The GitHub repo also includes a link to a TDS article with an explanation about the model.
Let me know what you think. Thanks!
/r/Python
https://redd.it/135jrz1
Hey everyone,
I created a project that uses machine learning for reverse engineering compiled binaries and identifing function boundaries: https://github.com/alonstern/function-identification.
The GitHub repo also includes a link to a TDS article with an explanation about the model.
Let me know what you think. Thanks!
/r/Python
https://redd.it/135jrz1
GitHub
GitHub - alonstern/function-identification: This project demonstrates how a convolutional neural network can be used to detect…
This project demonstrates how a convolutional neural network can be used to detect the boundaries of a function in compiled code - alonstern/function-identification
Automating the creation of Forms, Views, and Templates
I'm trying to use a couple loops to automatically build from the models each form, view, and url, and have a single template file render each list. I'm newer to python but I do know generating classes and functions like this is not best practice to say the least, however its something I wanted to try for my own project. What I'm interested in is playing with on the front end with my primary fact table and not the two dozen or so dimension tables, which may require frequent field additions or abstractions.
base/app/models.py
from django.db import models
from django.contrib.auth.models import User
#Create your models here.
class UserTypeModel(models.Model):
code = models.CharField(maxlength = 10, primarykey = True)
name = models.CharField(maxlength = 100, blank = False, unique = True)
def str(self):
return self.name
/r/djangolearning
https://redd.it/135v43t
I'm trying to use a couple loops to automatically build from the models each form, view, and url, and have a single template file render each list. I'm newer to python but I do know generating classes and functions like this is not best practice to say the least, however its something I wanted to try for my own project. What I'm interested in is playing with on the front end with my primary fact table and not the two dozen or so dimension tables, which may require frequent field additions or abstractions.
base/app/models.py
from django.db import models
from django.contrib.auth.models import User
#Create your models here.
class UserTypeModel(models.Model):
code = models.CharField(maxlength = 10, primarykey = True)
name = models.CharField(maxlength = 100, blank = False, unique = True)
def str(self):
return self.name
/r/djangolearning
https://redd.it/135v43t
Reddit
r/djangolearning on Reddit: Automating the creation of Forms, Views, and Templates
Posted by u/burmeisterN - 1 vote and 1 comment
Review My Python Chat Room Project with Flask and SocketIO
Hey everyone, I just completed a Python chat room project using the Flask web framework and SocketIO library for real-time communication. The front-end was implemented with JavaScript. I would love to get some feedback on my code and project, so I'm sharing it here!
Project Overview: The goal of this project is to create a chat room web application where users can chat with each other in real-time. Users can join different chat rooms and send messages to other users in the same room. The chat room interface is implemented with HTML, CSS, and JavaScript using the SocketIO library for real-time communication with the server.
https://github.com/Hajiub/flask\_chat\_room.git
/r/flask
https://redd.it/1365afd
Hey everyone, I just completed a Python chat room project using the Flask web framework and SocketIO library for real-time communication. The front-end was implemented with JavaScript. I would love to get some feedback on my code and project, so I'm sharing it here!
Project Overview: The goal of this project is to create a chat room web application where users can chat with each other in real-time. Users can join different chat rooms and send messages to other users in the same room. The chat room interface is implemented with HTML, CSS, and JavaScript using the SocketIO library for real-time communication with the server.
https://github.com/Hajiub/flask\_chat\_room.git
/r/flask
https://redd.it/1365afd
GitHub
GitHub - Hajiub/flask_chat_room: Welcome to our virtual hangout where code and conversation merge seamlessly. Explore our GitHub…
Welcome to our virtual hangout where code and conversation merge seamlessly. Explore our GitHub repo to join the fun and contribute to the community - GitHub - Hajiub/flask_chat_room: Welcome to ou...
Wednesday Daily Thread: Beginner questions
New to Python and have questions? Use this thread to ask anything about Python, there are no bad questions!
This thread may be fairly low volume in replies, if you don't receive a response we recommend looking at r/LearnPython or joining the Python Discord server at https://discord.gg/python where you stand a better chance of receiving a response.
/r/Python
https://redd.it/1364mx7
New to Python and have questions? Use this thread to ask anything about Python, there are no bad questions!
This thread may be fairly low volume in replies, if you don't receive a response we recommend looking at r/LearnPython or joining the Python Discord server at https://discord.gg/python where you stand a better chance of receiving a response.
/r/Python
https://redd.it/1364mx7
Discord
Join the Python Discord Server!
We're a large community focused around the Python programming language. We believe that anyone can learn to code. | 412982 members