Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit 5fbff47

Browse files
better errors for sdk bugs
1 parent eedd2ca commit 5fbff47

File tree

1 file changed

+97
-83
lines changed

1 file changed

+97
-83
lines changed

src/bevyframe/run.py

Lines changed: 97 additions & 83 deletions
Original file line numberDiff line numberDiff line change
@@ -13,73 +13,80 @@
1313

1414

1515
def run() -> int:
16-
file_path = sys.argv[1]
17-
sys.path += [os.getcwd()]
18-
req_headers = {}
19-
req_body = b''
20-
21-
in_headers = True
22-
for line in sys.stdin.buffer.readlines():
23-
if in_headers:
24-
if line.strip() == b'':
25-
in_headers = False
16+
try:
17+
file_path = sys.argv[1]
18+
sys.path += [os.getcwd()]
19+
req_headers = {}
20+
req_body = b''
21+
22+
in_headers = True
23+
for line in sys.stdin.buffer.readlines():
24+
if in_headers:
25+
if line.strip() == b'':
26+
in_headers = False
27+
else:
28+
parts = line.decode().split(':', 1)
29+
req_headers.update({parts[0]: str(parts[1]).removesuffix('\n').removeprefix(' ')})
2630
else:
27-
parts = line.decode().split(':', 1)
28-
req_headers.update({parts[0]: str(parts[1]).removesuffix('\n').removeprefix(' ')})
29-
else:
30-
req_body += line
31-
32-
resp_body = []
33-
status_code = ''
34-
resp_headers = []
35-
http_headers = {}
36-
http_query = {}
37-
environ = {
38-
'REQUEST_METHOD': req_headers.get('Method', 'GET'),
39-
'PATH_INFO': req_headers.get('Path', '/'),
40-
'REMOTE_ADDR': req_headers.get('IP', '127.0.0.1'),
41-
'QUERY_STRING': '',
42-
'wsgi.input': io.BytesIO(req_body),
43-
'wsgi.url_scheme': 'https'
44-
}
45-
46-
for i in req_headers:
47-
if i.startswith('Header.'):
48-
environ.update({"HTTP_" + i.removeprefix('Header.').upper(): req_headers[i]})
49-
http_headers.update({i.removeprefix('Header.'): req_headers[i]})
50-
elif i.startswith('Query.'):
51-
http_query.update({i.removeprefix('Query.'): req_headers[i]})
52-
53-
def start_response(status: str, _headers: list[tuple[str, str]]) -> callable:
54-
nonlocal status_code, resp_headers
55-
status_code = status.split(' ', 1)[0]
56-
resp_headers = _headers
57-
return resp_body.append
58-
59-
permissions = req_headers.get('Permissions', '').split(',')
60-
if not any(permissions):
61-
permissions = []
62-
r = Context({
63-
'method': req_headers.get('Method', 'GET'),
64-
'path': req_headers.get('Path', '/'),
65-
'protocol': 'bevyframe',
66-
'headers': http_headers,
67-
'body': req_body,
68-
'credentials': {
69-
'email': req_headers['Cred.Email'],
70-
'token': req_headers['Cred.Token'],
71-
'username': req_headers['Cred.Username'],
72-
'network': req_headers['Cred.Network'],
73-
},
74-
'query': http_query,
75-
'ip': req_headers.get('IP', '127.0.0.1'),
76-
'permissions': permissions,
77-
'package': req_headers.get('Package'),
78-
'loginview': req_headers.get('LoginView'),
79-
})
80-
81-
resp = None
31+
req_body += line
32+
33+
resp_body = []
34+
status_code = ''
35+
resp_headers = []
36+
http_headers = {}
37+
http_query = {}
38+
environ = {
39+
'REQUEST_METHOD': req_headers.get('Method', 'GET'),
40+
'PATH_INFO': req_headers.get('Path', '/'),
41+
'REMOTE_ADDR': req_headers.get('IP', '127.0.0.1'),
42+
'QUERY_STRING': '',
43+
'wsgi.input': io.BytesIO(req_body),
44+
'wsgi.url_scheme': 'https'
45+
}
8246

47+
for i in req_headers:
48+
if i.startswith('Header.'):
49+
environ.update({"HTTP_" + i.removeprefix('Header.').upper(): req_headers[i]})
50+
http_headers.update({i.removeprefix('Header.'): req_headers[i]})
51+
elif i.startswith('Query.'):
52+
http_query.update({i.removeprefix('Query.'): req_headers[i]})
53+
54+
def start_response(status: str, _headers: list[tuple[str, str]]) -> callable:
55+
nonlocal status_code, resp_headers
56+
status_code = status.split(' ', 1)[0]
57+
resp_headers = _headers
58+
return resp_body.append
59+
60+
permissions = req_headers.get('Permissions', '').split(',')
61+
if not any(permissions):
62+
permissions = []
63+
r = Context({
64+
'method': req_headers.get('Method', 'GET'),
65+
'path': req_headers.get('Path', '/'),
66+
'protocol': 'bevyframe',
67+
'headers': http_headers,
68+
'body': req_body,
69+
'credentials': {
70+
'email': req_headers['Cred.Email'],
71+
'token': req_headers['Cred.Token'],
72+
'username': req_headers['Cred.Username'],
73+
'network': req_headers['Cred.Network'],
74+
},
75+
'query': http_query,
76+
'ip': req_headers.get('IP', '127.0.0.1'),
77+
'permissions': permissions,
78+
'package': req_headers.get('Package'),
79+
'loginview': req_headers.get('LoginView'),
80+
})
81+
82+
resp = None
83+
except Exception as e:
84+
print("BevyFrame 500")
85+
print(f"Content-Type: text/plain\n")
86+
print(f"SDK Error: {e}")
87+
return 0
88+
89+
# noinspection PyBroadException
8390
try:
8491
page_script_spec = importlib.util.spec_from_file_location(
8592
os.path.splitext(os.path.basename(file_path))[0],
@@ -143,24 +150,31 @@ def start_response(status: str, _headers: list[tuple[str, str]]) -> callable:
143150
except:
144151
resp = error_handler(r, 500, traceback.format_exc())
145152

146-
if resp:
147-
if isinstance(resp, Page):
148-
resp = r.create_response(resp, headers={'Content-Type': 'application/bevyframe'})
149-
if not isinstance(resp, Response):
150-
resp = r.create_response(resp)
151-
152-
if isinstance(resp.body, str) or isinstance(resp.body, int):
153-
resp.body = str(resp.body).encode()
154-
elif isinstance(resp.body, list) or isinstance(resp.body, dict):
155-
resp.body = json.dumps(resp.body).encode()
156-
if resp.headers['Content-Type'] == 'text/html; charset=utf-8':
157-
resp.headers['Content-Type'] = 'application/json'
158-
elif isinstance(resp.body, Page):
159-
resp.body = resp.body.stdout().encode()
160-
161-
resp_body = [resp.body]
162-
status_code = str(resp.status_code)
163-
resp_headers = resp.headers.items()
153+
try:
154+
if resp:
155+
if isinstance(resp, Page):
156+
resp = r.create_response(resp, headers={'Content-Type': 'application/bevyframe'})
157+
if not isinstance(resp, Response):
158+
resp = r.create_response(resp)
159+
160+
if isinstance(resp.body, str) or isinstance(resp.body, int):
161+
resp.body = str(resp.body).encode()
162+
elif isinstance(resp.body, list) or isinstance(resp.body, dict):
163+
resp.body = json.dumps(resp.body).encode()
164+
if resp.headers['Content-Type'] == 'text/html; charset=utf-8':
165+
resp.headers['Content-Type'] = 'application/json'
166+
elif isinstance(resp.body, Page):
167+
resp.body = resp.body.stdout().encode()
168+
169+
resp_body = [resp.body]
170+
status_code = str(resp.status_code)
171+
resp_headers = resp.headers.items()
172+
173+
except Exception as e:
174+
print("BevyFrame 500")
175+
print(f"Content-Type: text/plain\n")
176+
print(f"SDK Error: {e}")
177+
return 0
164178

165179
out = f"BevyFrame {status_code}\n".encode()
166180
for header in resp_headers:

0 commit comments

Comments
 (0)