Thursday 11 March 2021

Create object on startup and share across requests

I would like to use my Django application as a relay for a session-based online service and share this session among all users. For this, I've configured a python-requests Session object.

I would like to initialise this Session when Django starts up and keep it alive forever. My idea is to have all requests to my Django application share the session object by allowing the view for the particular request access the session object.

In Flask setting this up (for experimental purposes) is fairly easy:

from flask import Flask, render_template, request, session
from requests import Session
app = Flask(__name__)

session = Session()
session.post()        # Setup Session by logging in

@app.route("/")
def use_session():
    reply = session.get()   # Get resource from web service
    return jsonify(reply)

Here session would be created when starting and can be accessed by use_session().

I struggle to set up the same in Django though. Where would be the preferred place to create the session?



from Create object on startup and share across requests

No comments:

Post a Comment