psycopg2 with flask, when to close connection - flask

I'm trying to build a simple web application that will be querying a postgres db and inserting/deleting data. Since it is a very simple application, I'm not using an ORM layer like sqlalchemy. Instead I'd like to use psycopg directly. Now, I'm wondering, when would be the best time to close cursors and connections? I'm having trouble getting the bigger picture of when the connection is idling with respect to access to the web app.
Thanks!

maybe the official documentation can be useful
#app.before_request
def before_request():
g.db = connect_db()
#app.teardown_request
def teardown_request(exception):
g.db.close()

Related

Integrating django-import-export with react

I have a postgresql database and I want to add data to it.
I want to upload an excel file containing the data and save it to database.
I have a backend server of django and a frontend server of React.
I am easily able to import the data from the excel sheet to database using django_import_export but from the django admin.
What I want is, to do this using React and for normal users(non superusers) also. Is there a way to integrate django_import_export with react? Any other way to implement this functionality is also apreciated.
Presumably your backend uses a REST API to handle requests from the frontend. So, you can write an API handler which receives the Excel data posted to it.
The Django API handler can create an import process to handle upload. Check the documentation for more information.
Note that if you are loading large files, then you might want to handle the upload asychronously. This is little more tricky, but you could look at Celery to help with this.

Persistent MongoDB Connection With Django

I am currently using (or hoping to use) both PostgreSQL and MongoDB for my Django project. When it comes to MongoDB I've been looking at PyMongo to make the connection, and add/edit info using Python. Most likely I will be calling PyMongo in my views.py to read/insert/edit data from MongoDB.
For the sake of this question, let's say I have a view called worksheet, which querys some data from MongoDB relevant to the current user. However I would like to maintain a persistent connection to the database so that I do not have to make a new connection every time a user visits the worksheet view.
Is there any way I could make a persistent connection so I am not wasting time/resources making new connections to MongoDB every time? Thanks.
I wanted the exact same thing and this is how I did it.
from pymongo import MongoClient
from threading import local
from django.conf import settings
_mongo_client = local()
def mongo_client():
client = getattr(_mongo_client, 'client', None)
if client is None:
client = MongoClient(settings.MONGODB_URI)
_mongo_client.client = client
return client
And then in your views you use it the client like this.
mongo_client().db.orders.find(...)
This is what I have been doing and it works, my only concern would be if the mongodb client correctly reestablishes lost connections... But I think it does because I have not been having any issues.

How to use Records with Flask?

My Flask app should execute some rather complicated sql queries, parse them and display results. Now I'm using SQLAlchemy (as described here), but I want to switch to Records, simple wrapper over SQLAlchemy (it has all I need out of the box). I haven't found any examples of integration Records into Flask.
Can you provide an example of simple Flask app with vanilla Records integration?
Records handle the SQLAlchemy connection lifecycle, I don't think it is a good idea to really integrate them. You can share the config, passing the database URL to records.Database.
app = Flask(__name__)
app.config['DATABASE_URL'] = 'postgres://...'
records_db = records.Database(app.config['DATABASE_URL'])
If you use Flask-SQLAlchemy, the config key is SQLALCHEMY_DATABASE_URI.
Add the records_db to Flask context g to access it from any file with a Flask context, without messing with circular imports.
from flask import g
g.records = records_db

How to use a mysql table of a particular django app in another django app if the is same?

I am trying my hand at Python. I have a created a simple app with MySQL as a back end and I want to use the application's table in another app.
Both of the applications are for the same project. Please help
Make sure all your app in registered in settings.py.Then import the model to other by appname.models.Modelname.
Execute Query:
ModelName.objects.all()

Django - Runtime database switching

In my work we want to run a server with multiple databases. The databases switching should occur when you acces a url like http://myapp.webpage.com or http://other.webpage.com. We want to run only one server instance and at the moment of the HTTP request switch the database and return the corresponding response.
We've been looking for a mantainable and 'Django-friendly' solution. In our investigation we have found possible ways to do this, but we have not enough information about.
Option 1: Django middleware
The django middleware runs each time the server receive a HTTP request.
Making a database switch here could be the best option but using django database routers as far as I know only allow to change the database for a model or group or models.
Another option is to set a django model manager instance in the middleware and force all models to re-assign the objects attribute from an added attribute in the custom middleware.
My last option is to create a new attribute in the request object received by the middleware that return the database alias from settings.py and in each model query use the using method.
Option 2: Class-based View Mixin
Create a mixin that use the past three options, but I the mixin must be set in ALL the Class-based views. If a programmer forget to set the mixin and it comes to a production server, the data could be (or stop being) in the right database, and I don't wanna take the risk.
Option 3: Changing the database settings in runtime
This option works but Is not recommended and is too risky.
UPDATE:
How this works?
middlewares.py
import django.conf as conf
import os.path
class SelectDB(object):
def process_request(self, request):
print request.META['HTTP_REFERER']
file_database = open("booklog/database.txt", "r")
database = file_database.read(10)
file_database.close()
if database != 'default':
conf.settings.DATABASES['default']['NAME'] = database
Any information that help us to solve will be greatly appreciated.
Answer (it worked for me)
The question was already answered here, in stackoverflow. I'd love this functionality were in django. It was a bit hard to find the way to make this possible.
I think that is important to comment the great work that Wilduck made with the django plugin django-dynamic-db-router, it's a great plugin that makes possible this operation in (a bit) different way.
Thanks a lot to #JL Peyret and #ire_and_curses.
And as an answer to #ire_and_curses. At least in this moment, in the project I'm working it's what we need. In previous projects we needed a similar behavior and made one server per instance was terrible to mantain and update each server, even automating the process.