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.

@@ -0,0 +1,81 @@
1
+ import decimal
2
+ import json
3
+ from datetime import datetime, date, time, timedelta
4
+
5
+
6
+ def gallons(data):
7
+ if data is None:
8
+ return ''
9
+ data = decimal.Decimal(data)
10
+ return "{:.2f}".format(data)
11
+ # return "{:1,.2f} gals".format(data)
12
+
13
+
14
+ def gallons2liters(data):
15
+ if data is None:
16
+ return ''
17
+ data = decimal.Decimal(data) * decimal.Decimal(3.78541)
18
+ return "{:.2f}".format(data)
19
+ # return "{:1,.2f} liters".format(data)
20
+
21
+
22
+ def currency(data):
23
+ if data is None:
24
+ return ''
25
+ decimal.Decimal(data)
26
+ return "{:.2f}".format(data)
27
+ # return "${:1,.2f}".format(data)
28
+
29
+
30
+ def human_delta(tdelta):
31
+ """
32
+ Takes a timedelta object and formats it for humans.
33
+ Usage:
34
+ # 149 day(s) 8 hr(s) 36 min 19 sec
35
+ print(human_delta(datetime(2014, 3, 30) - datetime.now()))
36
+ Example Results:
37
+ 23 sec
38
+ 12 min 45 sec
39
+ 1 hr(s) 11 min 2 sec
40
+ 3 day(s) 13 hr(s) 56 min 34 sec
41
+ :param tdelta: The timedelta object.
42
+ :return: The human formatted timedelta
43
+ """
44
+ d = dict(days=tdelta.days)
45
+ d['hrs'], rem = divmod(tdelta.seconds, 3600)
46
+ d['min'], d['sec'] = divmod(rem, 60)
47
+
48
+ if d['min'] == 0:
49
+ fmt = '{sec} sec'
50
+ elif d['hrs'] == 0:
51
+ fmt = '{min} min {sec} sec'
52
+ elif d['days'] == 0:
53
+ fmt = '{hrs} hr(s) {min} min {sec} sec'
54
+ else:
55
+ fmt = '{days} day(s) {hrs} hr(s) {min} min {sec} sec'
56
+
57
+ return fmt.format(**d)
58
+
59
+
60
+ def to_json(o, datefmt="%Y-%m-%d", timefmt="%H:%M:%S"):
61
+ class JsonEncoder(json.JSONEncoder):
62
+ def default(self, o):
63
+ if hasattr(o, 'to_json'):
64
+ return o.to_json()
65
+ elif o is None:
66
+ return 0
67
+ elif isinstance(o, decimal.Decimal):
68
+ return float(o)
69
+ elif isinstance(o, date):
70
+ return o.strftime(datefmt)
71
+ elif isinstance(o, datetime):
72
+ return o.strftime("{} {}".format(datefmt, timefmt))
73
+ elif isinstance(o, time):
74
+ return o.strftime(timefmt)
75
+ elif isinstance(o, timedelta):
76
+ return human_delta(o)
77
+ try:
78
+ return super(JsonEncoder, self).default(o)
79
+ except:
80
+ return str(o)
81
+ return json.dumps(o, cls=JsonEncoder)
velocity/misc/mail.py ADDED
@@ -0,0 +1,67 @@
1
+ #!/usr/local/bin/python
2
+ from email.parser import Parser as EmailParser
3
+ from io import BytesIO
4
+ import mimetypes, hashlib
5
+
6
+ class NotSupportedMailFormat(Exception):
7
+ pass
8
+
9
+ def get_full_emails(addresses):
10
+ results = []
11
+ for a in addresses:
12
+ if a.name:
13
+ results.append(f"{a.name.decode('utf-8')} <{a.mailbox.decode('utf-8')}@{a.host.decode('utf-8')}>")
14
+ else:
15
+ results.append(f"{a.mailbox.decode('utf-8')}@{a.host.decode('utf-8')}")
16
+ return results
17
+
18
+ def get_address_only(addresses):
19
+ results = []
20
+ for a in addresses:
21
+ results.append(f"{a.mailbox.decode('utf-8')}@{a.host.decode('utf-8')}")
22
+ return results
23
+
24
+ def parse_attachment(part):
25
+ content_disposition = part.get('Content-Disposition')
26
+ if content_disposition:
27
+ dispositions = content_disposition.strip().split(";")
28
+ if content_disposition and dispositions[0].lower() == "attachment":
29
+ name = part.get_filename()
30
+ if not name:
31
+ return None
32
+ data = part.get_payload(decode=True)
33
+ if not data:
34
+ return None
35
+ attachment = Object()
36
+ attachment.data = data
37
+ attachment.ctype = mimetypes.guess_type(name)[0]
38
+ attachment.size = len(data)
39
+ attachment.name = name
40
+ attachment.hash = hashlib.sha1(data).hexdigest()
41
+
42
+ return attachment
43
+
44
+ return None
45
+
46
+ def parse(content):
47
+ body = None
48
+ html = None
49
+ attachments = []
50
+ for part in EmailParser().parsestr(content).walk():
51
+ attachment = parse_attachment(part)
52
+ if attachment:
53
+ attachments.append(attachment)
54
+ elif part.get_content_type() == "text/plain":
55
+ if body is None:
56
+ body = bytes()
57
+ body += part.get_payload(decode=True)
58
+ elif part.get_content_type() == "text/html":
59
+ if html is None:
60
+ html = bytes()
61
+ html += part.get_payload(decode=True)
62
+
63
+ return {
64
+ 'body' : body,
65
+ 'html' : html,
66
+ 'attachments': attachments,
67
+ }
velocity/misc/timer.py ADDED
@@ -0,0 +1,27 @@
1
+ import time
2
+
3
+
4
+ class Timer:
5
+ def __init__(self, label='Timer'):
6
+ self._label = label
7
+ self.start()
8
+
9
+ def start(self):
10
+ self._end = self._start = time.time()
11
+ self._diff = 0
12
+
13
+ def end(self):
14
+ self._end = time.time()
15
+ self._diff = self._end - self._start
16
+
17
+ def __str__(self):
18
+ if not self._diff:
19
+ self.end()
20
+ return f"{self._label}: {self._diff:.4f} s"
21
+
22
+
23
+ if __name__ == '__main__':
24
+ t = Timer("My Label")
25
+ time.sleep(.003)
26
+ time.sleep(3)
27
+ print(t)
@@ -0,0 +1,19 @@
1
+ Copyright (c) 2000-2023 Paul Perez
2
+
3
+ Permission is hereby granted, free of charge, to any person obtaining a copy
4
+ of this software and associated documentation files (the "Software"), to deal
5
+ in the Software without restriction, including without limitation the rights
6
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
7
+ copies of the Software, and to permit persons to whom the Software is
8
+ furnished to do so, subject to the following conditions:
9
+
10
+ The above copyright notice and this permission notice shall be included in all
11
+ copies or substantial portions of the Software.
12
+
13
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
14
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
15
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
16
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
17
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
18
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
19
+ SOFTWARE.
@@ -0,0 +1,181 @@
1
+ Metadata-Version: 2.1
2
+ Name: velocity-python
3
+ Version: 0.0.1
4
+ Summary: A rapid application development library for interfacing with data storage
5
+ Author-email: Paul Perez <pperez@codeclubs.org>
6
+ Project-URL: Homepage, https://codeclubs.org/projects/velocity
7
+ Classifier: Programming Language :: Python :: 3
8
+ Classifier: License :: OSI Approved :: MIT License
9
+ Classifier: Operating System :: OS Independent
10
+ Requires-Python: >=3.7
11
+ Description-Content-Type: text/markdown
12
+ License-File: LICENSE
13
+ Requires-Dist: requests
14
+ Requires-Dist: psycopg2-binary
15
+ Requires-Dist: python-tds
16
+ Requires-Dist: mysql-connector-python
17
+ Requires-Dist: openpyxl
18
+ Requires-Dist: boto3
19
+ Requires-Dist: jinja2
20
+ Requires-Dist: xlrd
21
+
22
+ # Velocity.DB
23
+
24
+ This project's goal is to simplify database management by abstracting complex (and many times database engine specific) functions to Python methods. This project is still in its infancy and is not yet ready for production use. If you would like to contribute to this project, please feel free to fork it and submit a pull request. This documentation is severely out of date and not yet complete, but will be updated as the project progresses.
25
+
26
+ This project currently supports the following database engines:
27
+
28
+ <b>PostgreSQL</b><br/>
29
+ <b>Microsoft SQL Server</b><br/>
30
+ <b>SQLite</b><br/>
31
+ <b>MySQL</b><br/>
32
+
33
+ [The source for this project is available here][src].
34
+
35
+ <b>Prerequisites:</b><br/>
36
+ The following packages must be installed prior to using Velocity.DB:<br/>
37
+ `psycopg2` - For PostgreSQL<br/>
38
+ `pytds` - For Microsoft SQL Server<br/>
39
+ `sqlite3` - For SQLite 3<br/>
40
+ `mysqlclient` - MySQL<br/>
41
+ You will also need the MySQL Connector for your operating system before you install `mysqlclient`. You can download it <a href='https://dev.mysql.com/downloads/connector/c/'>here.</a>
42
+
43
+ <b>For Windows Users:</b><br/>
44
+ If you're using Windows, after you install the MySQL Connector you will need the Visual C++ Compiler for Python 2.7, you can download it <a href='https://www.microsoft.com/en-us/download/details.aspx?id=44266'>here.</a> After both dependencies are installed you can install `mysqlclient` without issue.
45
+
46
+ Optionally if you only want to support a single database engine or do not want to install dependencies for engines you won't be using, download the source code for velocity.db and comment out the engines you wont be using in the `python-db/velocity/db/__init_.py` file on the following lines:
47
+
48
+ <pre>
49
+ # Import for PostgreSQL Support
50
+ import servers.postgres
51
+ postgres = servers.postgres.initialize()
52
+ <br/># Import for Microsoft SQL Server Support
53
+ import servers.sqlserver
54
+ sqlserver = servers.sqlserver.initialize
55
+ <br/># Import for SQLite 3 Support
56
+ import servers.sqlite
57
+ sqlite = servers.sqlite.initialize
58
+ <br/># Import for MySQL Support
59
+ import servers.mysql
60
+ mysql = servers.mysql.initialize</pre>
61
+
62
+ If you setup your project this way, make sure to install velocity.db using: `python setup.py develop` in case you want to revert your changes.
63
+
64
+ ----
65
+
66
+ # Using Velocity.DB
67
+
68
+ <b>Warning: Not all database engines are alike, and some datatypes in certain engines will be specific to the engine. This tutorial assumes you have basic knowledge of your database engine and it's specific datatypes.</b>
69
+
70
+ To setup Velocity.DB with your server, define your server variable like so:
71
+
72
+ <b>PostgreSQL:</b>
73
+ <pre>
74
+ import velocity.db
75
+ <br/>server = velocity.db.postgres({
76
+ 'database':'db-name',
77
+ 'host': 'server',
78
+ 'user':'username',
79
+ 'password':'password',
80
+ })
81
+ </pre>
82
+ <b>Microsoft SQL Server:</b>
83
+ <pre>
84
+ import velocity.db
85
+ <br/>server = velocity.db.sqlserver({
86
+ 'database': 'db-name',
87
+ 'server': 'server',
88
+ 'user':'username',
89
+ 'password':'password',
90
+ 'use_mars': True, # To enable Multiple Active Result Sets (disabled by default)
91
+ })
92
+ </pre>
93
+ <b>SQLite:</b>
94
+ <pre>
95
+ import velocity.db
96
+ <br/>server = velocity.db.sqlserver({
97
+ 'database': 'db-name' # Use ':memory:' for an in memory database
98
+ })
99
+ </pre>
100
+ <b>MySQL:</b>
101
+ <pre>
102
+ import velocity.db
103
+ <br/>server = velocity.db.mysql({
104
+ 'db':'db-name',
105
+ 'host':'server',
106
+ 'user':'username',
107
+ 'passwd':'password',
108
+ })
109
+ </pre>
110
+ <br>
111
+ <b>Basic SQL Functions:</b><br/>
112
+ Since the SQL ANSI standard holds all SQL compliant databases to the CRUD standard (Create, Read, Update, Delete) we will cover how to accomplish all of those functions using Velocity.DB.<br/>
113
+ <br/><b>The <code>@server.transaction</code> Decorator:</b><br/>
114
+ All SQL transactions have to live in their own functions so that in case some part of the function fails, the transaction will not commit. In order to signify a method as a transaction, use the <code>@server.transaction</code> decorator. Any function using this decorator will not commit any changes to the database unless the function successfully completes without error. This also passes the argument <code>tx</code> to your method which allows you to access the transaction object within your method.<br/>
115
+ <br/><b>Creating a Table:</b>
116
+ <pre>
117
+ @server.transaction
118
+ def create_new_table(self, tx):
119
+ t = tx.table('new_table')
120
+ t.create()
121
+ </pre>
122
+ Once the function is complete the transaction will commit and you will have a new table in your database titled 'new_table'.<br>
123
+ If you would like to create a new row and add a column, you could do so using the following syntax:
124
+ <pre>
125
+ @server.transaction
126
+ def add_column(self,tx):
127
+ # We will be using the same table we made in the above method.
128
+ t = tx.table('new_table')
129
+ # Creates a new row with a primary key of 1 (sys_id by default)
130
+ r = t.row(1)
131
+ r['new_column'] = 'Value to be placed in the first row of the new column'
132
+ </pre>
133
+ <br/><b>Reading Data from a Table:</b>
134
+ <br/>Now let's say you already have a table with data named 'people', and you want to read the 'firstname' column of your table on the third row and return that field. You would accomplish this in Velocity.DB like so:
135
+ <pre>
136
+ @server.transaction
137
+ def read_third_firstname(self, tx):
138
+ t = tx.table('people')
139
+ r = t.row(3)
140
+ return r['firstname']
141
+ </pre>
142
+ The above method will return the value of the 'firstname' column in row 3 of the table. The table object is iterable so if you would like to return the values of each field in the 'firstname' column you could do so like this:
143
+ <pre>
144
+ @server.transaction
145
+ def read_all_firstnames(self,tx):
146
+ t = tx.table('people')
147
+ name_list = []
148
+ for r in t:
149
+ name_list.append(r['firstname'])
150
+ return name_list
151
+ </pre>
152
+ <b>Updating a Preexisting Table:</b><br/>
153
+ If you already have a table that you would like to update the data within, you can update data fields using the same syntax that you would use to create the field. This example will be working on a table named 'people' with columns: 'firstname' and 'lastname' with information filled out for 3 rows. Let's assume that the person on row 2 just got married and their last name has changed so we need to update it within the database.
154
+ <pre>
155
+ @server.transaction
156
+ def update_lastname(self, tx):
157
+ t = tx.table('people')
158
+ r = t.row(2)
159
+ r['lastname'] = 'Newname'
160
+ </pre>
161
+ Notice the syntax is the same as if we were creating a new column. This syntax will attempt to insert the data, and if the column doesn't exist then it will create it. It will also see if the data is already populated, and if so it will issue a UPDATE command to the database instead.<br/>
162
+ <br/><b>Deleting Data and Dropping Tables:</b><br/>
163
+ To delete data from an existing table you may want to only delete a specific row. We will use the same 'people' database, let's go ahead and delete the person that was occupying row 3.
164
+ <pre>
165
+ @server.transaction
166
+ def delete_person(self, tx):
167
+ t = tx.table('people')
168
+ r = t.row(3)
169
+ r.delete()
170
+ </pre>
171
+ It's as simple as that! But what if instead you were wanting to drop the whole table? <b>Warning: Executing the following code will drop the table from the database, if you are testing on your own database make sure you have a backup first.</b>
172
+ <pre>
173
+ @server.transaction
174
+ def drop_table(self, tx):
175
+ t = tx.table('people')
176
+ t.drop()
177
+ </pre>
178
+ Keep in mind this will use the "IF EXISTS" SQL statement so if you accidentally misspell a table name, your program will not hang and no tables will be dropped.<br/>
179
+ <br/>Congratulations, you now know how to use basic CRUD functionality with Velocity.DB. Velocity.DB has many advanced features as well, so if you'd like to see how some of those methods are used check out the <code>python-db/velocity/tests/db/unit_tests.py</code> file for examples.
180
+
181
+ [src]: https://github.com/
@@ -0,0 +1,36 @@
1
+ velocity/__init__.py,sha256=zOzb6090Y-kq0sFFXB-uZl9DFpojkKMKiXgXSbh57HQ,55
2
+ velocity/aws/__init__.py,sha256=9hVUbHjWh1HvD-xolBY_jLnV_bARlHyxkl5_l2nnINg,713
3
+ velocity/aws/context.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
4
+ velocity/aws/handlers/__init__.py,sha256=OVqAh3Ln501EnmWUz2fq4lhokGHga6KSPA82yU4kRQs,119
5
+ velocity/aws/handlers/lambda_handler.py,sha256=3mCFnFXCZReyOcNoFhj2kyXjokT8TsDb8Rc_IDasg6Q,4586
6
+ velocity/aws/handlers/sqs_handler.py,sha256=OBpmK0_ZTollITPFcQifpUfwjwNmR6Apkl0LKn2QJdk,2033
7
+ velocity/db/__init__.py,sha256=vrn2AFNAKaqTdnPwLFS0OcREcCtzUCOodlmH54U7ADg,200
8
+ velocity/db/core/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
9
+ velocity/db/core/column.py,sha256=vB7dCrcIWFvRG1fgyzDQnEu7j_0KYxUuDSTCWVCYlPc,6153
10
+ velocity/db/core/database.py,sha256=i1hzCkte6onEInH8ZtTI7D2Xj8q3uwU-uL3wn7Ix5oU,1860
11
+ velocity/db/core/decorators.py,sha256=Y-ottCY3rJC2qWpDHQufU5khX-WkDba7_GfX2lon3Ss,2978
12
+ velocity/db/core/engine.py,sha256=94wVlnapVVmJCRp6NPGrwnqSxCDlC-848Vu42p9RtCs,14643
13
+ velocity/db/core/exceptions.py,sha256=3ZyRq-idtCdtOGyT4rbNsmEyjfP75BMBq9y-Phakxow,684
14
+ velocity/db/core/result.py,sha256=I8-gdHK5Qb4gD0CpAePVjW_zFK4lGXM2XiOwZp7NmPQ,3776
15
+ velocity/db/core/row.py,sha256=n_IliA3fS9Sp_LoT1br3gV4rpPJW2JQGxT7_iUCzjDY,5133
16
+ velocity/db/core/sequence.py,sha256=6sUaHJ29ItthNYoAvQy0SMAZURRdDS8bomnmQspJaT4,1083
17
+ velocity/db/core/table.py,sha256=PkyZvSfjSWnI2qv2wYFWSSMdQ-b-GuxUQDkrdljmYnc,17128
18
+ velocity/db/core/transaction.py,sha256=9MrclVnT5-_XAU_QxiqlcPttqyskLQ-6zNGwmvWaPGw,5849
19
+ velocity/db/servers/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
20
+ velocity/db/servers/mysql.py,sha256=c0yUG00jvgnhLMJcV8BuOlTL7uGJ3uRPjJ0xVJingbk,21975
21
+ velocity/db/servers/postgres.py,sha256=H8WUrho-JC1X9M7zuUrEtOB3C5Yr9GnWCjPWrE9QDxQ,39672
22
+ velocity/db/servers/sql.py,sha256=8yxljVYjMMY4weLCrugpLb7R3FEriHqamR-8lFaNfZg,21856
23
+ velocity/db/servers/sqlite.py,sha256=QVdr_ytvCuSSKVgcP_PI05yTU0gNyFRtTmH4XQlQVjQ,34047
24
+ velocity/db/servers/sqlserver.py,sha256=5kRNLNKbaszMww8JrlUvs2viSIb2hDZfn6nSvR52MEU,31593
25
+ velocity/misc/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
26
+ velocity/misc/conv.py,sha256=wpSz1VZFYCbwEu1yz7Rrj03EkD5YdRVxiK3VceB-XKc,10588
27
+ velocity/misc/db.py,sha256=ZbAlVjSC-ASfVV69zlLjUqwndQnsUTBBjORyIBNrMUo,2842
28
+ velocity/misc/export.py,sha256=KA_ezon-jd874rHIDMeZSOWTCAuLcA7kayjWZVTewew,4863
29
+ velocity/misc/format.py,sha256=2GwdWOpUqmQjtLJKrHjQjTMFrATF6G1IXkLI1xVPB7U,2301
30
+ velocity/misc/mail.py,sha256=fKfJtEkRKO3f_JbHNw9ThxKHJnChlBMsQwmEDFgj264,2096
31
+ velocity/misc/timer.py,sha256=wMbV-1yNXeCJo_UPi5sTSslu9hPzokLaIKgd98tyG_4,536
32
+ velocity_python-0.0.1.dist-info/LICENSE,sha256=aoN245GG8s9oRUU89KNiGTU4_4OtnNmVi4hQeChg6rM,1076
33
+ velocity_python-0.0.1.dist-info/METADATA,sha256=g6_2mjjI4d63ugyJCH4eVVlpTUbJb2NQ4x10A5eWyy4,8405
34
+ velocity_python-0.0.1.dist-info/WHEEL,sha256=oiQVh_5PnQM0E3gPdiz09WCNmwiHDMaGer_elqB3coM,92
35
+ velocity_python-0.0.1.dist-info/top_level.txt,sha256=JW2vJPmodgdgSz7H6yoZvnxF8S3fTMIv-YJWCT1sNW0,9
36
+ velocity_python-0.0.1.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: bdist_wheel (0.42.0)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1 @@
1
+ velocity