Codebeispiele für Python-basierte Request-Anwendungen

Die folgenden Beispiele haben keinen Anspruch auf Korrektheit bzw. Lauffähigkeit und dienen nur der Veranschaulichung.

ND: DIQ

POST-Request

  • mehrere ND-DIQ-Datensätze eintragen
  • jedes Device muß bereits in NetDB vorhanden sein (da nur FQDN mitgegeben wird)
  • es wird nur der Arbeitsschritt “Konfigurationslader” ausgeführt, wobei dieselbe Datei auf mehrere Devices hochgeladen wird
  • Python-Codevorlage:
#!/usr/bin/python

import requests
import json

certfilename = '/home/username/.ssl/mycert.pem'
root_url = 'https://www-net.scc.kit.edu/api'
major_version = 1
minor_version = 0
system_name = 'nd'
objtype_name = 'diq'
function_name = 'create'

url = '{ru}/{mav}.{miv}/{sys}/{ot}/{func}'.format(
  ru   = root_url,
  mav  = major_version,
  miv  = minor_version,
  sys  = system_name,
  ot   = objtype_name,
  func = function_name
)

device_fqdn_list = [
  'se-test-1.tmn.scc.kit.edu.',
  'se-test-2.tmn.scc.kit.edu.'
]
upload_cfg_filename = '/tmp/se-test-x.tmn.scc.kit.edu.upload'

data_keyval_dict = { "--mode_flags": "", "--upload_cfg_filename": upload_cfg_filename }
json_list = list()
for dev in device_fqdn_list:
  data_param_list = [ { "name": "dev_fqdn", "new_value": dev } ]
  json_list.append( { "param_list": data_param_list, "keyval_dict": data_keyval_dict } )

json_string = json.dumps(json_list, ensure_ascii = False)
headers_dict = { "Content-Type": "application/json" }

response = requests.post(url = url, data = json_string, headers = headers_dict, cert = certfilename)
if response.ok:
  # continue with normal request (process result)
  result = response.json()
else:
  # errormessage for further processing
  # get as dict-type:
  err_dict = response.json()
  # get as string-type:
  err_text = response.text
  # only simple print out
  print(err_text)
  # recommended: raise exception
  raise requests.exceptions.RequestException(response.status_code, response.text)

GET-Request

  • ND-DIQ auslesen
  • Python-Codevorlage:
#!/usr/bin/python

import requests
import json

certfilename = '/home/username/.ssl/mycert.pem'
root_url = 'https://www-net.scc.kit.edu/api'
major_version = 1
minor_version = 0
system_name = 'nd'
objtype_name = 'diq'
function_name = 'list'

url = '{ru}/{mav}.{miv}/{sys}/{ot}/{func}'.format(
  ru   = root_url,
  mav  = major_version,
  miv  = minor_version,
  sys  = system_name,
  ot   = objtype_name,
  func = function_name
)

response = requests.get(url = url, cert = certfilename)
if response.ok:
  # continue with normal request (process result)
  result = response.json()
else:
  # errormessage for further processing
  # get as dict-type:
  err_dict = response.json()
  # get as string-type:
  err_text = response.text
  # only simple print out
  print(err_text)
  # recommended: raise exception
  raise requests.exceptions.RequestException(response.status_code, response.text)