Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
43 changes: 43 additions & 0 deletions pyShelly/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
import base64
import traceback
import json
import urllib
from datetime import datetime
from .compat import s

Expand Down Expand Up @@ -79,3 +80,45 @@ def shelly_http_get(host, url, username, password, log_error=True):
conn.close()

return success, res

def shelly_http_post(host, url, body, username, password, log_error=True):
"""Send HTTP POST request"""
res = ""
success = False
conn = None
try:
LOGGER.debug("http://%s%s", host, url)
conn = httplib.HTTPConnection(host, timeout=5)
headers = {}
if username is not None \
and password is not None:
combo = '%s:%s' % (username, password)
auth = s(
base64.b64encode(combo.encode())) # .replace('\n', '')
headers["Authorization"] = "Basic %s" % auth
conn.request("POST", url, urllib.parse.urlencode(body), headers)
resp = conn.getresponse()

if resp.status == 200:
body = resp.read()
#LOGGER.debug("Body: %s", body)
res = json.loads(s(body))
success = True
LOGGER.debug("http://%s%s - Ok", host, url)
else:
res = "Error, " + str(resp.status) \
+ ' ' + str(resp.reason)
LOGGER.warning(res)
except Exception as ex:
success = False
res = str(ex)
if log_error:
exception_log(ex, "Error http POST: http://{}{}", host, url)
else:
LOGGER.debug(
"Fail http POST: %s %s %s", host, url, ex)
finally:
if conn:
conn.close()

return success, res