Python Middleware Create Session Key

Hi All,

Just a quick question, I want to be able to create a key from Python just like we’re able to do with a JS middleware using the following syntax:

TykSetKeyData(key keyDetails, 1)

I want to be able to create it from a Pythong middleware, and I dont seem to find the similar function in the Python API, only raw functions to interact with Redis.


I don’t think that API call exists at the moment, there are hooks for setting and getting data from Redis, but that’s probably not what you need.

However, if you are creating a token in Python using middleware, why not just generate a custom authentication middleware in python and then you can provide a session object back without having to generate a token at all? (see the authenticatino section here: tyk/ at master · TykTechnologies/tyk · GitHub)

Hi Martin, thanks for your reply. I checked what you suggested, and it makes sense. I’m assuming you meant, that I dont need to store the key in Redis at all, that it’d be enough to just modify the session object straight from the middleware.
The thing is, it’s not working, this is an snippet…

def MyPreMiddleware(request, session, spec):

    ip = request.get_header('X-Real-Ip') #Obtain IP
    request.add_header('x-limit-authorization', ip) # Save IP to request

    #Specify what will happen with this session... WRONG?
    session.apply_policy_id = "58cae541d81dd609b3d249d5"
    session.org_id = "58cad6dfd81dd609b3d249cc"

    return request, session

The idea is to have the Pre Middleware apply a policy at this level, and limit requests per IP.


How are you initialising this? You will actually need to set this middleware up as auth middleware, not pre/post, this would replace the token check altogether, this bit of the docs is the code and initialisation you should be using:

Hi Martin, this link is working and I used it. Thanks for sharing new concept.