Skip to content

Instantly share code, notes, and snippets.

@seanbehan
Last active March 13, 2023 04:55
Show Gist options
  • Star 59 You must be signed in to star a gist
  • Fork 12 You must be signed in to fork a gist
  • Save seanbehan/168a277a5a23086e76000a59e54fb3d5 to your computer and use it in GitHub Desktop.
Save seanbehan/168a277a5a23086e76000a59e54fb3d5 to your computer and use it in GitHub Desktop.
Flask with Django ORM
'''
Run the following commands (bc. gists don't allow directories)
pip install flask django dj-database-url psycopg2
mkdir -p app/migrations
touch app/__init__.py app/migrations/__init__.py
mv models.py app/
python manage.py makemigrations
python manage.py migrate
DJANGO_SETTINGS_MODULE=settings python app.py
visit http://localhost:5000
See https://docs.djangoproject.com/en/1.11/topics/settings/#either-configure-or-django-settings-module-is-required for documentation
'''
from flask import Flask
from django.apps import apps
from django.conf import settings
apps.populate(settings.INSTALLED_APPS)
from app.models import Hit
app = Flask(__name__)
@app.route("/")
def index():
return str(Hit.objects.count())
if __name__=='__main__':
app.run(debug=True)
#!/usr/bin/env python
import os, sys
if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "settings")
from django.core.management import execute_from_command_line
execute_from_command_line(sys.argv)
from django.db import models
from django.contrib.postgres.fields import JSONField
class BaseModel(models.Model):
created_at = models.DateTimeField(auto_now_add=True, null=True)
updated_at = models.DateTimeField(auto_now=True, null=True)
def attributes(self):
return self.__dict__
class Meta:
abstract = True
class Hit(BaseModel):
data = JSONField(null=True)
import dj_database_url
DATABASES = { 'default': dj_database_url.config(default='postgres://localhost/py_example_app') }
INSTALLED_APPS = ( 'app', )
SECRET_KEY = 'REPLACE_ME'
@Ehco1996
Copy link

smart guys

@ashishk1996
Copy link

I have done something similar, now facing issues in threads(each flask thread spawning one DB connection, then not closing it after transaction).Running out of Postgres threads.
Flask
Django ORM
Waitress

@ChaosJohn
Copy link

ChaosJohn commented Jul 24, 2020

I have made some modification for the project structure.
See from my fork

@vulcan25
Copy link

vulcan25 commented Nov 7, 2021

@ashishk1996

I also noticed the same behaviour in a slight variation of this. I solved by adding an after_request decorator to the Flask app:

from django.db import close_old_connections

@app.after_request
def after_request_func(response):
    close_old_connections()
    return response

As a sidenote, you can check the current number of DB connections (postgres) with:

SELECT count(*) FROM pg_stat_activity;

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment