Merge pull request #17 from sartography/feature/make_responses_act_the_same

make the responses act more the same w/ burnettk
This commit is contained in:
Kevin Burnett 2022-10-27 15:26:09 +00:00 committed by GitHub
commit cae53313a3
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
8 changed files with 52 additions and 42 deletions

6
app.py
View File

@ -3,9 +3,9 @@ import inspect
import json import json
import os import os
import pkgutil import pkgutil
import re
import types import types
import typing import typing
import re
from flask import Flask from flask import Flask
from flask import redirect from flask import redirect
@ -120,7 +120,7 @@ def auth_callback(plugin_display_name, auth_name):
return redirect(f"{redirect_url}{redirect_url_params_symbol}response={response}") return redirect(f"{redirect_url}{redirect_url_params_symbol}response={response}")
@app.route("/v1/do/<plugin_display_name>/<command_name>", methods = ["GET", "POST"]) @app.route("/v1/do/<plugin_display_name>/<command_name>", methods=["GET", "POST"])
def do_command(plugin_display_name, command_name): def do_command(plugin_display_name, command_name):
command = PluginService.command_named(plugin_display_name, command_name) command = PluginService.command_named(plugin_display_name, command_name)
if command is None: if command is None:
@ -129,7 +129,7 @@ def do_command(plugin_display_name, command_name):
) )
params = request.json params = request.json
task_data = params.pop('spiff__task_data', '{}') task_data = params.pop("spiff__task_data", "{}")
try: try:
result = command(**params).execute(app.config, task_data) result = command(**params).execute(app.config, task_data)

View File

@ -1,15 +1,13 @@
"""AddDynamoItem.""" """AddDynamoItem."""
import json import json
from decimal import Decimal
from connector_aws.auths.simpleAuth import SimpleAuth # type: ignore from connector_aws.auths.simpleAuth import SimpleAuth # type: ignore
class AddDynamoItem: class AddDynamoItem:
"""Add a new record to a dynamo db table.""" """Add a new record to a dynamo db table."""
def __init__( def __init__(self, table_name: str, item_data: dict):
self, table_name: str, item_data: dict
):
""" """
:param table_name: The name of hte Dynamo DB table to add information to. :param table_name: The name of hte Dynamo DB table to add information to.
:param item_data: The data to add, should be in json format. :param item_data: The data to add, should be in json format.
@ -20,7 +18,6 @@ class AddDynamoItem:
self.fix_floats(item_data) self.fix_floats(item_data)
self.item_data = item_data self.item_data = item_data
def execute(self, config, task_data): def execute(self, config, task_data):
"""Execute.""" """Execute."""
# Get the service resource. # Get the service resource.

View File

@ -1,14 +1,11 @@
"""QueryDynamoTable.""" """QueryDynamoTable."""
import simplejson as json import simplejson as json
from boto3 import dynamodb
from boto3.dynamodb.conditions import Key from boto3.dynamodb.conditions import Key
from connector_aws.auths.simpleAuth import SimpleAuth # type: ignore from connector_aws.auths.simpleAuth import SimpleAuth # type: ignore
class QueryDynamoTable: class QueryDynamoTable:
"""Return all records for a given partition key, and optionally a sort_key""" """Return all records for a given partition key, and optionally a sort_key."""
def __init__(self, table_name: str, partition_key: str, sort_key: str = None): def __init__(self, table_name: str, partition_key: str, sort_key: str = None):
""" """
@ -25,8 +22,8 @@ class QueryDynamoTable:
"""Execute.""" """Execute."""
dynamodb = SimpleAuth("dynamodb", config).get_resource() dynamodb = SimpleAuth("dynamodb", config).get_resource()
table = dynamodb.Table(self.table_name) table = dynamodb.Table(self.table_name)
partition_key_name = self.get_schema_key_name(table, 'HASH') partition_key_name = self.get_schema_key_name(table, "HASH")
sort_key_name = self.get_schema_key_name(table, 'RANGE') sort_key_name = self.get_schema_key_name(table, "RANGE")
query = {partition_key_name: self.partition_key} query = {partition_key_name: self.partition_key}
condition = Key(partition_key_name).eq(self.partition_key) condition = Key(partition_key_name).eq(self.partition_key)
if self.sort_key: if self.sort_key:
@ -38,6 +35,7 @@ class QueryDynamoTable:
return dict(response=result_str, mimetype="application/json") return dict(response=result_str, mimetype="application/json")
def get_schema_key_name(self, table, key_type: str): def get_schema_key_name(self, table, key_type: str):
"""Get_schema_key_name."""
for item in table.key_schema: for item in table.key_schema:
if item['KeyType'] == key_type: if item["KeyType"] == key_type:
return item['AttributeName'] return item["AttributeName"]

View File

@ -27,15 +27,12 @@ class UploadFileData:
def execute(self, config, task_data): def execute(self, config, task_data):
"""Execute.""" """Execute."""
file_data = self.parse_file_data(self.file_data) file_data = self.parse_file_data(self.file_data)
# Upload the file # Upload the file
client = SimpleAuth("s3", config).get_resource() client = SimpleAuth("s3", config).get_resource()
try: try:
result = client.Object(self.bucket, self.object_name).put( result = client.Object(self.bucket, self.object_name).put(Body=file_data)
Body=file_data
)
status = str(result["ResponseMetadata"]["HTTPStatusCode"]) status = str(result["ResponseMetadata"]["HTTPStatusCode"])
# TODO these can be improved # TODO these can be improved
@ -50,6 +47,7 @@ class UploadFileData:
return {"response": response, "status": status, "mimetype": "application/json"} return {"response": response, "status": status, "mimetype": "application/json"}
def parse_file_data(self, raw_data): def parse_file_data(self, raw_data):
"""Parse_file_data."""
# looks like: # looks like:
# "data:application/pdf;name=Harmeet_13435%20(1).pdf;base64,JVBERi0xLjQKJZOMi54gUmVwb3J0TGFiIEdlb....=" # "data:application/pdf;name=Harmeet_13435%20(1).pdf;base64,JVBERi0xLjQKJZOMi54gUmVwb3J0TGFiIEdlb....="
parts = raw_data.split(";", 2) parts = raw_data.split(";", 2)

View File

@ -3,6 +3,7 @@ import json
import requests import requests
class GetEmployeeInfo: class GetEmployeeInfo:
"""GetPayRate.""" """GetPayRate."""
@ -21,17 +22,23 @@ class GetEmployeeInfo:
params = {"fields": self.fields, "onlyCurrent": "true"} params = {"fields": self.fields, "onlyCurrent": "true"}
auth = (api_key, "x") auth = (api_key, "x")
status_code = 0
try: try:
response = requests.get(url, params, headers=headers, auth=auth) raw_response = requests.get(url, params, headers=headers, auth=auth)
except Exception: status_code = raw_response.status_code
response = '{ "error": "Invalid Employee ID" }' parsed_response = json.loads(raw_response.text)
response = json.dumps(parsed_response)
except Exception as ex:
response = json.dumps({"error": str(ex)})
status_code = 500
return { return {
"response": response, "response": response,
"status": response.status_code, "status": status_code,
"mimetype": "application/json", "mimetype": "application/json",
} }
# #
# Sample response # Sample response
# #
@ -53,16 +60,23 @@ class GetPayRate:
def execute(self, config, task_data): def execute(self, config, task_data):
"""Execute.""" """Execute."""
status_code = 0
try: try:
response = GetEmployeeInfo(self.employee_id, "payRate").execute(config, task_data) response = GetEmployeeInfo(self.employee_id, "payRate").execute(
parsed_response = json.loads(response["response"].text) config, task_data
)
parsed_response = json.loads(response["response"])
pay_rate = parsed_response["payRate"] pay_rate = parsed_response["payRate"]
pay_rate_parts = pay_rate.split(" ") pay_rate_parts = pay_rate.split(" ")
parsed_response["amount"] = pay_rate_parts[0] parsed_response["amount"] = pay_rate_parts[0]
parsed_response["currency"] = pay_rate_parts[1] parsed_response["currency"] = pay_rate_parts[1]
response["response"] = json.dumps(parsed_response) response = json.dumps(parsed_response)
except Exception: except Exception as ex:
response = '{ "error": "Invalid Employee ID" }' response = json.dumps({"error": str(ex)})
status_code = 500
return response return {
"response": response,
"status": status_code,
"mimetype": "application/json",
}

View File

@ -21,6 +21,8 @@ curl -XPOST http://localhost:8545 -H 'Content-type: application/json' \
"id": 1 "id": 1
}' }'
""" """
@dataclass @dataclass
class SendMessage: class SendMessage:
"""SendMessage.""" """SendMessage."""
@ -36,12 +38,11 @@ class SendMessage:
request_body = { request_body = {
"jsonrpc": "2.0", "jsonrpc": "2.0",
"method": self.message_type, "method": self.message_type,
"params":[{"id": self.recipient, "params": [{"id": self.recipient, "message": self.message}],
"message": self.message}], "id": 1,
"id": 1
} }
status_code = None status_code = 0
try: try:
raw_response = requests.post(url, json.dumps(request_body), headers=headers) raw_response = requests.post(url, json.dumps(request_body), headers=headers)
status_code = raw_response.status_code status_code = raw_response.status_code
@ -49,6 +50,7 @@ class SendMessage:
response = json.dumps(parsed_response) response = json.dumps(parsed_response)
except Exception as ex: except Exception as ex:
response = json.dumps({"error": str(ex)}) response = json.dumps({"error": str(ex)})
status_code = 500
return { return {
"response": response, "response": response,

View File

@ -6,7 +6,6 @@ class OAuth:
def __init__(self): def __init__(self):
"""__init__.""" """__init__."""
pass
def app_description(self, config): def app_description(self, config):
"""App_description.""" """App_description."""

View File

@ -232,11 +232,13 @@ class CreateInvoice:
created_invoices = api_instance.create_invoices( created_invoices = api_instance.create_invoices(
xero_tenant_id, invoices, summarize_errors, unitdp xero_tenant_id, invoices, summarize_errors, unitdp
) )
response = json.dumps({ response = json.dumps(
{
"api_response": serialize(created_invoices), "api_response": serialize(created_invoices),
"refreshed_token_set": obtain_xero_oauth2_token(), "refreshed_token_set": obtain_xero_oauth2_token(),
"auth": "xero/OAuth", "auth": "xero/OAuth",
}) }
)
status = 200 status = 200
except Exception as e: except Exception as e:
# TODO better error logging/reporting in debug # TODO better error logging/reporting in debug