fivetran-api-playground 0.9.27.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 fivetran-api-playground might be problematic. Click here for more details.

@@ -0,0 +1,141 @@
1
+ import uuid
2
+ import argparse
3
+ from flask import Flask, jsonify, request, Response
4
+ from faker import Faker
5
+ from datetime import datetime, timedelta
6
+ import random
7
+ from collections import OrderedDict
8
+ import json
9
+
10
+ __version__ = "0.9.27.1"
11
+ VALID_COMMANDS = ["start"]
12
+
13
+ app = Flask(__name__)
14
+ fake = Faker()
15
+
16
+ # Sample data
17
+ items = []
18
+ MAX_RECORDS = 50
19
+ for index in range(MAX_RECORDS):
20
+ record_creation_time = datetime.now() - timedelta(hours=MAX_RECORDS - index, minutes=random.randint(0, 59),
21
+ seconds=random.randint(0, 59))
22
+ user = OrderedDict([
23
+ ('id', str(uuid.uuid4())),
24
+ ('name', fake.name()),
25
+ ('email', fake.email()),
26
+ ('address', fake.address()),
27
+ ('company', fake.company()),
28
+ ('job', fake.job()),
29
+ ('createdAt', record_creation_time.strftime(
30
+ '%Y-%m-%dT%H:%M:%SZ')),
31
+ ('updatedAt',
32
+ (record_creation_time + timedelta(minutes=random.randint(0, 59), seconds=random.randint(0, 59))).strftime(
33
+ '%Y-%m-%dT%H:%M:%SZ'))
34
+ ])
35
+ items.append(user)
36
+
37
+ DEFAULT_ORDER_BY = 'updatedAt'
38
+ DEFAULT_ORDER_TYPE = 'asc'
39
+ DEFAULT_PAGE_SIZE = 10
40
+
41
+
42
+ # Custom JSON encoder to preserve order
43
+ class CustomJSONEncoder(json.JSONEncoder):
44
+ def encode(self, obj):
45
+ if isinstance(obj, OrderedDict):
46
+ return json.dumps(obj, indent=4, separators=(',', ': '))
47
+ return super().encode(obj)
48
+
49
+
50
+ @app.route('/pagination/next_page_url', methods=['GET'])
51
+ def get_items():
52
+ # Get filters from query parameters
53
+ order_by_arg = request.args.get('order_by', type=str,
54
+ default=DEFAULT_ORDER_BY) # createdAt, updatedAt [Default updatedAt]
55
+ order_type_arg = request.args.get('order_type', type=str, default=DEFAULT_ORDER_TYPE) # asc, desc [Default asc]
56
+ per_page_arg = request.args.get('per_page', type=int, default=DEFAULT_PAGE_SIZE) # [1-50] Default 10
57
+ updated_since_arg = request.args.get('updated_since', type=str)
58
+
59
+ # Validate `order_by` value
60
+ if order_by_arg not in ['createdAt', 'updatedAt']:
61
+ return jsonify({"error": "Invalid value for 'order_by'. Use 'createdAt' or 'updatedAt'"}), 400
62
+
63
+ # Validate `order_type` value
64
+ if order_type_arg not in ['asc', 'desc']:
65
+ return jsonify({"error": "Invalid value for 'order_type'. Use 'asc' or 'desc'"}), 400
66
+
67
+ # Validate `per_page` value
68
+ if not (1 <= per_page_arg <= 50):
69
+ return jsonify({"error": "Invalid value for 'per_page'. It should be between 1 and 50."}), 400
70
+
71
+ # Filter items based on the updated_since parameter
72
+ filtered_items = items
73
+ if updated_since_arg:
74
+ try:
75
+ # Ensure the format ends with 'Z' indicating UTC
76
+ if updated_since_arg.endswith('Z'):
77
+ updated_since_arg = updated_since_arg[:-1] # Strip the 'Z' before parsing
78
+ updated_since_date = datetime.strptime(updated_since_arg, "%Y-%m-%dT%H:%M:%S")
79
+ updated_since_date = updated_since_date.replace(tzinfo=None) # Set the timezone to UTC
80
+ else:
81
+ return jsonify({"error": "Invalid date format for 'updated_since'. Must end with 'Z' for UTC"}), 400
82
+
83
+ # Convert 'updatedAt' to datetime for comparison
84
+ filtered_items = [item for item in items if
85
+ datetime.strptime(item['updatedAt'][:-1], "%Y-%m-%dT%H:%M:%S") >= updated_since_date]
86
+ except ValueError:
87
+ return jsonify({"error": "Invalid date format for 'updated_since'. Use 'YYYY-MM-DDTHH:MM:SSZ'"}), 400
88
+
89
+ # Sort the filtered items
90
+ reverse_order = (order_type_arg == 'desc')
91
+ filtered_items.sort(key=lambda x: x[order_by_arg], reverse=reverse_order)
92
+
93
+ # Pagination logic
94
+ page = request.args.get('page', default=1, type=int)
95
+ start_index = (page - 1) * per_page_arg
96
+ end_index = start_index + per_page_arg
97
+ paginated_items = filtered_items[start_index:end_index]
98
+
99
+ # Next page logic
100
+ next_page_url = None
101
+ if end_index < len(filtered_items):
102
+ next_page_url = f"{request.base_url}?page={page + 1}&per_page={per_page_arg}&order_by={order_by_arg}&order_type={order_type_arg}"
103
+ if updated_since_arg:
104
+ next_page_url += f"&updated_since={updated_since_arg}Z" # Add 'Z' back for the next page
105
+
106
+ response = {
107
+ 'data': paginated_items,
108
+ 'total_items': len(filtered_items),
109
+ 'page': page,
110
+ 'per_page': per_page_arg,
111
+ 'next_page_url': next_page_url
112
+ }
113
+
114
+ return Response(json.dumps(response, cls=CustomJSONEncoder), mimetype='application/json')
115
+
116
+
117
+ def main():
118
+ """The main entry point for the script.
119
+ Parses command line arguments and passes them to connector object methods
120
+ """
121
+
122
+ parser = argparse.ArgumentParser(allow_abbrev=False)
123
+
124
+ parser.add_argument("command", help="|".join(VALID_COMMANDS))
125
+ parser.add_argument("--port", type=int, default=None, help="Provide the port on which you want to run the API on "
126
+ "localhost")
127
+ args = parser.parse_args()
128
+ port = args.port if args.port else 5001
129
+
130
+ if args.command.lower() == "start":
131
+ print("Start Local API on port " + str(port) + "\n")
132
+ print("You can read the API documentation on: "
133
+ "https://gist.github.com/varundhall/7dfcfecf85fa35db4fa8bb58f5e7fbbb")
134
+ app.run(debug=True, port=port)
135
+
136
+ else:
137
+ raise NotImplementedError(f"Invalid command: {args.command}, see `api_playground --help`")
138
+
139
+
140
+ if __name__ == "__main__":
141
+ main()
@@ -0,0 +1,15 @@
1
+ Metadata-Version: 2.1
2
+ Name: fivetran_api_playground
3
+ Version: 0.9.27.1
4
+ Summary: Fivetran API Examples to build custom connectors
5
+ Author-email: Fivetran <developers@fivetran.com>
6
+ Project-URL: Homepage, https://fivetran.com/
7
+ Project-URL: Github, https://github.com/fivetran
8
+ Classifier: Programming Language :: Python :: 3
9
+ Classifier: License :: OSI Approved :: MIT License
10
+ Classifier: Operating System :: OS Independent
11
+ Requires-Python: >=3.9
12
+ Description-Content-Type: text/markdown
13
+ Requires-Dist: flask ==3.0.3
14
+ Requires-Dist: faker ==30.0.0
15
+
@@ -0,0 +1,6 @@
1
+ fivetran_api_playground/__init__.py,sha256=rfTo9m1_UOXrZkxH7gEb1AA5C-8qpULuxjinb-7yd6Y,5577
2
+ fivetran_api_playground-0.9.27.1.dist-info/METADATA,sha256=f078ur_yGPKpq1HlpxYoAlwF6-emvUsfxln4BIgMJFY,540
3
+ fivetran_api_playground-0.9.27.1.dist-info/WHEEL,sha256=GV9aMThwP_4oNCtvEC2ec3qUYutgWeAzklro_0m4WJQ,91
4
+ fivetran_api_playground-0.9.27.1.dist-info/entry_points.txt,sha256=XgpeXG2dUc-VcI57hqm5KdL7YO0Z_dF3Mz29clxfQA0,64
5
+ fivetran_api_playground-0.9.27.1.dist-info/top_level.txt,sha256=psKJiejSmFTujJwFm0HPEQELMG8Mly5dh3yPU4-OKig,24
6
+ fivetran_api_playground-0.9.27.1.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (75.1.0)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ api_playground = fivetran_api_playground:main
@@ -0,0 +1 @@
1
+ fivetran_api_playground