-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbicchiere.py
executable file
·5771 lines (5001 loc) · 221 KB
/
bicchiere.py
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
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
from http.client import HTTPException
import os, sys
import webbrowser
from xml.dom import NotSupportedErr
if sys.version_info < (3, 6):
raise NotSupportedErr("This software only runs within Python version 3.6 or higher.")
# Following 3 for ASGIServer
from dataclasses import dataclass, field
from typing import List, Tuple, Any, Callable, Dict, Optional, overload
import http
# These for sync2async
import asyncio.coroutines
import contextvars
import functools
import warnings
import weakref
from concurrent.futures import Future, ThreadPoolExecutor
from concurrent.futures import Executor
import queue
import string
# Till here
import logging
import inspect
import struct
import mimetypes
import random
import re
import json
import cgi
import threading
import base64
import sqlite3
import hmac
import hashlib
import asyncio
import urllib.request
import wsgiref.util
import zlib
from tempfile import TemporaryFile, SpooledTemporaryFile
#from email import charset
from argparse import ArgumentTypeError
from io import StringIO, BytesIO
from subprocess import Popen, PIPE, STDOUT, run as runsub
from datetime import datetime # , timedelta
from time import time as timestamp, sleep
import time as o_time
from functools import reduce, wraps, partial
from http.cookies import SimpleCookie # , Morsel
from socketserver import ThreadingMixIn
import socket
from socket import error as socket_error # , socket as Socket
from wsgiref.headers import Headers
from wsgiref.simple_server import make_server, ServerHandler, WSGIRequestHandler, WSGIServer
from wsgiref.simple_server import demo_app as simple_demo_app
from uuid import uuid4
from urllib.parse import parse_qsl
from mimetypes import guess_type
import wsgiref.util
#from xmlrpc.client import Boolean
# Prepares logging
logger = logging.getLogger("Bicchiere")
logging.basicConfig()
# End of logging part
# Part I - The sync world
# Websocket auxiliary classes and stuff
_is_hop_by_hop = wsgiref.util.is_hop_by_hop
wsgiref.util.is_hop_by_hop = lambda x: False
class EventArg:
"Simple class for passing packed event arguments to handlers"
__slots__ = ["target", "type", "data"]
def __init__(self, target=None, type="change", data=None):
self.target = target
self.type = type
self.data = data
class Event:
"""
Class to manage event handlers and emit events on behalf of their source (target)
Not meant to be used as a mixin, but to be included in a 'has a' relationship.
Mainly, to implement 'onxxx' handlers.
"""
def __init__(self, event_target, event_type: str):
self.event_target = event_target
self.event_type = event_type
self.event_handlers = []
self.cancel_handlers = []
def subscribe(self, handler):
if not callable(handler):
raise ArgumentTypeError("Event handler must be a callable object")
fid = uuid4().hex
handler.fid = fid
def off():
for index, handler in enumerate(self.event_handlers):
if handler.fid == fid:
return self.event_handlers.pop(index)
return None
off.fid = fid
self.event_handlers.append(handler)
self.cancel_handlers.append(off)
return off
def unsubscribe(self, fid: str = ""):
if not fid:
self.event_handlers = []
self.cancel_handlers = []
return None
for index, cancel_handler in enumerate(self.cancel_handlers):
if cancel_handler.fid == fid:
event_handler = cancel_handler()
self.cancel_handlers.pop(index)
return event_handler
return None
def __iadd__(self, handler):
self.subscribe(handler)
return self
def __isub__(self, fid):
self.unsubscribe(fid)
return self
def emit(self, data=None):
arg = EventArg(target=self.event_target,
type=self.event_type, data=data)
for handler in self.event_handlers:
handler(arg)
class BicchiereServerHandler(ServerHandler):
http_version = "1.1"
def _convert_string_type(self, value, title):
if isinstance(value, str):
return value
raise AssertionError(
"{0} must be of type str (got {1})".format(title, repr(value)))
def start_response(self, status, headers, exc_info=None):
if exc_info:
try:
if self.headers_sent:
raise exc_info[0](exc_info[1]).with_traceback(exc_info[2])
finally:
exc_info = None
elif self.headers is not None:
raise AssertionError("Headers already set!")
self.status = status
self.headers = self.headers_class(headers)
status = self._convert_string_type(status, "Status")
assert len(status) >= 4, "Status must be at least 4 characters"
assert status[:3].isdigit(), "Status message must begin w/3-digit code"
assert status[3] == " ", "Status message must have a space after code"
if __debug__:
for name, val in headers:
name = self._convert_string_type(name, "Header name")
val = self._convert_string_type(val, "Header value")
self.send_headers()
return self.write
class BicchiereHandler(WSGIRequestHandler):
def address_string(self):
return self.client_address[0]
def log_request(self, *args, **kw):
try:
if not getattr(self, "quit", False):
return WSGIRequestHandler.log_request(self, *args, **kw)
except:
pass
def get_app(self):
return self.server.get_app()
def handle(self):
self.raw_requestline = self.rfile.readline(65537)
if len(self.raw_requestline) > 65536:
self.requestline = ""
self.request_version = ""
self.command = ""
self.send_error(414)
return
if not self.parse_request():
return
handler = BicchiereServerHandler(
self.rfile, self.wfile, self.get_stderr(), self.get_environ())
handler.request_handler = self
handler.run(self.get_app())
class SuperDict(dict):
"Dictionary that makes no difference between items and attributes"
def __getattr__(self, attr):
return super().get(attr)
def __setattr__(self, attr, val):
self.__setitem__(attr, val)
def __delattr__(self, attr):
if self.get(attr):
self.__delitem__(attr)
def __getitem__(self, key):
return super().get(key)
def __delitem__(self, key):
if super().get(key):
super().__delitem__(key)
def __repr__(self) -> str:
return json.dumps(self, default=lambda x: repr(x))
def pop(self, __name: str):
value = super().get(__name)
if value:
super().__delitem__(__name)
return value
else:
return None
class Stream:
"""Handler that encapsulates an input file descriptor together with an output file descriptor"""
def __init__(self, inputstream, outputstream):
self.input = inputstream
self.output = outputstream
self.buffer = []
self.flush = self.output.flush if hasattr(
self.output, "flush") else lambda: None
def read(self, size=-1):
try:
value = self.input.read(size)
except Exception as exc:
value = self.error(exc)
finally:
return value
def write(self, buffer):
try:
value = self.output.write(buffer)
self.flush()
except Exception as exc:
value = self.error(exc)
finally:
return value
def close(self):
try:
self.input.close()
self.output.close()
except Exception as exc:
self.error(exc)
def error(self, exc):
r = repr(exc)
print(r)
return r
def __del__(self):
try:
self.close()
except:
pass
class WebSocketError(socket_error):
"""
Base class for all websocket errors.
"""
pass
class ProtocolError(WebSocketError):
pass
class FrameTooLargeException(ProtocolError):
"""
Raised if a frame is received that is too large.
"""
class WebSocket:
"""
Base class for supporting websocket operations.
"""
OPCODE_CONTINUATION = 0x00
OPCODE_TEXT = 0x01
OPCODE_BINARY = 0x02
OPCODE_CLOSE = 0x08
OPCODE_PING = 0x09
OPCODE_PONG = 0x0A
FIN_MASK = 0x80
OPCODE_MASK = 0x0F
MASK_MASK = 0x80
LENGTH_MASK = 0x7F
RSV0_MASK = 0x40
RSV1_MASK = 0x20
RSV2_MASK = 0x10
HEADER_FLAG_MASK = RSV0_MASK | RSV1_MASK | RSV2_MASK
# default messages
MSG_SOCKET_DEAD = "Socket is dead"
MSG_ALREADY_CLOSED = "Connection is already closed"
MSG_CLOSED = "Connection closed"
origin = None
protocol = None
version = None
path = None
logger = logging.getLogger("WebSocket")
def __init__(self, environ, read, write, handler, do_compress):
self.environ = environ
self.closed = False
self.write = write
self.read = read
self.handler = handler
self.do_compress = do_compress
self.origin = self.environ.get("HTTP_SEC_WEBSOCKET_ORIGIN") or self.environ.get("HTTP_ORIGIN")
self.protocols = list(map(str.strip, self.environ.get("HTTP_SEC_WEBSOCKET_PROTOCOL", "").split(",")))
self.version = int(self.environ.get("HTTP_SEC_WEBSOCKET_VERSION", "13").strip())
self.path = self.environ.get("PATH_INFO", "/")
if do_compress:
self.compressor = zlib.compressobj(7, zlib.DEFLATED, -zlib.MAX_WBITS)
self.decompressor = zlib.decompressobj(-zlib.MAX_WBITS)
self.default_handler = self.logger.info
self.onopen = Event(self, "open")
self.onopen += partial(self.default_handler, "WebSocket Opened")
self.onerror = Event(self, "error")
self.onmessage = Event(self, "message")
self.onclose = Event(self, "close")
self.onping = Event(self, "ping")
self.onpong = Event(self, "pong")
def heartbeat(self):
#dt = datetime.now()
#sdate = dt.strftime("%Y-%m-%d %H:%M:%S").encode("utf-8")
#self.send_frame(sdate, self.OPCODE_PING)
self.send_frame(str(Bicchiere.millis()), self.OPCODE_PING)
def __del__(self):
try:
self.close()
except:
# close() may fail if __init__ didn't complete
pass
def _decode_bytes(self, bytestring):
if not bytestring:
return ""
try:
return bytestring.decode("utf-8")
except UnicodeDecodeError as e:
self.logger.debug('UnicodeDecodeError')
self.close(1007, str(e))
raise
def _encode_bytes(self, text):
if not isinstance(text, str):
text = str(text or "")
return text.encode("utf-8")
def _is_valid_close_code(self, code):
# valid hybi close code?
if (code < 1000 or 1004 <= code <= 1006 or 1012 <= code <= 1016
or code ==
# not sure about this one but the autobahn fuzzer requires it.
1100
or 2000 <= code <= 2999):
return False
return True
def handle_close(self, payload):
if not payload:
self.close(1000, "")
return
if len(payload) < 2:
raise ProtocolError("Invalid close frame: %s" % payload)
code = struct.unpack("!H", payload[:2])[0]
payload = payload[2:]
if payload:
payload.decode("utf-8")
if not self._is_valid_close_code(code):
raise ProtocolError("Invalid close code %s" % code)
self.close(code, payload)
self.onclose.emit(payload)
def handle_ping(self, payload):
self.send_frame(payload, self.OPCODE_PONG)
self.onping.emit(payload)
def handle_pong(self, payload):
self.onpong.emit(payload)
def mask_payload(self, mask, length, payload):
payload = bytearray(payload)
mask = bytearray(mask)
for i in range(length):
payload[i] ^= mask[i % 4]
return payload
def read_message(self):
opcode = None
message = bytearray()
while True:
data = self.read(2)
if len(data) != 2:
first_byte, second_byte = 0, 0
else:
first_byte, second_byte = struct.unpack("!BB", data)
fin = first_byte & self.FIN_MASK
f_opcode = first_byte & self.OPCODE_MASK
flags = first_byte & self.HEADER_FLAG_MASK
length = second_byte & self.LENGTH_MASK
has_mask = second_byte & self.MASK_MASK == self.MASK_MASK
if f_opcode > 0x07:
if not fin:
raise ProtocolError(
"Received fragmented control frame: {0!r}".format(data))
# Control frames MUST have a payload length of 125 bytes or less
if length > 125:
raise FrameTooLargeException(
"Control frame cannot be larger than 125 bytes: {0!r}".format(data))
if length == 126:
# 16 bit length
data = self.read(2)
if len(data) != 2:
raise WebSocketError(
"Unexpected EOF while decoding header")
length = struct.unpack("!H", data)[0]
elif length == 127:
# 64 bit length
data = self.read(8)
if len(data) != 8:
raise WebSocketError(
"Unexpected EOF while decoding header")
length = struct.unpack("!Q", data)[0]
if has_mask:
mask = self.read(4)
if len(mask) != 4:
raise WebSocketError(
"Unexpected EOF while decoding header")
if self.do_compress and (flags & self.RSV0_MASK):
flags &= ~self.RSV0_MASK
compressed = True
else:
compressed = False
if flags:
raise ProtocolError(str(flags))
if not length:
payload = b""
else:
try:
payload = self.read(length)
except socket.error:
payload = b""
except Exception:
raise WebSocketError("Could not read payload")
if len(payload) != length:
raise WebSocketError(
"Unexpected EOF reading frame payload")
if has_mask:
payload = self.mask_payload(mask, length, payload)
if compressed:
payload = b"".join((
self.decompressor.decompress(bytes(payload)),
self.decompressor.decompress(b"\0\0\xff\xff"),
self.decompressor.flush(),
))
if f_opcode in (self.OPCODE_TEXT, self.OPCODE_BINARY):
# a new frame
if opcode:
raise ProtocolError("The opcode in non-fin frame is "
"expected to be zero, got "
"{0!r}".format(f_opcode))
opcode = f_opcode
elif f_opcode == self.OPCODE_CONTINUATION:
if not opcode:
raise ProtocolError("Unexpected frame with opcode=0")
elif f_opcode == self.OPCODE_PING:
self.handle_ping(payload)
continue
elif f_opcode == self.OPCODE_PONG:
self.handle_pong(payload)
continue
elif f_opcode == self.OPCODE_CLOSE:
print('opcode close')
self.handle_close(payload)
return
else:
raise ProtocolError("Unexpected opcode={0!r}".format(f_opcode))
if opcode == self.OPCODE_TEXT:
payload.decode("utf-8")
message += payload
if fin:
break
self.onmessage.emit(message)
if opcode == self.OPCODE_TEXT:
return self._decode_bytes(message)
else:
return message
def receive(self):
"""
Read and return a message from the stream. If `None` is returned, then
the socket is considered closed/errored.
"""
if self.closed:
self.logger.debug('Receive closed')
err_already_closed = WebSocketError(self.MSG_ALREADY_CLOSED)
self.onerror.emit(err_already_closed)
raise err_already_closed
# return None
try:
return self.read_message()
except UnicodeError as e:
self.logger.debug('UnicodeDecodeError')
self.close(1007, str(e).encode("utf-8"))
self.onclose.emit(str(e).encode("utf-8"))
except ProtocolError as e:
self.logger.debug(f'Protocol err: {repr(e)}')
self.close(1002, str(e).encode())
self.onclose.emit(self.MSG_CLOSED)
except socket.timeout as e:
self.logger.debug('Socket timeout')
self.close(message=str(e))
self.onclose.emit(str(e))
except socket.error as e:
self.logger.debug(f'Spcket error: {repr(e)}')
self.close(message=str(e))
self.onclose.emit(self.MSG_CLOSED)
return None
def encode_header(self, fin, opcode, mask, length, flags):
first_byte = opcode
second_byte = 0
extra = b""
result = bytearray()
if fin:
first_byte |= self.FIN_MASK
if flags & self.RSV0_MASK:
first_byte |= self.RSV0_MASK
if flags & self.RSV1_MASK:
first_byte |= self.RSV1_MASK
if flags & self.RSV2_MASK:
first_byte |= self.RSV2_MASK
if length < 126:
second_byte += length
elif length <= 0xFFFF:
second_byte += 126
extra = struct.pack("!H", length)
elif length <= 0xFFFFFFFFFFFFFFFF:
second_byte += 127
extra = struct.pack("!Q", length)
else:
raise FrameTooLargeException
if mask:
second_byte |= self.MASK_MASK
result.append(first_byte)
result.append(second_byte)
result.extend(extra)
if mask:
result.extend(mask)
return result
def send_frame(self, message, opcode, do_compress=False):
if self.closed:
self.logger.debug('Receive closed')
self.onclose.emit(self.MSG_ALREADY_CLOSED)
raise WebSocketError(self.MSG_ALREADY_CLOSED)
if not message:
return
if opcode in (self.OPCODE_TEXT, self.OPCODE_PING):
message = self._encode_bytes(message)
elif opcode == self.OPCODE_BINARY:
message = bytes(message)
if do_compress and self.do_compress:
message = self.compressor.compress(message)
message += self.compressor.flush(zlib.Z_SYNC_FLUSH)
if message.endswith(b"\x00\x00\xff\xff"):
message = message[:-4]
flags = self.RSV0_MASK
else:
flags = 0
header = self.encode_header(True, opcode, b"", len(message), flags)
try:
self.write(bytes(header + message))
except socket_error as e:
raise WebSocketError(self.MSG_SOCKET_DEAD + " : " + str(e))
def send(self, message, binary=None, do_compress=True):
"""
Send a frame over the websocket with message as its payload
"""
if binary is None:
binary = not isinstance(message, str)
opcode = self.OPCODE_BINARY if binary else self.OPCODE_TEXT
try:
self.send_frame(message, opcode, do_compress)
except WebSocketError:
self.logger.debug(
f"Socket already closed: {repr(self.MSG_ALREADY_CLOSED)}")
self.onclose.emit(self.MSG_SOCKET_DEAD)
raise WebSocketError(self.MSG_SOCKET_DEAD)
def close(self, code=1000, message=b""):
"""
Close the websocket and connection, sending the specified code and
message. The underlying socket object is _not_ closed, that is the
responsibility of the initiator.
"""
print("close called")
if self.closed:
self.logger.debug('Receive closed')
self.onclose.emit(self.MSG_ALREADY_CLOSED)
try:
message = self._encode_bytes(message)
self.send_frame(struct.pack("!H%ds" % len(message), code, message),
opcode=self.OPCODE_CLOSE)
except WebSocketError:
self.logger.debug(
"Failed to write closing frame -> closing socket")
finally:
self.logger.debug("Closed WebSocket")
self.closed = True
self.write = None
self.read = None
self.environ = None
# End of websocket auxiliary classes
# Threading server
class BicchiereServer(ThreadingMixIn, WSGIServer):
"""This class is identical to WSGIServer but uses threads to handle
requests by using the ThreadingMixIn. This is useful to handle web
browsers pre-opening sockets, on which Server would wait indefinitely.
Credits for the idea to Kavindu Santhusa (@ksenginew)
See https://github.com/ksenginew/WSocket
"""
multithread = True
daemon_threads = True
# Threading server
# Routing classes
class Route:
"Utility class for routing requests"
def __init__(self, pattern, func, param_types, methods=['GET']):
self.pattern = pattern
self.func = func
self.param_types = param_types
self.methods = methods
self.args = {}
def __call__(self):
return (self.pattern, self.func, self.param_types, self.args, self.methods)
def match(self, path):
if not path:
return None
m = self.pattern.match(path)
if m:
kwargs = m.groupdict()
self.args = {}
for argname in kwargs:
self.args[argname] = self.param_types[argname](kwargs[argname])
return self
# return m.groupdict(), self.func, self.methods, self.param_types
return None
def __str__(self):
return f"""
Pattern: {str(self.pattern)}
Handler: {self.func.__name__}
Parameter Types: {self.param_types}
Methods: {self.methods}
Arguments: {self.args}
"""
# End of routing classes
# Templates related code
class CodeBuilder:
"""Build source code conveniently."""
def __init__(self, indent=0):
self.code = []
self.indent_level = indent
def add_line(self, line):
"""Add a line of source to the code.
Indentation and newline will be added for you, don't provide them.
"""
self.code.extend([" " * self.indent_level, line, "\n"])
INDENT_STEP = 4 # PEP8 says so!
def indent(self):
"""Increase the current indent for following lines."""
self.indent_level += self.INDENT_STEP
def dedent(self):
"""Decrease the current indent for following lines."""
self.indent_level -= self.INDENT_STEP
def add_section(self):
"""Add a section, a sub-CodeBuilder."""
section = CodeBuilder(self.indent_level)
self.code.append(section)
return section
def __str__(self):
return "".join(str(c) for c in self.code)
def get_globals(self):
"""Execute the code, and return a dict of globals it defines."""
# A check that the caller really finished all the blocks they started.
assert self.indent_level == 0
# Get the Python source as a single string.
python_source = str(self)
# Execute the source, defining globals, and return them.
global_namespace = {}
exec(python_source, global_namespace)
return global_namespace
class TemplateSyntaxError(BaseException):
pass
class TemplateLight:
test_tpl = """
<h2> Hello, I am {{ user }}. </h2>
<p>These are my favourite teams, in no particular order.<p>
<p>
<ul>
{% for team in teams %}
<li> {{ team }} </li>
{% endfor %}
</ul>
</p>
"""
def __init__(self, text, **contexts):
"""Construct a TemplateLight with the given `text`.
`contexts` are key-value pairs to use for future renderings.
These are good for filters and global values.
"""
self._template_text = text
self.context = {}
# for context in contexts:
# self.context.update(context)
self.context.update(contexts)
self.all_vars = set()
self.loop_vars = set()
code = CodeBuilder()
code.add_line("def render_function(context, do_dots):")
code.indent()
vars_code = code.add_section()
code.add_line("result = []")
code.add_line("append_result = result.append")
code.add_line("extend_result = result.extend")
code.add_line("to_str = str")
buffered = []
def flush_output():
"""Force `buffered` to the code builder."""
if len(buffered) == 1:
code.add_line("append_result(%s)" % buffered[0])
elif len(buffered) > 1:
code.add_line("extend_result([%s])" % ", ".join(buffered))
del buffered[:]
ops_stack = []
text = text.replace(",", " , ")
tokens = re.split(r"(?s)({{.*?}}|{%.*?%}|{#.*?#})", text)
for token in tokens:
if token.startswith('{#'):
# Comment: ignore it and move on.
continue
elif token.startswith('{{'):
# An expression to evaluate.
expr = self._expr_code(token[2:-2].strip())
buffered.append("to_str({0})".format(expr))
elif token.startswith('{%'):
# Action tag: split into words and parse further.
flush_output()
words = token[2:-2].strip().split()
if words[0] == 'if':
# An if statement: evaluate the expression to determine if.
# if len(words) != 2:
# self._syntax_error("Don't understand if", token)
ops_stack.append('if')
code.add_line("if {0}:".format(
self._expr_code(' '.join(words[1:]))))
code.indent()
elif words[0] == 'elif':
# An elif statement: evaluate the expression to determine else.
#print("Uso de 'else' en el template detectado.")
# if len(words) != 2:
# self._syntax_error("Don't understand elif", token)
if not ops_stack:
self._syntax_error(
"'elif' without previous 'if'", token)
start_what = ops_stack.pop()
if (start_what != "if"):
self._syntax_error(
"'elif' without previous 'if'", token)
ops_stack.append('if')
code.dedent()
code.add_line("elif {0}:".format(
self._expr_code(' '.join(words[1:]))))
code.indent()
elif words[0] == 'else':
# An else statement: evaluate the expression to determine else.
#print("Uso de 'else' en el template detectado.")
if len(words) != 1:
self._syntax_error("Don't understand else", token)
if not ops_stack:
self._syntax_error(
"'Else' without previous 'if'", token)
start_what = ops_stack.pop()
if (start_what != "if"):
self._syntax_error(
"'Else' without previous 'if'", token)
ops_stack.append('else')
code.dedent()
code.add_line("else:")
code.indent()
elif words[0] == 'for':
# A loop: iterate over expression result.
if words[-2] != 'in':
self._syntax_error("Don't understand for", token)
ops_stack.append('for')
loopvars = list(filter(lambda x: x != ',', words[1:-2]))
for loopvar in loopvars:
self._variable(loopvar, self.loop_vars)
deco_loopvars = list(map(lambda v: f"c_{v}", loopvars))
line_to_add = "for {0} in {1}:".format(
" , ".join(deco_loopvars), self._expr_code(words[-1]))
code.add_line(line_to_add)
code.indent()
elif words[0].startswith('end'):
# Endsomething. Pop the ops stack.
if len(words) != 1:
self._syntax_error("Don't understand end", token)
end_what = words[0][3:]
if not ops_stack:
self._syntax_error("Too many ends", token)
start_what = ops_stack.pop()
if (start_what != end_what) and (start_what != "else" or end_what != "if"):
self._syntax_error("Mismatched end tag", end_what)
code.dedent()
else:
self._syntax_error("Don't understand tag", words[0])
else:
# Literal content. If it isn't empty, output it.
if token:
buffered.append(repr(token))
if ops_stack:
self._syntax_error("Unmatched action tag", ops_stack[-1])
flush_output()
for var_name in self.all_vars - self.loop_vars:
vars_code.add_line("c_%s = context[%r]" % (var_name, var_name))
code.add_line("return ''.join(result)")
code.dedent()
self._code = code
self._render_function = code.get_globals()['render_function']
@staticmethod
def _is_string(name):
pattrn = r"""^(\"|\')(.*?)\1$"""
return re.match(pattrn, name)
@staticmethod
def _is_reserved(name):
if name == "true":
name = "True"
if name == "false":
name = "False"
# if name == "null" or name == "nil":
# name = "None"
return name in ["|", "if", "else", "and", "or", "not", "in", "is", "True", "False", "None"]
@staticmethod
def _is_variable(name):
if TemplateLight._is_reserved(name) or TemplateLight._is_string(name):
return False
pattrn = r"(?P<varname>[_a-zA-Z][_a-zA-Z0-9]*)(?P<subscript>\[(?P<subvar>.+)\])?$"
return re.match(pattrn, name)