[Answered ]-Using Django inside Tornado App – Can't Access MySQL Records Created After The Tornado App Starts

0👍

Using the django orm from a tornado handler can be tricky; you need some hooks with the request starts and stops since django’s middleware isn’t running. Here’s something I wrote years ago to do this; I have no idea if it still works: https://gist.github.com/bdarnell/654157. Looking back at it now, I’m not sure if it’s correct for asynchronous requests; I think you’d want to do what’s in prepare/finish in this gist before and after segment that includes a database call.

1👍

Based on Ben Darnell’s code, all it took was the following:

from django.db import connection

if user_id is None:
    return None

try:
    connection.queries = []
    user = user_model.objects.get(pk=user_id)
    connection.close()
    return user
except user_model.DoesNotExist:
    return None
👤Corky

1👍

Actually, after playing around a bit, all that was needed was to add the single line:

django.db.connection.close()

To the WebSocketHandler’s open method. This forces Django to reestablish the connection on the first db call…

👤Corky

Leave a comment