user1843591
user1843591

Reputation: 1146

Python requests module - POST failing - invalid character 'o'

I am trying to convert a raw curl command to use Python Request Module with no luck. This is a simple request to query JBoss Mgmt interface but it does not parse my JSON correctly.

16:34:26,868 DEBUG [org.jboss.as.domain.http.api] (HttpManagementService-threads - 15) Unable to construct ModelNode 'Invalid character: o'

Python version

Python 2.7.6

Working raw cURL command:

/usr/bin/curl --digest -v -L -D - 'http://brenn:!12rori@localhost:9990/management' --header Content-Type:application/json '-d {"operation":"read-attribute","name":"server-state","json.pretty":1}'

In python code i read in my REST/cURL payload like so

import requests
----
def readconfigfile():
    with open('jboss_modification.cfg') as f:
        lines = f.readlines()
    return lines

The config file looks like so

{"operation":"read-attribute","name":"server-state","json.pretty":1}

I convert the str format from readconfigfile() to a dictionary as follows

def converttodictionary(incominglines):
commands = []
for lin in incominglines:
    #dumps = json.dumps(lin)
    obj = json.loads(lin)
    commands.append(obj)
return commands

The python code to execute this request is as follows

def applyconfig(lines):
    url="http://localhost:9990/management"
    auth=HTTPBasicAuth('brenn', '!12rori')
    s = requests.Session()
    re=s.get(url,  auth=HTTPDigestAuth('brenn', '!12rori')) ##200 RESP
    s.headers.update({'Content-Type': 'application/json'})
    for line in lines:
        payload=line
        r=s.post(url,payload)
        print(r.text)

Any help much appreciated?

Note: This question has been updated a few times as I resolved other issues....

Upvotes: 3

Views: 1946

Answers (1)

user1843591
user1843591

Reputation: 1146

The issues was...

Initial JSON requestfailed because when i read it from file python interpreted as a str.

Converted to dictionary using json.loads and server accepted request but could not parse the JSON with illegal character error

Converted this json back to a str using json.dumps -- which to my mind looks like what i was trying to do in the first place -- and this now works

  1. read JSON file as per def readconfigfile(): above
  2. convert to json/dictionary as per def converttodictionary above: json.loads(lin)
  3. Convert this json "back" to a string using json.dumps and POST as follows

    payload = json.dumps(command)
    
    r = session.post(url, payload,auth=HTTPDigestAuth('brenn', '!12rori')
    

)

Upvotes: 2

Related Questions