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 os
import pkgutil
import re
import types
import typing
import re
from flask import Flask
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}")
@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):
command = PluginService.command_named(plugin_display_name, command_name)
if command is None:
@ -129,7 +129,7 @@ def do_command(plugin_display_name, command_name):
)
params = request.json
task_data = params.pop('spiff__task_data', '{}')
task_data = params.pop("spiff__task_data", "{}")
try:
result = command(**params).execute(app.config, task_data)

View File

@ -1,15 +1,13 @@
"""AddDynamoItem."""
import json
from decimal import Decimal
from connector_aws.auths.simpleAuth import SimpleAuth # type: ignore
class AddDynamoItem:
"""Add a new record to a dynamo db table."""
def __init__(
self, table_name: str, item_data: dict
):
def __init__(self, table_name: str, item_data: dict):
"""
: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.
@ -20,7 +18,6 @@ class AddDynamoItem:
self.fix_floats(item_data)
self.item_data = item_data
def execute(self, config, task_data):
"""Execute."""
# Get the service resource.

View File

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

View File

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

View File

@ -3,6 +3,7 @@ import json
import requests
class GetEmployeeInfo:
"""GetPayRate."""
@ -21,17 +22,23 @@ class GetEmployeeInfo:
params = {"fields": self.fields, "onlyCurrent": "true"}
auth = (api_key, "x")
status_code = 0
try:
response = requests.get(url, params, headers=headers, auth=auth)
except Exception:
response = '{ "error": "Invalid Employee ID" }'
raw_response = requests.get(url, params, headers=headers, auth=auth)
status_code = raw_response.status_code
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 {
"response": response,
"status": response.status_code,
"status": status_code,
"mimetype": "application/json",
}
#
# Sample response
#
@ -53,16 +60,23 @@ class GetPayRate:
def execute(self, config, task_data):
"""Execute."""
status_code = 0
try:
response = GetEmployeeInfo(self.employee_id, "payRate").execute(config, task_data)
parsed_response = json.loads(response["response"].text)
response = GetEmployeeInfo(self.employee_id, "payRate").execute(
config, task_data
)
parsed_response = json.loads(response["response"])
pay_rate = parsed_response["payRate"]
pay_rate_parts = pay_rate.split(" ")
parsed_response["amount"] = pay_rate_parts[0]
parsed_response["currency"] = pay_rate_parts[1]
response["response"] = json.dumps(parsed_response)
except Exception:
response = '{ "error": "Invalid Employee ID" }'
response = json.dumps(parsed_response)
except Exception as ex:
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
}'
"""
@dataclass
class SendMessage:
"""SendMessage."""
@ -36,12 +38,11 @@ class SendMessage:
request_body = {
"jsonrpc": "2.0",
"method": self.message_type,
"params":[{"id": self.recipient,
"message": self.message}],
"id": 1
"params": [{"id": self.recipient, "message": self.message}],
"id": 1,
}
status_code = None
status_code = 0
try:
raw_response = requests.post(url, json.dumps(request_body), headers=headers)
status_code = raw_response.status_code
@ -49,6 +50,7 @@ class SendMessage:
response = json.dumps(parsed_response)
except Exception as ex:
response = json.dumps({"error": str(ex)})
status_code = 500
return {
"response": response,

View File

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

View File

@ -189,7 +189,7 @@ class CreateInvoice:
@api_client.oauth2_token_saver
def store_xero_oauth2_token(token):
"""Store_xero_oauth2_token."""
token_store[token_store_key] = token # noqa
token_store[token_store_key] = token # noqa
store_xero_oauth2_token(access_token)
@ -232,11 +232,13 @@ class CreateInvoice:
created_invoices = api_instance.create_invoices(
xero_tenant_id, invoices, summarize_errors, unitdp
)
response = json.dumps({
"api_response": serialize(created_invoices),
"refreshed_token_set": obtain_xero_oauth2_token(),
"auth": "xero/OAuth",
})
response = json.dumps(
{
"api_response": serialize(created_invoices),
"refreshed_token_set": obtain_xero_oauth2_token(),
"auth": "xero/OAuth",
}
)
status = 200
except Exception as e:
# TODO better error logging/reporting in debug