How to remove quotes in suds-py3 requests - python-3.x

I´m using suds-py3 to make requests to a service with complex arguments that requires numbers and texts. This is the code i´m trying:
from suds.client import Client
url = <service_url>
parameter = <service_method_parameter>
method = <service_method>
client = Client(url)
parameter_object = client.factory.create(str(parameter))
Until here, i´ve created a dictionary of the values that the service asks that looks like this:
parameter_object = {
'codigoAmbiente': '',
'codigoModalidad': '',
'codigoPuntoVenta': '',
'codigoSistema': '',
'codigoSucursal': '',
'cuis': '',
'nit': ''
}
So to make the request, i create another dictionary with the required values:
request_dictionary = {
'codigoAmbiente': 2,
'codigoModalidad': 2,
'codigoPuntoVenta': 0,
'codigoSistema': 'AA5BB4CC3',
'codigoSucursal': 0,
'cuis': 'A1B2C3',
'nit': 12343456
}
Then i send the values to the service with the following code.
for var, value in request_dictionary.items():
parameter_object[str(var)] = value
request_response = getattr(client.service, method)()
print(request_response)
The problem is that the service sends back an error because of the quotes, it doesn´t recognise them. If i try to send a dictionary like the following:
request_dictionary = {
'codigoAmbiente': 2,
'codigoModalidad': 2,
'codigoPuntoVenta': 0,
'codigoSistema': AA5BB4CC3,
'codigoSucursal': 0,
'cuis': A1B2C3,
'nit': 12343456
}
Python throws the error "NameError: AA5BB4CC3 is not defined".
How should my code look like so the request to the service is as intended?

I´ve made a mistake in my code. It wasn´t the quotes. The correct code is the following:
from suds.client import Client
url = <service_url>
parameter = <service_method_parameter>
method = <service_method>
client = Client(url)
parameter_object = client.factory.create(str(parameter))
for var, value in request_dictionary.items():
parameter_object[str(var)] = value
request_response = getattr(client.service, method)(parameter_object)
print(request_response)
As you can notice, the mistake was in this line:
request_response = getattr(client.service, method)(parameter_object)
in wich the "parameter_object" dicitonary that contains the request values was missing.

Related

NodeJS using single quotes instead of double quotes in object [Answered]

[Answered by: Loulou BadWeed]
Hi #NickP. , did you stringify/serialize your payload before passing
it in the fetch body ? Does not seem the case from your example and I
don't think fetch does that for you. Try JSON.stringify(config) in the
body argument of the fetch function
I have a "small" problem.
I can't figure out, why nodejs uses single quotes for the string value instead of double quotes...
My Code
let config = {}
config["active"] = 1
config["domain"] = req.body.domain
config["mailboxes"] = req.body.mailboxes
config["defquota"] = req.body.defquota
config["maxquota"] = req.body.maxquota
config["quota"] = req.body.quota
config["restart_sogo"] = 10
console.log(req.body.domain)
console.log(config)
What I input:
{
"domain": "domain.tld",
"mailboxes": 10,
"defquota": 512,
"maxquota": 1024,
"quota": 10240
}
What I get:
{
active: 1,
domain: 'domain.tld',
mailboxes: 10,
defquota: 512,
maxquota: 1024,
quota: 10240,
restart_sogo: 10
}
The problem I have with this, is that the mailcow api doesn't like single quotes in the request body. :) Does anyone know, why this happens and can help me?
I tried replacing the single quotes with str.replace() or str.replaceAll(). But that didn't work. I tried using both types where I used the '' outside of the "".
I also already asked ChatGPT for help, but the results were just the replace and replaceAll...
PS: It's 4:30 AM when I wrote this. I'm not at 100% of my usual capacity. So please don't hate me for my question.

Python list add variables in rows

im trying to add variables to a list that i created. Got a result from a session.execute.
i´ve done this:
def machine_id(session, machine_serial):
stmt_raw = '''
SELECT
id
FROM
machine
WHERE
machine.serial = :machine_serial_arg
'''
utc_now = datetime.datetime.utcnow()
utc_now_iso = pytz.utc.localize(utc_now).isoformat()
utc_start = datetime.datetime.utcnow() - datetime.timedelta(days = 30)
utc_start_iso = pytz.utc.localize(utc_start).isoformat()
stmt_args = {
'machine_serial_arg': machine_serial,
}
stmt = text(stmt_raw).columns(
#ts_insert = ISODateTime
)
result = session.execute(stmt, stmt_args)
ts = utc_now_iso
ts_start = utc_start_iso
ID = []
for row in result:
ID.append({
'id': row[0],
'ts': ts,
'ts_start': ts_start,
})
return ID
In trying to get the result over api like this:
def form_response(response, session):
result_machine_id = machine_id(session, machine_serial)
if not result_machine_id:
response['Error'] = 'Seriennummer nicht vorhanden/gefunden'
return
response['id_timerange'] = result_machine_id
Output looks fine.
{
"id_timerange": [
{
"id": 1,
"ts": "2020-08-13T08:32:25.835055+00:00",
"ts_start": "2020-07-14T08:32:25.835089+00:00"
}
]
}
Now i only want the id from it as a parameter for another function. Problem is i think its not a list. I cant select the first element. result_machine_id[0] result is like the posted Output. I think in my first function i only add ts & ts_start to the first row? Is it possible to add emtpy rows and then add 'ts':ts as value?
Help would be nice
If I have understood your question correctly ...
Your output looks like dict. so access its id_timerange key which gives you a list. Access the first element which gives you another dict. On this dict you have an id key:
result_machine_id["id_timerange"][0]["id"]

Python - Error querying Solarwinds N-Central via SOAP

I'm using python 3 to write a script that generates a customer report for Solarwinds N-Central. The script uses SOAP to query N-Central and I'm using zeep for this project. While not new to python I am new to SOAP.
When calling the CustomerList fuction I'm getting the TypeError: __init__() got an unexpected keyword argument 'listSOs'
import zeep
wsdl = 'http://' + <server url> + '/dms/services/ServerEI?wsdl'
client = zeep.CachingClient(wsdl=wsdl)
config = {'listSOs': 'true'}
customers = client.service.CustomerList(Username=nc_user, Password=nc_pass, Settings=config)
Per the perameters below 'listSOs' is not only a valid keyword, its the only one accepted.
CustomerList
public com.nable.nobj.ei.Customer[] CustomerList(String username, String password, com.nable.nobj.ei.T_KeyPair[] settings) throws RemoteException
Parameters:
username - MSP N-central username
password - Corresponding MSP N-central password
settings - A list of non default settings stored in a T_KeyPair[]. Below is a list of the acceptable Keys and Values. If not used leave null
(Key) listSOs - (Value) "true" or "false". If true only SOs with be shown, if false only customers and sites will be shown. Default value is false.
I've also tried passing the dictionary as part of a list:
config = []
key = {'listSOs': 'true'}
config += key
TypeError: Any element received object of type 'str', expected lxml.etree._Element or builtins.dict or zeep.objects.T_KeyPair
Omitting the Settings value entirely:
customers = client.service.CustomerList(Username=nc_user, Password=nc_pass)
zeep.exceptions.ValidationError: Missing element Settings (CustomerList.Settings)
And trying zeep's SkipValue:
customers = client.service.CustomerList(Username=nc_user, Password=nc_pass, Settings=zeep.xsd.SkipValue)
zeep.exceptions.Fault: java.lang.NullPointerException
I'm probably missing something simple but I've been banging my head against the wall off and on this for awhile I'm hoping someone can point me in the right direction.
Here's my source code from my getAssets.py script. I did it in Python2.7, easily upgradeable though. Hope it helps someone else, N-central's API documentation is really bad lol.
#pip2.7 install zeep
import zeep, sys, csv, copy
from zeep import helpers
api_username = 'your_ncentral_api_user'
api_password='your_ncentral_api_user_pw'
wsdl = 'https://(yourdomain|tenant)/dms2/services2/ServerEI2?wsdl'
client = zeep.CachingClient(wsdl=wsdl)
response = client.service.deviceList(
username=api_username,
password=api_password,
settings=
{
'key': 'customerId',
'value': 1
}
)
# If you can't tell yet, I code sloppy
devices_list = []
device_dict = {}
dev_inc = 0
max_dict_keys = 0
final_keys = []
for device in response:
# Iterate through all device nodes
for device_properties in device.items:
# Iterate through each device's properties and add it to a dict (keyed array)
device_dict[device_properties.first]=device_properties.second
# Dig further into device properties
device_properties = client.service.devicePropertyList(
username=api_username,
password=api_password,
deviceIDs=device_dict['device.deviceid'],
reverseOrder=False
)
prop_ind = 0 # This is a hacky thing I did to make my CSV writing work
for device_node in device_properties:
for prop_tree in device_node.properties:
for key, value in helpers.serialize_object(prop_tree).items():
prop_ind+=1
device_dict["prop" + str(prop_ind) + "_" + str(key)]=str(value)
# Append the dict to a list (array), giving us a multi dimensional array, you need to do deep copy, as .copy will act like a pointer
devices_list.append(copy.deepcopy(device_dict))
# check to see the amount of keys in the last item
if len(devices_list[-1].keys()) > max_dict_keys:
max_dict_keys = len(devices_list[-1].keys())
final_keys = devices_list[-1].keys()
print "Gathered all the datas of N-central devices count: ",len(devices_list)
# Write the data out to a CSV
with open('output.csv', 'w') as csvfile:
fieldnames = final_keys
writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
writer.writeheader()
for csv_line in devices_list:
writer.writerow(csv_line)

Can't get HTTP headers from request

I'm trying to get the headers from a HTTP request. I've tried echoing them, only to get a compile error. I've tried looping through the headers as well. My code is:
var packet = newMultipartData()
packet["username"] = username
packet["password"] = password
var response = post(BASE & "users/login", multipart=packet)
echo response.headers
And the error I'm getting is: Error: type mismatch: got (HttpHeaders)
Figured it out - Turns out I can call the one I want from the list. Ex: response.headers["X-CSRF-TOKEN"]
The reason your code does not work because there is no $ proc defined for HttpHeaders:
let headers = newHttpHeaders()
headers["foo"] = "bar"
headers["foo2"] = "bar2"
echo headers["foo"] # compiles
echo headers # does _not_ compile
We can quickly implement an own $ proc ourselves:
proc `$`(h: HttpHeaders): string =
result = "{"
for key, value in h:
if result.len > 1: result.add(", ")
result.add(key)
result.add(": ")
result.add(value)
result.add("}")
The implementation is based on https://github.com/nim-lang/Nim/blob/master/lib/pure/collections/tables.nim#L333. Because HttpHeaders is just a type to a table, we can simply reuse the existing proc.
type
HttpHeaders* = ref object
table*: TableRef[string, seq[string]]

Unexpected character encountered while parsing value: c. Path '', line 0, position 0.

I know the question is asked before but i tried all the options and could not get ride of it . my code is something like this
WebClient client = new WebClient();
string url = "https://demos.telerik.com/kendo-ui/service/StockData";
string EncryptedJson = client.DownloadString(url);
var dataresponse = (JObject)JsonConvert.DeserializeObject(EncryptedJson);
and at deserialzeObject it is throwing the exception
Unexpected character encountered while parsing value: c. Path '', line
0, position 0.
while the client.DownloadString(url) is giving data in the following format
callback([{"Date":"/Date(1196467200000)/","Close":40.635,"Volume":1650185491,"Open":40.640,"High":40.680,"Low":39.090}])
That's not JSON, it's JSONP.
Remove the callback( at the start and the ) at the end to make it JSON:
EncryptedJson = EncryptedJson.Substring(9, EncryptedJson.Length - 10);

Resources