Calaos, Home Automation Forum

Full Version: API Calaos - Recuperer le JSON avec Python 3
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Bonjour a tous,

J'essaie l'API Calaos avec Python 3. Le script ci-dessous ne fonctionne pas (le serveur retourne une page vide).  Quelqu'un a deja reussi ?  A noter que ca marche avec wget comme decrit ici https://www.calaos.fr/wiki/en/protocole_json .


Code:
import urllib.request, urllib.parse

import json
import ssl

url = "https://XXX.XXX.XXX.XXX/api.php"

params = {
    "cn_user": "XXX",
    "cn_pass": "XXX",
    "action": "get_home"  # get the complete configuration of the house
    }

context = ssl._create_unverified_context()
response = urllib.request.urlopen(url, urllib.parse.urlencode(params).encode("utf-8"), context=context)
body = response.read()
data = json.loads(body.decode("utf-8"))
print(data)
Il faut faire une requete HTTP POST et pas GET. Il faut aussi mettre le header Content-Type: application/json et envoyer le "params" en json dans le body.
Merci Raoul.

Donc voila comment faire pour ceux que ca interesse.

Code:
import urllib.request, urllib.parse
import json
import ssl

calaos_url = 'https://XXX.XXX.XXX.XXX/api.php' # Calaos server API url
calaos_user = 'XXX'
calaos_password = 'XXX'

# Parameters dictionary to be sent to Calaos server
dict_send = {
    'cn_user': calaos_user,
    'cn_pass': calaos_password,
    'action': 'get_home'  # get the complete configuration of the house
    }

json_send = json.dumps(dict_send) # parameters string in JSON format
data_send = json_send.encode('ascii') # bytes data to be sent
headers_send = {'Content-Type': 'application/json'} # media type of the data to be sent
request = urllib.request.Request(calaos_url, data_send, headers_send) # data sent with POST method
context = ssl._create_unverified_context() # do not verify the SSL certificate

with urllib.request.urlopen(request, context=context) as response:
    print(response.info())
    data_receive = response.read() # bytes data received
    json_receive = data_receive.decode('ascii') # string received in JSON format
    dict_receive = json.loads(json_receive) # dictionary received
    print(dict_receive)

EDIT : C'est maintenant sur le wiki https://calaos.fr/wiki/en/protocole_json..._languages
super merci