Search code examples
pythondjangodjango-urlspath-parameter

Retrieving URL parameters in the order they are passed - django


I am trying to retrieve the URL parameters that are passed into the function, in the order they are acutally passed. The reason this matters, is its a payment provider integration, which calculates a hash from concatenating the values that are passed (in the order they are passed). So based on this, i need to access the parameters in the order they are passed in the actual URL, concatenate them and then add a MD5 key that is secret to my account to verify the request.

For example: http://example.com/order/callback?date=20200101&currency=USD&txnid=1234567&hash=thegeneratedhas

If i access the request through request.GET I get ordered dict.

pseudo-code

def callback(request):
  keys_concatenated = ""
  for value in request.GET:
    if value == "hash":
      pass
    else:
      keys_concatenated = keys_concatenated + request.GET[value]

This generates a string like: USD202001011234567 The hash generated from the provider that the order is kept, and thus is expecting the value 20200101USD1234567

Defining the parameters within urls.py is not really something I want as the payment provider is openly saying that they might change parameters passed, and thus it would break the implementation. I also dont know the actual order they are passing it in from time to time.


Solution

  • You can use python's built-in urllib.parse and parse the URL params while also maintaining their order.

    A brief example:

    >>> from urllib.parse import parse_qsl
    >>> parse_qsl('date=20200101&currency=USD&txnid=1234567&hash=thegeneratedhas')
    [('date', '20200101'), ('currency', 'USD'), ('txnid', '1234567'), ('hash', 'thegeneratedhas')]
    >>>