how to pass value from json-rpc and let python read it - python

I added {"value":10} in json-rpc:
import requests
import xbmc
import xbmcgui
import xbmcplugin
import xbmcaddon
import json
headers = {
'Content-Type': 'application/json',
}
data = '{"jsonrpc":"2.0","method":"Addons.ExecuteAddon","params":
{"addonid":"script.activatewindowid"},"params":{"value": 10},"id":1}'
response = requests.post('http://192.168.1.200:8080/jsonrpc',
headers=headers,
data=data,
auth=('user', '1234'))
And I want the python script can understand the value:10 and use it in his IF function:
import json
json_string = what should be here???
parsed_data = json.loads(json_string)
x = parsed_data["value"]
if x == 10:
xbmc.executebuiltin('ActivateWindow(9000)')
else:
xbmc.executebuiltin('ActivateWindow(1199)')
the json-rpc data reached coerrectly to python script but the python didn't understand how to deal with x value?
Any suggestion to solve this issue please?

Related

Read and register EventStream API in python

I did this code to connect to an API and read the data. (I removed the Cookie and URL)
import requests
import urllib3
import json
import sseclient
import pprint
requests.packages.urllib3.disable_warnings()
requests.packages.urllib3.util.ssl_.DEFAULT_CIPHERS += ':HIGH:!DH:!aNULL'
parameter = {
"Cookie" : ""
}
response2 = requests.get("", headers=parameter, verify=False, stream=True)
print(response2.status_code)
for a in response2.iter_lines(chunk_size=1024, decode_unicode=True):
print(a)
It works but the data are not very clean. Example :
data: {"id":"1660609778692","timestamp":1660636693,"heure":35893,"sens":1,"action":"A"}
event: heartbeat
data:
data: {"id":"1660604578692","timestamp":1660636665,"heure":35864,"sens":2,"action":"A"}
Can you tell me how to clean the data ? maybe have a json format.
Is there a good way to register the data in a file ?
If you have advice to improve the code, it would be great.
Thanks.

Error in POST API python while trying to send data

Here is the json data to send
{
"mobile": "1234567890"
}
Here is the python code:
from urllib import response
import requests
import urllib
import json
query = {"mobile": "1234567890"}
headers = {"Content-Type":"application/json"}
url = 'https://cdn-api.co-vin.in/api/v2/auth/public/generateOTP'
y = requests.post(url, data=query, headers=headers)
print(y)
Response from the API:
c:/pythonprojects/covid-otp-requests.py
<Response [400]>
I am a newbie, I don't understand the mistake I am making, Can someone please help me out?.
Fix here:
from urllib import response
import requests
import urllib
import json
params = {
"mobile": "1234567890"
}
headers = {"Content-Type":"application/json"}
response = requests.post("https://cdn-api.co-vin.in/api/v2/auth/public/generateOTP", data=json.dumps(params))
print(response)
details = response.json()
print(details)
The parameters has to be sent in json format which I making a mistake in.
Thank you all!

How to set params in Python requests library

I have the following code using urllib in Python 2.7 and its working. I'm trying to do the same request using the requests library but I cant get it to work.
import urllib
import urllib2
import json
req = urllib2.Request(url='https://testone.limequery.com/index.php/admin/remotecontrol',\
data='{\"method\":\"get_session_key\",\"params\":[\"username\",\"password\"],\"id\":1}')
req.add_header('content-type', 'application/json')
req.add_header('connection', 'Keep-Alive')
f = urllib2.urlopen(req)
myretun = f.read()
j=json.loads(myretun)
print(j['result'])
Using requests library( Doesn't work)
import requests
import json
d= {"method":"get_session_key","params":["username","password"],"id":"1"}
headers = {'content-type' :'application/json','connection': 'Keep-Alive'}
req2 = requests.get(url='https://testone.limequery.com/index.php/admin/remotecontrol',data=d,headers=headers)
json_data = json.loads(req2.text)
print(json data['result'])
I'm getting an error JSONDecodeError: Expecting value: line 1 column 1 (char 0) How can I make the code work with the requests library?
First, you're sending the wrong type of request. You're sending a GET request, but you need to send a POST, with requests.post.
Second, passing a dict as data will form-encode the data rather than JSON-encoding it. If you want to use JSON in your request body, use the json argument, not data:
requests.post(url=..., json=d)
Reference Link: http://docs.python-requests.org/en/master/api/
You can use requests module of python like so
import requests
Req = requests.request(
method = "GET", # or "POST", "PUT", "DELETE", "PATCH" etcetera
url = "http(s)://*",
params = {"key": "value"}, # IF GET Request (Optional)
data = {"key": "value"}, # IF POST Request (Optional)
headers = {"header_name": "header_value"} # (Optional)
)
print Req.content
You can surround the code with try::catch block like below to catch any exception thrown by requests module
try:
# requests.request(** Arguments)
except requests.exceptions.RequestException as e:
print e
For full argument list, please check reference link.

make python accept json via the web

I have a web server and can run python on it, like this:
import os
from urllib.parse import parse_qsl
def main():
thestring = os.environ["QUERY_STRING"]
parameter_dict = dict(parse_qsl(thestring))
print(parameter_dict)
print("Content-Type: text/plain")
print("")
main()
If I hit is like this: http://127.0.0.1/web.py?hello=world
I'll get a nice little hash:
{'hello': 'world'}
That works just fine for my purposes. Now what I'm trying to do is make this webserver accept json input.
I'm using this code to 'throw' json at the URL
body = {
"username":"user1",
"folder":"folder1"
}
req = urllib.request.Request("http://127.0.0.1/web.py")
req.add_header('Content-Type', 'application/json; charset=utf-8')
jsondata = json.dumps(body)
jsondataasbytes = jsondata.encode('utf-8') # needs to be bytes
req.add_header('Content-Length', len(jsondataasbytes))
response = urllib.request.urlopen(req, jsondataasbytes)
content = json.loads(response.read().decode("utf-8"))
print(content)
But what do I need to do in my top section of code to have web.py 'accept' the json and be able to use it? Ideally just put the json into a dict. I bet this is just something really simple and I'm just missing a basic command. Thank you in advance!

Issue with making transaction in Neo4J Python

I am trying to send a POST request with a Neo4j transaction query. Although I get a response 200 the node is not created. This is my Python script:
import requests
import json
import csv
headers = {'content-type': 'application/json'}
url = "http://localhost:7474/db/data/transaction/commit"
checkNode = {"query" : '{"statements": [{"statement":"CREATE (n:test) RETURN n"}]}'}
mkr =requests.post(url, data=json.dumps(checkNode), headers=headers)
print(mkr)
I haven't used transactions before and nver tried to create one through the Rest Api. What am I doing wrong here?
It seems unlikely to me that you're receiving a response code of 200; you should be getting a 500 as the transactional endpoint doesn't accept a query parameter. Try this:
import requests
import json
import csv
headers = {'content-type': 'application/json'}
url = "http://localhost:7474/db/data/transaction/commit"
checkNode = {"statements":[{"statement":"CREATE n RETURN n"}]}
mkr = requests.post(url, data=json.dumps(checkNode), headers=headers)
print(mkr.text)

Categories

Resources