Search code examples
pythonjsonrequesthttp-status-codesjson-rpc

Print status code from the post in a json-rpc call


I have a working script that does the job just fine but I can't seem to figure out how to print the status code after the script runs. Can someone please review and provide some guidance and help?

import requests
import json


url = 'http://10.3.198.100/ins'
switchuser = 'user'
switchpassword = 'password'

myheaders = {'content-type' : 'application/json-rpc'}
payload = [
  {
    "jsonrpc": "2.0",
    "method": "cli",
    "params": {
    "cmd": "vrf context management",
    "version": 1
    },
    "id": 1
  },
  {
    "jsonrpc": "2.0",
    "method": "cli",
    "params": {
    "cmd": "ip route 192.168.255.0/24 10.3.198.130",
    "version": 1
  },
    "id": 2
  },
  {
    "jsonrpc": "2.0",
    "method": "cli",
    "params": {
    "cmd": "copy run start",
    "version": 1
    },
    "id": 3
  }
 ]
 response = requests.post(url, data = json.dumps(payload), headers = myheaders, auth = (switchuser, switchpassword)).json()

Solution

  • You are immediately calling .json() after your .post() returns. This means that you are throwing away the rest of the info from the response.

    Try this instead:

    response = requests.post(
        url,data=json.dumps(payload),
        headers=myheaders,
        auth=(switchuser,switchpassword))
    json_response = response.json()
    print(response.status_code)
    

    Reference: http://docs.python-requests.org/