Guillaume Taquet Gasperini 28614a0504 fix rest platform headers not working
headers were of type str, but requests.get expects a dict.
This deserializes the headers argument from str to dict (via json).
2020-04-02 13:17:17 +02:00

106 lines
4.0 KiB
Python

"""
##### rest
Make a call on a REST API and display the results as a jinja formatted string.
```ini
[variable_name]
platform = rest
resource = https://your-website.com/api
value_template = {{value}}
method = post
authentication = basic
username = my_username
password = my_password
payload = {"var1": "hi", "var2": 1}
headers = {"Content-Type": "application/json"}
verify = false
```
> **Returns:** `value_template` as rendered string
| Variable | Required | Description | Options |
|-----------------|----------|-----------------------------------------------------------------|-------------------|
| [variable_name] | Yes | Name for the data source. | [variable_name] |
| platform | Yes | Name of the platform. | rest |
| resource | Yes | Url of rest api resource. | url |
| value_template | Yes | Jinja template for how the returned data from api is displayed. | jinja template |
| method | No | Method for the api call, default is GET | GET,POST |
| authentication | No | Authentication for the api call, default is None | None,basic,digest |
| username | No | Username to use for auth. | string |
| password | No | Password to use for auth. | string |
| payload | No | Payload for post request. | json |
| headers | No | Custom headers for get or post | json |
| verify | No | Turn TLS verification on or off, default is True | true,false |
> **Working example:**
>```ini
>[test]
>platform = rest
>resource = https://pokeapi.co/api/v2/pokemon
>value_template = Pokemon: {{value['count']}}
>
>[Pokemon]
>prefix = https://
>url = pokemon.com
>icon = static/images/apps/default.png
>description = Data sources example
>open_in = this_tab
>data_sources = test
>```
"""
import json
from requests import get, post
from requests.auth import HTTPBasicAuth, HTTPDigestAuth
from flask import render_template_string
class Platform:
def __init__(self, *args, **kwargs):
# parse the user's options from the config entries
for key, value in kwargs.items():
if key == "headers":
value = json.loads(value)
self.__dict__[key] = value
# set defaults for omitted options
if not hasattr(self, "method"):
self.method = "GET"
if not hasattr(self, "authentication"):
self.authentication = None
if not hasattr(self, "headers"):
self.headers = None
if not hasattr(self, "verify"):
self.verify = True
def process(self):
if self.authentication:
if self.authentication.lower() == "digest":
auth = HTTPDigestAuth(self.username, self.password)
else:
auth = HTTPBasicAuth(self.username, self.password)
else:
auth = None
verify = False if str(self.verify).lower() == "false" else True
if self.method.upper() == "GET":
try:
value = get(
self.resource, auth=auth, headers=self.headers, verify=verify
).json()
except Exception as e:
value = f"{e}"
elif self.method.upper() == "POST":
payload = json.loads(self.payload.replace("'", '"'))
value = post(
self.resource,
data=payload,
auth=auth,
headers=self.headers,
verify=verify,
)
value_template = render_template_string(self.value_template, value=value)
return value_template