velocity-python 0.0.1__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/__init__.py ADDED
@@ -0,0 +1,3 @@
1
+ from . import aws
2
+ from . import db
3
+ from . import misc
@@ -0,0 +1,24 @@
1
+ import os
2
+ import requests
3
+
4
+ from velocity.aws.handlers import LambdaHandler
5
+ from velocity.aws.handlers import SqsHandler
6
+
7
+ DEBUG = (os.environ.get('ENV') != 'production') \
8
+ or (os.environ.get('DEBUG') == 'Y')
9
+
10
+ # This is helpful for running HTTPS clients on lambda.
11
+ if os.path.exists('/opt/python/ca-certificates.crt'):
12
+ os.environ["REQUESTS_CA_BUNDLE"] = '/opt/python/ca-certificates.crt'
13
+
14
+
15
+ class AWS(object):
16
+ # Get AWS EC2 Instance ID. Must run this from the EC2 instance itself to get the ID
17
+ @staticmethod
18
+ def instance_id(cls):
19
+ response = requests.get(
20
+ 'http://169.254.169.254/latest/meta-data/instance-id')
21
+ instance_id = response.text
22
+ return instance_id
23
+
24
+
File without changes
@@ -0,0 +1,2 @@
1
+ from velocity.aws.handlers.lambda_handler import LambdaHandler
2
+ from velocity.aws.handlers.sqs_handler import SqsHandler
@@ -0,0 +1,123 @@
1
+ from velocity.misc.format import to_json
2
+ import json
3
+ import pprint
4
+ import traceback
5
+
6
+ class LambdaHandler:
7
+ def __init__(self, event, context):
8
+ self.event = event
9
+ self.context = context
10
+ self.serve_action_default = True
11
+
12
+ requestContext = event.get('requestContext', {})
13
+ identity = requestContext.get('identity', {})
14
+ headers = event.get('headers', {})
15
+ 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'),
40
+ }
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'
49
+ else:
50
+ self.session['device_type'] = 'unknown'
51
+
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
+ },
60
+ }
61
+ 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)
70
+ actions = []
71
+ action = postdata.get('action', req_params.get('action'))
72
+ if action:
73
+ actions.append(
74
+ f"on action {action.replace('-', ' ').replace('_', ' ')}".
75
+ title().replace(' ', ''))
76
+ if self.serve_action_default:
77
+ actions.append('OnActionDefault')
78
+ for action in actions:
79
+ if hasattr(self, action):
80
+ getattr(self, action)(args=req_params,
81
+ postdata=postdata,
82
+ response=response)
83
+ break
84
+ if hasattr(self, 'afterAction'):
85
+ self.afterAction(args=req_params,
86
+ postdata=postdata,
87
+ response=response)
88
+
89
+ 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())
111
+
112
+ return response
113
+
114
+ def OnActionDefault(self, tx, args, postdata, response):
115
+ response['body'] = to_json({'event': self.event, 'postdata': postdata})
116
+
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
+ })
123
+
@@ -0,0 +1,48 @@
1
+ from velocity.misc.format import to_json
2
+ import json
3
+ import traceback
4
+
5
+ class SqsHandler:
6
+ def __init__(self, event, context):
7
+ self.event = event
8
+ self.context = context
9
+ self.serve_action_default = True
10
+
11
+ def serve(self, tx):
12
+ records = self.event.get('Records', [])
13
+ print(f"Handling batch of {len(records)} records from SQS")
14
+ for record in records:
15
+ print(f"Start MessageId {record.get('messageId')}")
16
+ attrs = record.get('attributes')
17
+ try:
18
+ postdata = {}
19
+ if record.get('body'):
20
+ postdata = json.loads(record.get('body'))
21
+ if hasattr(self, 'beforeAction'):
22
+ self.beforeAction(attrs=attrs, postdata=postdata)
23
+ actions = []
24
+ action = postdata.get('action')
25
+ if action:
26
+ actions.append(
27
+ f"on action {action.replace('-', ' ').replace('_', ' ')}"
28
+ .title().replace(' ', ''))
29
+ if self.serve_action_default:
30
+ actions.append('OnActionDefault')
31
+ for action in actions:
32
+ if hasattr(self, action):
33
+ getattr(self, action)(attrs=attrs, postdata=postdata)
34
+ break
35
+ if hasattr(self, 'afterAction'):
36
+ self.afterAction(attrs=attrs, postdata=postdata)
37
+ 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())
43
+
44
+ def OnActionDefault(self, tx, attrs, postdata):
45
+ 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})
@@ -0,0 +1,5 @@
1
+ from velocity.db.core import exceptions
2
+ from velocity.db.servers import postgres
3
+ from velocity.db.servers import mysql
4
+ from velocity.db.servers import sqlite
5
+ from velocity.db.servers import sqlserver
File without changes
@@ -0,0 +1,202 @@
1
+ from velocity.db import exceptions
2
+ from velocity.db.core.decorators import return_default
3
+
4
+ class Column(object):
5
+ """
6
+ Represents a column in a database table.
7
+ """
8
+ def __init__(self, table, name):
9
+ """
10
+ Initializes a column object with the specified table and name.
11
+
12
+ Args:
13
+ table (table): The table object that the column belongs to.
14
+ name (str): The name of the column.
15
+
16
+ Raises:
17
+ Exception: If the table parameter is not of type 'table'.
18
+ """
19
+ if isinstance(table,str):
20
+ raise Exception("column table parameter must be a `table` class.")
21
+ self.tx = table.tx
22
+ self.sql = table.tx.engine.sql
23
+ self.name = name
24
+ self.table = table
25
+
26
+ def __str__(self):
27
+ """
28
+ Returns a string representation of the column object.
29
+
30
+ Returns:
31
+ str: A string representation of the column object.
32
+ """
33
+ return """
34
+ Table: %s
35
+ Column: %s
36
+ Column Exists: %s
37
+ Py Type: %s
38
+ SQL Type: %s
39
+ NULL OK: %s
40
+ Foreign Key: %s
41
+ """ % (
42
+ self.table.name,
43
+ self.name,
44
+ self.exists(),
45
+ self.py_type,
46
+ self.sql_type,
47
+ self.is_nullok,
48
+ self.foreign_key_to
49
+ )
50
+
51
+ @property
52
+ def info(self):
53
+ """
54
+ Retrieves information about the column from the database.
55
+
56
+ Returns:
57
+ dict: A dictionary containing information about the column.
58
+
59
+ Raises:
60
+ DbColumnMissingError: If the column does not exist in the database.
61
+ """
62
+ sql, vals = self.sql.column_info(self.table.name, self.name)
63
+ result = self.tx.execute(sql, vals).one()
64
+ if not result:
65
+ raise exceptions.DbColumnMissingError
66
+ return result
67
+
68
+ @property
69
+ def foreign_key_info(self):
70
+ """
71
+ Retrieves information about the foreign key constraint on the column.
72
+
73
+ Returns:
74
+ dict: A dictionary containing information about the foreign key constraint.
75
+
76
+ Raises:
77
+ DbColumnMissingError: If the column does not exist in the database.
78
+ """
79
+ sql, vals = self.sql.foreign_key_info(table=self.table.name, column=self.name)
80
+ result = self.tx.execute(sql, vals).one()
81
+ if not result:
82
+ raise exceptions.DbColumnMissingError
83
+ return result
84
+
85
+ @property
86
+ def foreign_key_to(self):
87
+ """
88
+ Retrieves the name of the referenced table and column for the foreign key constraint.
89
+
90
+ Returns:
91
+ str: The name of the referenced table and column in the format 'referenced_table_name.referenced_column_name'.
92
+
93
+ Raises:
94
+ DbColumnMissingError: If the column does not exist in the database.
95
+ """
96
+ try:
97
+ return "{referenced_table_name}.{referenced_column_name}".format(**self.foreign_key_info)
98
+ except exceptions.DbColumnMissingError:
99
+ return None
100
+
101
+ @property
102
+ def foreign_key_table(self):
103
+ """
104
+ Retrieves the name of the referenced table for the foreign key constraint.
105
+
106
+ Returns:
107
+ str: The name of the referenced table.
108
+
109
+ Raises:
110
+ DbColumnMissingError: If the column does not exist in the database.
111
+ """
112
+ try:
113
+ return self.foreign_key_info['referenced_table_name']
114
+ except exceptions.DbColumnMissingError:
115
+ return None
116
+
117
+ def exists(self):
118
+ """
119
+ Checks if the column exists in the table.
120
+
121
+ Returns:
122
+ bool: True if the column exists, False otherwise.
123
+ """
124
+ return self.name in self.table.columns
125
+
126
+ @property
127
+ def py_type(self):
128
+ """
129
+ Retrieves the Python data type of the column.
130
+
131
+ Returns:
132
+ type: The Python data type of the column.
133
+ """
134
+ return self.sql.py_type(self.sql_type)
135
+
136
+ @property
137
+ def sql_type(self):
138
+ """
139
+ Retrieves the SQL data type of the column.
140
+
141
+ Returns:
142
+ str: The SQL data type of the column.
143
+ """
144
+ return self.info[self.sql.type_column_identifier]
145
+
146
+ @property
147
+ def is_nullable(self):
148
+ """
149
+ Checks if the column is nullable.
150
+
151
+ Returns:
152
+ bool: True if the column is nullable, False otherwise.
153
+ """
154
+ return self.info[self.sql.is_nullable]
155
+
156
+ is_nullok = is_nullable
157
+
158
+ def rename(self, name):
159
+ """
160
+ Renames the column.
161
+
162
+ Args:
163
+ name (str): The new name for the column.
164
+ """
165
+ sql, vals = self.sql.rename_column(self.table.name, self.name, name)
166
+ self.tx.execute(sql, vals)
167
+ self.name = name
168
+
169
+ @return_default([])
170
+ def distinct(self, order='asc', qty=None):
171
+ """
172
+ Retrieves distinct values from the column.
173
+
174
+ Args:
175
+ order (str, optional): The order in which the values should be sorted. Defaults to 'asc'.
176
+ qty (int, optional): The maximum number of distinct values to retrieve. Defaults to None.
177
+
178
+ Returns:
179
+ list: A list of distinct values from the column.
180
+ """
181
+ sql, vals = self.sql.select(columns="distinct {}".format(self.name), table=self.table.name, orderby="{} {}".format(self.name,order), qty=qty)
182
+ return self.tx.execute(sql, vals).as_simple_list().all()
183
+
184
+ def max(self, where=None):
185
+ """
186
+ Retrieves the maximum value from the column.
187
+
188
+ Args:
189
+ where (str, optional): The WHERE clause to filter the rows. Defaults to None.
190
+
191
+ Returns:
192
+ int: The maximum value from the column.
193
+
194
+ Raises:
195
+ DbTableMissingError: If the table does not exist in the database.
196
+ DbColumnMissingError: If the column does not exist in the database.
197
+ """
198
+ try:
199
+ sql, vals = self.sql.select(columns="max({})".format(self.name), table=self.table.name, where=where)
200
+ return self.tx.execute(sql, vals).scalar()
201
+ except (exceptions.DbTableMissingError,exceptions.DbColumnMissingError):
202
+ return 0
@@ -0,0 +1,65 @@
1
+ class Database(object):
2
+
3
+ def __init__(self, tx, name=None):
4
+ self.tx = tx
5
+ self.name = name or self.tx.engine.config['database']
6
+ self.sql = tx.engine.sql
7
+
8
+ def __str__(self):
9
+ return """
10
+ Engine: %s
11
+ Database: %s
12
+ (db exists) %s
13
+ Tables: %s
14
+ """ % (
15
+ self.tx.engine.sql.server,
16
+ self.name,
17
+ self.exists(),
18
+ len(self.tables)
19
+ )
20
+
21
+ def __enter__(self):
22
+ return self
23
+
24
+ def __exit__(self, exc_type, exc_val, exc_tb):
25
+ if not exc_type:
26
+ self.close()
27
+
28
+ def close(self):
29
+ try:
30
+ self._cursor.close()
31
+ #print("*** database('{}').cursor.close()".format(self.name))
32
+ except AttributeError:
33
+ pass
34
+
35
+ @property
36
+ def cursor(self):
37
+ try:
38
+ return self._cursor
39
+ except AttributeError:
40
+ #print("*** database('{}').cursor.open()".format(self.name))
41
+ self._cursor = self.tx.cursor()
42
+ return self._cursor
43
+
44
+ def drop(self):
45
+ sql, vals = self.engine.sql.drop_database(self.name)
46
+ self.tx.execute(sql, vals, single=True, cursor=self.cursor)
47
+
48
+ def create(self):
49
+ sql, vals = self.engine.sql.create_database(self.name)
50
+ self.tx.execute(sql, vals, single=True, cursor=self.cursor)
51
+
52
+ def exists(self):
53
+ sql, vals = self.sql.databases()
54
+ result = self.tx.execute(sql, vals, cursor=self.cursor)
55
+ return bool(self.name in [x[0] for x in result.as_tuple()])
56
+
57
+ @property
58
+ def tables(self):
59
+ sql, vals = self.sql.tables()
60
+ result = self.tx.execute(sql ,vals, cursor=self.cursor)
61
+ return ["%s.%s" % x for x in result.as_tuple()]
62
+
63
+ def reindex(self):
64
+ sql, vals = "REINDEX DATABASE {}".format(self.name), tuple()
65
+ self.tx.execute(sql, vals, cursor=self.cursor)
@@ -0,0 +1,81 @@
1
+ from functools import wraps
2
+ from velocity.db import exceptions
3
+
4
+ def retry_on_dup_key(function):
5
+ @wraps(function)
6
+ def retry_decorator(self, *args, **kwds):
7
+ if hasattr(self, 'cursor'):
8
+ cursor = self.cursor
9
+ elif hasattr(self, 'table'):
10
+ cursor = self.table.cursor
11
+ sp = self.tx.create_savepoint(cursor=cursor)
12
+ while True:
13
+ try:
14
+ return function(self, *args, **kwds)
15
+ except exceptions.DbDuplicateKeyError:
16
+ self.tx.rollback_savepoint(sp, cursor=cursor)
17
+ continue
18
+ return retry_decorator
19
+
20
+ def return_default(default=None):
21
+ def decorator(function):
22
+ function.default = default
23
+ @wraps(function)
24
+ def return_default(self, *args, **kwds):
25
+ if hasattr(self, 'cursor'):
26
+ cursor = self.cursor
27
+ elif hasattr(self, 'table'):
28
+ cursor = self.table.cursor
29
+ sp = self.tx.create_savepoint(cursor=cursor)
30
+ try:
31
+ result = function(self, *args, **kwds)
32
+ except (exceptions.DbApplicationError,
33
+ exceptions.DbTableMissingError,
34
+ exceptions.DbColumnMissingError,
35
+ exceptions.DbTruncationError,
36
+ StopIteration,
37
+ exceptions.DbObjectExistsError):
38
+ self.tx.rollback_savepoint(sp, cursor=cursor)
39
+ return function.default
40
+ self.tx.release_savepoint(sp, cursor=cursor)
41
+ return result
42
+ return return_default
43
+ return decorator
44
+
45
+
46
+ def create_missing(function):
47
+ @wraps(function)
48
+ def create_missing_decorator(self, *args, **kwds):
49
+ if hasattr(self, 'cursor'):
50
+ cursor = self.cursor
51
+ elif hasattr(self, 'table'):
52
+ cursor = self.table.cursor
53
+ sp = self.tx.create_savepoint(cursor=cursor)
54
+ try:
55
+ result = function(self, *args, **kwds)
56
+ self.tx.release_savepoint(sp, cursor=cursor)
57
+ except exceptions.DbColumnMissingError:
58
+ self.tx.rollback_savepoint(sp, cursor=cursor)
59
+ data = {}
60
+ if 'pk' in kwds:
61
+ data.update(kwds['pk'])
62
+ if 'data' in kwds:
63
+ data.update(kwds['data'])
64
+ for i in range(len(args)):
65
+ if args[i]:
66
+ data.update(args[i])
67
+ self.alter(data)
68
+ result = function(self, *args, **kwds)
69
+ except exceptions.DbTableMissingError:
70
+ self.tx.rollback_savepoint(sp, cursor=cursor)
71
+ data = {}
72
+ if 'pk' in kwds:
73
+ data.update(kwds['pk'])
74
+ if 'data' in kwds:
75
+ data.update(kwds['data'])
76
+ for i in range(len(args)):
77
+ data.update(args[i])
78
+ self.create(data)
79
+ result = function(self, *args, **kwds)
80
+ return result
81
+ return create_missing_decorator