pythonhttpjythonmaximooslc

How to make a hard-coded HTTP processing script dynamic?


I have a Jython 2.7 script that receives a URL and uses the parameters/values in the URL to create or update records.


Details:

  1. Receive the URL and put the parameters/values in variables:
from psdi.server import MXServer
from psdi.mbo import MboSet

resp = {}
wonum =             request.getQueryParam("wonum")
description =       request.getQueryParam("description")
classstructureid =  request.getQueryParam("classstructureid")
wopriority =        request.getQueryParam("wopriority")
worktype =          request.getQueryParam("worktype")
  1. Some lines that aren't relevant to the question:
woset = MXServer.getMXServer().getMboSet("workorder",request.getUserInfo())
whereClause = "wonum= '" + wonum + "'"

woset.setWhere(whereClause)
woset.reset()
woMbo = woset.moveFirst()
  1. Then use the values to either create a new record or update an existing record:
#If workorder already exists, update it:
if woMbo is not None:
  woMbo.setValue("description", description)
  woMbo.setValue("classstructureid", classstructureid)
  woMbo.setValue("wopriority", wopriority)
  woMbo.setValue("worktype", worktype)
  woset.save()
  woset.clear()
  woset.close()
  resp[0]='Updated workorder ' + wonum
#Else, create a new workorder
else:
  woMbo=woset.add()
  woMbo.setValue("wonum",wonum)
  woMbo.setValue("description", description)
  woMbo.setValue("classstructureid", classstructureid)
  woMbo.setValue("wopriority", wopriority)
  woMbo.setValue("worktype", worktype)
  woset.save()
  woset.clear()
  woset.close()
  resp[0]='Created workorder ' + wonum
responseBody =resp[0]

Question:

Unfortunately, the field names/values are hardcoded in 3 different places in the script.

I would like to enhance the script so that it is dynamic -- not hardcoded.

Is it possible to do this?


Solution

  • Assuming you are working always with the same query parameters, rather than define variables, loop through a list of strings and put them as key-value pairs

    To populate

    items = ["wonum", "description"]
    resp = {k: request.getQueryParam(k) for k in items}
    

    Then to set

    for i in items:
        woMbo.setValue(i, resp[i])
    

    Otherwise, you are looking for URL parsing and the getQuery method, followed by a split("="), giving you ["wonum", "WO0001", "description", "Legacy"], for example, and you can loop over every other element to get you dynamic entries

    l = ["wonum", "WO0001", "description", "Legacy"]
    for i in range(0, len(l)-1, 2):
        print(f'key:{l[i]}\tvalue:{l[i+1]}')
    

    key:wonum   value:WO0001
    key:description value:Legacy
    

    Note: This is subject to SQL injection attacks, and should be fixed

    whereClause = "wonum= '" + wonum + "'"