velocity-python 0.0.6__py3-none-any.whl → 0.0.7__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.

Potentially problematic release.


This version of velocity-python might be problematic. Click here for more details.

velocity/aws/__init__.py CHANGED
@@ -1,12 +1,12 @@
1
1
  import os
2
2
  import requests
3
3
 
4
- from velocity.aws.handlers import LambdaHandler
5
- from velocity.aws.handlers import SqsHandler
6
-
7
4
  DEBUG = (os.environ.get('ENV') != 'production') \
8
5
  or (os.environ.get('DEBUG') == 'Y')
9
6
 
7
+ from velocity.aws.handlers import LambdaHandler
8
+ from velocity.aws.handlers import SqsHandler
9
+
10
10
  # This is helpful for running HTTPS clients on lambda.
11
11
  if os.path.exists('/opt/python/ca-certificates.crt'):
12
12
  os.environ["REQUESTS_CA_BUNDLE"] = '/opt/python/ca-certificates.crt'
@@ -1,123 +1,154 @@
1
1
  from velocity.misc.format import to_json
2
2
  import json
3
- import pprint
3
+ import sys
4
+ import os
4
5
  import traceback
6
+ from velocity.aws import DEBUG
7
+ from support.app import helpers, AlertError, enqueue
8
+ from response import Response
5
9
 
6
10
  class LambdaHandler:
7
11
  def __init__(self, event, context):
8
12
  self.event = event
9
13
  self.context = context
10
14
  self.serve_action_default = True
15
+ self.skip_action = False
11
16
 
12
- requestContext = event.get('requestContext', {})
13
- identity = requestContext.get('identity', {})
14
- headers = event.get('headers', {})
17
+ requestContext = event.get("requestContext") or {}
18
+ identity = requestContext.get("identity") or {}
19
+ headers = event.get("headers") or {}
20
+ auth = identity.get("cognitoAuthenticationProvider")
15
21
  self.session = {
16
- 'authentication_provider':
17
- identity.get('cognitoAuthenticationProvider'),
18
- 'authentication_type':
19
- identity.get('cognitoAuthenticationType'),
20
- 'cognito_user':
21
- identity.get('user'),
22
- 'is_desktop':
23
- headers.get('CloudFront-Is-Desktop-Viewer') == 'true',
24
- 'is_mobile':
25
- headers.get('CloudFront-Is-Mobile-Viewer') == 'true',
26
- 'is_smart_tv':
27
- headers.get('CloudFront-Is-SmartTV-Viewer') == 'true',
28
- 'is_tablet':
29
- headers.get('CloudFront-Is-Tablet-Viewer') == 'true',
30
- 'origin':
31
- headers.get('origin'),
32
- 'path':
33
- event.get('path'),
34
- 'referer':
35
- headers.get('Referer'),
36
- 'source_ip':
37
- identity.get('sourceIp'),
38
- 'user_agent':
39
- identity.get('userAgent'),
22
+ "authentication_provider": identity.get("cognitoAuthenticationProvider"),
23
+ "authentication_type": identity.get("cognitoAuthenticationType"),
24
+ "cognito_user": identity.get("user"),
25
+ "is_desktop": headers.get("CloudFront-Is-Desktop-Viewer") == "true",
26
+ "is_mobile": headers.get("CloudFront-Is-Mobile-Viewer") == "true",
27
+ "is_smart_tv": headers.get("CloudFront-Is-SmartTV-Viewer") == "true",
28
+ "is_tablet": headers.get("CloudFront-Is-Tablet-Viewer") == "true",
29
+ "origin": headers.get("origin"),
30
+ "path": event.get("path"),
31
+ "referer": headers.get("Referer"),
32
+ "source_ip": identity.get("sourceIp"),
33
+ "user_agent": identity.get("userAgent"),
34
+ "sub": auth.split(":")[-1] if auth else None,
40
35
  }
41
- if self.session.get('is_mobile'):
42
- self.session['device_type'] = 'mobile'
43
- elif self.session.get('is_desktop'):
44
- self.session['device_type'] = 'desktop'
45
- elif self.session.get('is_tablet'):
46
- self.session['device_type'] = 'tablet'
47
- elif self.session.get('is_smart_tv'):
48
- self.session['device_type'] = 'smart_tv'
36
+ if self.session.get("is_mobile"):
37
+ self.session["device_type"] = "mobile"
38
+ elif self.session.get("is_desktop"):
39
+ self.session["device_type"] = "desktop"
40
+ elif self.session.get("is_tablet"):
41
+ self.session["device_type"] = "tablet"
42
+ elif self.session.get("is_smart_tv"):
43
+ self.session["device_type"] = "smart_tv"
49
44
  else:
50
- self.session['device_type'] = 'unknown'
45
+ self.session["device_type"] = "unknown"
51
46
 
52
- def serve(self, tx):
53
- response = {
54
- 'statusCode': 200,
55
- 'body': '{}',
56
- 'headers': {
57
- 'Content-Type': 'application/json',
58
- "Access-Control-Allow-Origin": "*",
59
- },
47
+ def log(self, tx, message, function=None):
48
+ if not function:
49
+ function = "<Unknown>"
50
+ idx = 0
51
+ while True:
52
+ try:
53
+ temp = sys._getframe(idx).f_code.co_name
54
+ except ValueError as e:
55
+ break
56
+ if temp in ["x", "log", "_transaction"]:
57
+ idx += 1
58
+ continue
59
+ function = temp
60
+ break
61
+
62
+ data = {
63
+ "app_name": os.environ["ProjectName"],
64
+ "source_ip": self.session["source_ip"],
65
+ "referer": self.session["referer"],
66
+ "user_agent": self.session["user_agent"],
67
+ "device_type": self.session["device_type"],
68
+ "function": function,
69
+ "message": message,
60
70
  }
71
+ if "email_address" in self.session:
72
+ data["sys_modified_by"] = self.session["email_address"]
73
+ tx.table("sys_log").insert(data)
74
+
75
+ def serve(self, tx):
76
+ response = Response()
77
+ body = self.event.get("body")
78
+ postdata = {}
79
+ if isinstance(body, str) and len(body) > 0:
80
+ try:
81
+ postdata = json.loads(body)
82
+ except:
83
+ postdata = {"raw_body": body}
84
+ elif isinstance(body, dict):
85
+ postdata = body
86
+ elif isinstance(body, list) and len(body) > 0:
87
+ try:
88
+ new = "\n".join(body)
89
+ postdata = json.loads(new)
90
+ except:
91
+ postdata = {"raw_body": body}
92
+
93
+ req_params = self.event.get("queryStringParameters") or {}
61
94
  try:
62
- postdata = {}
63
- if self.event.get('body'):
64
- postdata = json.loads(self.event.get('body'))
65
- req_params = self.event.get('queryStringParameters') or {}
66
- if hasattr(self, 'beforeAction'):
67
- self.beforeAction(args=req_params,
68
- postdata=postdata,
69
- response=response)
95
+ if hasattr(self, "beforeAction"):
96
+ self.beforeAction(args=req_params, postdata=postdata, response=response)
70
97
  actions = []
71
- action = postdata.get('action', req_params.get('action'))
98
+ action = postdata.get("action", req_params.get("action"))
72
99
  if action:
73
100
  actions.append(
74
- f"on action {action.replace('-', ' ').replace('_', ' ')}".
75
- title().replace(' ', ''))
101
+ f"on action {action.replace('-', ' ').replace('_', ' ')}".title().replace(
102
+ " ", ""
103
+ )
104
+ )
76
105
  if self.serve_action_default:
77
- actions.append('OnActionDefault')
106
+ actions.append("OnActionDefault")
78
107
  for action in actions:
108
+ if self.skip_action:
109
+ break
79
110
  if hasattr(self, action):
80
- getattr(self, action)(args=req_params,
81
- postdata=postdata,
82
- response=response)
111
+ result = getattr(self, action)(
112
+ args=req_params, postdata=postdata, response=response
113
+ )
114
+ if result and result != response:
115
+ response.set_body(result)
83
116
  break
84
- if hasattr(self, 'afterAction'):
85
- self.afterAction(args=req_params,
86
- postdata=postdata,
87
- response=response)
88
-
117
+ if hasattr(self, "afterAction"):
118
+ self.afterAction(args=req_params, postdata=postdata, response=response)
119
+ except AlertError as e:
120
+ response.alert(e.get_payload())
89
121
  except Exception as e:
90
- response = {
91
- 'statusCode':
92
- 500,
93
- 'body':
94
- to_json({
95
- 'type': 'Unhandled Exception',
96
- 'error_message': str(e),
97
- 'user_message': 'Oops! An unhandled error occurred.',
98
- 'traceback': traceback.format_exc() if DEBUG else None
99
- }),
100
- 'headers': {
101
- 'Content-Type': 'application/json',
102
- 'Access-Control-Allow-Origin': '*'
103
- }
104
- }
105
- if hasattr(self, 'onError'):
106
- self.onError(args=req_params,
107
- postdata=postdata,
108
- response=response,
109
- exc=e,
110
- tb=traceback.format_exc())
122
+ response.exception()
123
+ if hasattr(self, "onError"):
124
+ self.onError(
125
+ args=req_params,
126
+ postdata=postdata,
127
+ response=response,
128
+ exc=e.__class__.__name__,
129
+ tb=traceback.format_exc(),
130
+ )
111
131
 
112
- return response
132
+ return response.render()
133
+
134
+ def track(self, tx, data={}, user=None):
135
+ data = data.copy()
136
+ data.update(
137
+ {
138
+ "source_ip": self.session["source_ip"],
139
+ "referer": self.session["referer"],
140
+ "user_agent": self.session["user_agent"],
141
+ "device_type": self.session["device_type"],
142
+ "sys_modified_by": self.session["email_address"],
143
+ }
144
+ )
145
+ tx.table(helpers.get_tracking_table(user or self.session)).insert(data)
113
146
 
114
147
  def OnActionDefault(self, tx, args, postdata, response):
115
- response['body'] = to_json({'event': self.event, 'postdata': postdata})
148
+ return {"event": self.event, "postdata": postdata}
116
149
 
117
- def onError(self, tx, args, postdata, response, exc, tb):
118
- pprint.pprint({
119
- 'message': 'Unhandled Exception',
120
- 'exception': str(exc),
121
- 'traceback': traceback.format_exc()
122
- })
150
+ def OnActionTracking(self, tx, args, postdata, response):
151
+ self.track(tx, postdata.get("payload", {}).get("data", {}))
123
152
 
153
+ def enqueue(self, tx, action, payload={}):
154
+ return enqueue(tx, action, payload, self.session["email_address"])
@@ -1,10 +1,8 @@
1
1
  from velocity.misc.format import to_json
2
2
  import sys
3
3
  import traceback
4
- import os
4
+ from velocity.aws import DEBUG
5
5
 
6
- DEBUG = (os.environ.get('ENV') != 'production') or \
7
- (os.environ.get('DEBUG') == 'Y')
8
6
 
9
7
  variants = [
10
8
  'success',
@@ -1,48 +1,85 @@
1
1
  from velocity.misc.format import to_json
2
2
  import json
3
+ import sys
4
+ import os
3
5
  import traceback
6
+ from velocity.aws import DEBUG
4
7
 
5
8
  class SqsHandler:
6
9
  def __init__(self, event, context):
7
10
  self.event = event
8
11
  self.context = context
9
12
  self.serve_action_default = True
13
+ self.skip_action = False
14
+
15
+ def log(self, tx, message, function=None):
16
+ if not function:
17
+ function = "<Unknown>"
18
+ idx = 0
19
+ while True:
20
+ try:
21
+ temp = sys._getframe(idx).f_code.co_name
22
+ except ValueError as e:
23
+ break
24
+ if temp in ["x", "log", "_transaction"]:
25
+ idx += 1
26
+ continue
27
+ function = temp
28
+ break
29
+
30
+ data = {
31
+ "app_name": os.environ["ProjectName"],
32
+ "referer": "SQS",
33
+ "user_agent": "QueueHandler",
34
+ "device_type": "Lambda",
35
+ "function": function,
36
+ "message": message,
37
+ "sys_modified_by": "lambda:BackOfficeQueueHandler",
38
+ }
39
+ tx.table("sys_log").insert(data)
10
40
 
11
41
  def serve(self, tx):
12
- records = self.event.get('Records', [])
13
- print(f"Handling batch of {len(records)} records from SQS")
42
+ records = self.event.get("Records", [])
14
43
  for record in records:
15
- print(f"Start MessageId {record.get('messageId')}")
16
- attrs = record.get('attributes')
44
+ attrs = record.get("attributes")
17
45
  try:
18
46
  postdata = {}
19
- if record.get('body'):
20
- postdata = json.loads(record.get('body'))
21
- if hasattr(self, 'beforeAction'):
47
+ if record.get("body"):
48
+ postdata = json.loads(record.get("body"))
49
+ if hasattr(self, "beforeAction"):
22
50
  self.beforeAction(attrs=attrs, postdata=postdata)
23
51
  actions = []
24
- action = postdata.get('action')
52
+ action = postdata.get("action")
25
53
  if action:
26
54
  actions.append(
27
- f"on action {action.replace('-', ' ').replace('_', ' ')}"
28
- .title().replace(' ', ''))
55
+ f"on action {action.replace('-', ' ').replace('_', ' ')}".title().replace(
56
+ " ", ""
57
+ )
58
+ )
29
59
  if self.serve_action_default:
30
- actions.append('OnActionDefault')
60
+ actions.append("OnActionDefault")
31
61
  for action in actions:
62
+ if self.skip_action:
63
+ return
32
64
  if hasattr(self, action):
33
65
  getattr(self, action)(attrs=attrs, postdata=postdata)
34
66
  break
35
- if hasattr(self, 'afterAction'):
67
+ if hasattr(self, "afterAction"):
36
68
  self.afterAction(attrs=attrs, postdata=postdata)
37
69
  except Exception as e:
38
- if hasattr(self, 'onError'):
39
- self.onError(attrs=attrs,
40
- postdata=postdata,
41
- exc=e,
42
- tb=traceback.format_exc())
70
+ if hasattr(self, "onError"):
71
+ self.onError(
72
+ attrs=attrs,
73
+ postdata=postdata,
74
+ exc=e.__class__.__name__,
75
+ tb=traceback.format_exc(),
76
+ )
43
77
 
44
78
  def OnActionDefault(self, tx, attrs, postdata):
45
79
  print(
46
- "Action handler not found. Calling default action `SqsHandler.OnActionDefault` with the following parameters for tx, attrs, and postdata:"
47
- )
48
- print({'tx': tx, 'attrs': attrs, 'postdata': postdata})
80
+ f"""
81
+ [Warn] Action handler not found. Calling default action `SqsHandler.OnActionDefault` with the following parameters for attrs, and postdata:
82
+ attrs: {str(attrs)}
83
+ postdata: {str(postdata)}
84
+ """
85
+ )
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.1
2
2
  Name: velocity-python
3
- Version: 0.0.6
3
+ Version: 0.0.7
4
4
  Summary: A rapid application development library for interfacing with data storage
5
5
  Author-email: Paul Perez <pperez@codeclubs.org>
6
6
  Project-URL: Homepage, https://codeclubs.org/projects/velocity
@@ -1,10 +1,10 @@
1
1
  velocity/__init__.py,sha256=zOzb6090Y-kq0sFFXB-uZl9DFpojkKMKiXgXSbh57HQ,55
2
- velocity/aws/__init__.py,sha256=9hVUbHjWh1HvD-xolBY_jLnV_bARlHyxkl5_l2nnINg,713
2
+ velocity/aws/__init__.py,sha256=Bfov3WUtS0JvxFx1jEcG_ni9n5TeqIlOifVsamaV_8w,713
3
3
  velocity/aws/context.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
4
4
  velocity/aws/handlers/__init__.py,sha256=OVqAh3Ln501EnmWUz2fq4lhokGHga6KSPA82yU4kRQs,119
5
- velocity/aws/handlers/lambda_handler.py,sha256=3mCFnFXCZReyOcNoFhj2kyXjokT8TsDb8Rc_IDasg6Q,4586
6
- velocity/aws/handlers/response.py,sha256=mO4bW595_AVuYE0r-YXD2T5kZyVyCywCg4yAQJJowUo,3988
7
- velocity/aws/handlers/sqs_handler.py,sha256=OBpmK0_ZTollITPFcQifpUfwjwNmR6Apkl0LKn2QJdk,2033
5
+ velocity/aws/handlers/lambda_handler.py,sha256=8_YgqB_zw4cu_H8kIAMw3wyp0IRLtKipZTWWrKWbXlg,6019
6
+ velocity/aws/handlers/response.py,sha256=VN4uFI_wtHiqAyBLX-eeQlmCwj1hdIvokvZLjsOyCnw,3915
7
+ velocity/aws/handlers/sqs_handler.py,sha256=VB9XMZVqUTeXxgUJswa8Hl8wYGtEKgFp3lQKJE5Icx0,3014
8
8
  velocity/db/__init__.py,sha256=vrn2AFNAKaqTdnPwLFS0OcREcCtzUCOodlmH54U7ADg,200
9
9
  velocity/db/core/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
10
10
  velocity/db/core/column.py,sha256=vB7dCrcIWFvRG1fgyzDQnEu7j_0KYxUuDSTCWVCYlPc,6153
@@ -31,8 +31,8 @@ velocity/misc/format.py,sha256=2GwdWOpUqmQjtLJKrHjQjTMFrATF6G1IXkLI1xVPB7U,2301
31
31
  velocity/misc/mail.py,sha256=fKfJtEkRKO3f_JbHNw9ThxKHJnChlBMsQwmEDFgj264,2096
32
32
  velocity/misc/merge.py,sha256=hBYPJy6lGL8lzb0wK1i1oEAyzragTWKF1rW9_PGHm6s,918
33
33
  velocity/misc/timer.py,sha256=wMbV-1yNXeCJo_UPi5sTSslu9hPzokLaIKgd98tyG_4,536
34
- velocity_python-0.0.6.dist-info/LICENSE,sha256=aoN245GG8s9oRUU89KNiGTU4_4OtnNmVi4hQeChg6rM,1076
35
- velocity_python-0.0.6.dist-info/METADATA,sha256=O5NgDrfTR3lEHRqwLihLNwQ4qcVq7iJvf0aRXloUnUo,8521
36
- velocity_python-0.0.6.dist-info/WHEEL,sha256=oiQVh_5PnQM0E3gPdiz09WCNmwiHDMaGer_elqB3coM,92
37
- velocity_python-0.0.6.dist-info/top_level.txt,sha256=JW2vJPmodgdgSz7H6yoZvnxF8S3fTMIv-YJWCT1sNW0,9
38
- velocity_python-0.0.6.dist-info/RECORD,,
34
+ velocity_python-0.0.7.dist-info/LICENSE,sha256=aoN245GG8s9oRUU89KNiGTU4_4OtnNmVi4hQeChg6rM,1076
35
+ velocity_python-0.0.7.dist-info/METADATA,sha256=yBaBcYrDdsBYj28SCNjTo_bQdc0SZ9awpIRxNX6Jzp0,8521
36
+ velocity_python-0.0.7.dist-info/WHEEL,sha256=oiQVh_5PnQM0E3gPdiz09WCNmwiHDMaGer_elqB3coM,92
37
+ velocity_python-0.0.7.dist-info/top_level.txt,sha256=JW2vJPmodgdgSz7H6yoZvnxF8S3fTMIv-YJWCT1sNW0,9
38
+ velocity_python-0.0.7.dist-info/RECORD,,