-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
147 lines (121 loc) · 4.69 KB
/
Copy pathmain.py
File metadata and controls
147 lines (121 loc) · 4.69 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
#!/usr/bin/env python3
import types
import sys
import json
import argparse
import traceback
from flask import Flask, request, jsonify
import os
def create_chapar_module():
"""
Dynamically create the chapar module with full implementation
"""
# Create a new module object
chapar_module = types.ModuleType('chapar')
chapar_module.__file__ = '<dynamic>'
chapar_module.__doc__ = """
chapar module - Interface for interacting with the Chapar application
"""
# Store environments internally
environments = {}
set_environments = {}
print_outputs = []
# Environment variable methods
def get_env(name):
value = environments.get(name)
return value
def set_env(name, value):
set_environments[name] = value
def custom_print(*args, **kwargs):
message = ' '.join(str(arg) for arg in args)
print_outputs.append(message)
# Assign methods to the module
chapar_module.get_env = get_env
chapar_module.set_env = set_env
chapar_module.custom_print = custom_print
chapar_module.on_response = None
chapar_module.print_outputs = print_outputs
chapar_module._environments = environments
chapar_module._set_environments = set_environments
# Register the module in sys.modules
sys.modules['chapar'] = chapar_module
return chapar_module
# Create the chapar module
chapar = create_chapar_module()
app = Flask(__name__)
@app.route("/health")
def health_check():
return jsonify({"status": "ok"})
@app.route("/execute", methods=["POST"])
def execute_post_response():
try:
data = request.json
script = data.get("script", "")
request_data = data.get("requestData", {})
response_data = data.get("responseData", {})
environments = data.get("environments", {})
# Update chapar module environments
chapar._environments.clear()
chapar._set_environments.clear()
chapar.print_outputs.clear()
chapar._environments.update(environments)
# Create response object
response_obj = type("ResponseObject", (), {
"status_code": response_data.get("statusCode"),
"headers": response_data.get("headers", {}),
"text": response_data.get("body", ""),
"json": lambda self=None: json.loads(response_data.get("body", "{}")),
})()
# create request object
request_obj = type("RequestObject", (), {
"method": request_data.get("method", "GET"),
"url": request_data.get("url", ""),
"headers": request_data.get("headers", {}),
"metadata": request_data.get("metadata", {}),
"params": request_data.get("params", {}),
"query": request_data.get("query", {}),
"trailers": request_data.get("trailers", {}),
"data": request_data.get("data", {}),
"json": lambda self=None: request_data.get("json", {}),
})()
# Prepare execution environment
globals_dict = {
"__builtins__": __builtins__,
"chapar": chapar, # Make chapar available in globals
"print": chapar.custom_print,
"request": request_obj,
}
locals_dict = {
"request": request_obj,
"response": response_obj,
"chapar": chapar, # Also make it available in locals
"print": chapar.custom_print
}
# Reset any callbacks
chapar.on_response = None
# Execute the script
exec(script, globals_dict, locals_dict)
# If on_response was set, call it
if chapar.on_response is not None and callable(chapar.on_response):
chapar.on_response(response_obj)
# Return the potentially modified data
return jsonify({
"environments": chapar._environments,
"set_environments": chapar._set_environments,
"prints": chapar.print_outputs,
})
except Exception as e:
return jsonify({"error": str(e), "traceback": traceback.format_exc()}), 400
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument('--port', type=int,
default=int(os.environ.get("PORT", 2397)),
help='Port to run the server on')
parser.add_argument('--host',
default=os.environ.get("HOST", "0.0.0.0"),
help='Host to run the server on')
parser.add_argument('--debug', action='store_true',
default=(os.environ.get("DEBUG", "").lower() == "true"),
help='Run in debug mode')
args = parser.parse_args()
app.run(host=args.host, port=args.port, debug=False)