Search code examples
web2py

Extracting and storing a query parameter from any page in a web2py app


I want the user to be able to append an affiliate ID key and value as the query string on any URL in my web2py app. Which I then register in the session. At any point should they click a link to register:

  1. I use the affiliate ID that is in the query string (if there is one)
  2. I use the affiliate ID in the session object (if one is there)
  3. I randomly choose a user from the database as the affiliate otherwise

My question is: how can I "decorate" each function in the web2py app such that it extracts and assigns the query variable affiliate to the session variable affiliate without manually writing such code in each and every function in every controller?


Solution

  • By default, model files in the top level of the /models folder are executed on every request, so just put the code in a model file:

    if request.get_vars.affiliate:
        session.affiliate = request.get_vars.affiliate
    

    Also, using the above, there would be no need for your step #1 above (i.e., pulling the affiliate ID from the query string) -- if "affiliate" is in the query string, it will also be copied to the session within the same request. So, just read the ID from the session.