/
base.py
5345 lines (4530 loc) · 219 KB
/
base.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/python
# -*- coding: utf-8 -*-
# Hive Appier Framework
# Copyright (c) 2008-2018 Hive Solutions Lda.
#
# This file is part of Hive Appier Framework.
#
# Hive Appier Framework is free software: you can redistribute it and/or modify
# it under the terms of the Apache License as published by the Apache
# Foundation, either version 2.0 of the License, or (at your option) any
# later version.
#
# Hive Appier Framework is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# Apache License for more details.
#
# You should have received a copy of the Apache License along with
# Hive Appier Framework. If not, see <http://www.apache.org/licenses/>.
__author__ = "João Magalhães <joamag@hive.pt>"
""" The author(s) of the module """
__version__ = "1.0.0"
""" The version of the module """
__revision__ = "$LastChangedRevision$"
""" The revision number of the module """
__date__ = "$LastChangedDate$"
""" The last change date of the module """
__copyright__ = "Copyright (c) 2008-2018 Hive Solutions Lda."
""" The copyright for the module """
__license__ = "Apache License, Version 2.0"
""" The license for the module """
import os
import re
import sys
import imp
import time
import json
import uuid
import atexit
import locale
import signal
import socket
import inspect
import datetime
import itertools
import mimetypes
import threading
import traceback
import logging.handlers
from . import bus
from . import log
from . import git
from . import http
from . import meta
from . import util
from . import data
from . import smtp
from . import mock
from . import cache
from . import extra
from . import model
from . import config
from . import legacy
from . import defines
from . import session
from . import request
from . import compress
from . import settings
from . import observer
from . import execution
from . import controller
from . import structures
from . import exceptions
from . import preferences
from . import asynchronous
APP = None
""" The global reference to the application object this
should be a singleton object and so no multiple instances
of an app may exist in the same process """
LEVEL = None
""" The global reference to the (parsed/processed) debug
level that is going to be used for some core assumptions
in situations where no app is created (eg: api clients) """
NAME = "appier"
""" The name to be used to describe the framework while working
on its own environment, this is just a descriptive value """
VERSION = "1.15.3"
""" The version of the framework that is currently installed
this value may be used for debugging/diagnostic purposes """
PLATFORM = "%s %d.%d.%d.%s %s" % (
sys.subversion[0] if hasattr(sys, "subversion") else "CPython",
sys.version_info[0],
sys.version_info[1],
sys.version_info[2],
sys.version_info[3],
sys.platform
)
""" Extra system information containing some of the details
of the technical platform that is running the system, this
string should be exposed carefully to avoid extra information
from being exposed to outside agents """
IDENTIFIER_SHORT = "%s/%s" % (NAME, VERSION)
""" The short version of the current environment's identifier
meant to be used in production like environment as it hides some
of the critical and internal information of the system """
IDENTIFIER_LONG = "%s/%s (%s)" % (NAME, VERSION, PLATFORM)
""" Longest version of the system identifier, to be used in the
development like environment as it shows critical information
about the system internals that may expose the system """
IDENTIFIER = IDENTIFIER_LONG if config._is_devel() else IDENTIFIER_SHORT
""" The identifier that may be used to identify an user agent
or service running under the current platform, this string
should comply with the typical structure for such values,
by default this value is set with the short version of the
identifier (less information) but this may be changed at
runtime if the current verbosity level is changed """
API_VERSION = 1
""" The incremental version number that may be used to
check on the level of compatibility for the api """
BUFFER_SIZE = 32768
""" The size of the buffer so be used while sending data using
the static file serving approach (important for performance) """
MAX_LOG_SIZE = 524288
""" The maximum amount of bytes for a log file created by
the rotating file handler, after this value is reached a
new file is created for the buffering of the results """
MAX_LOG_COUNT = 5
""" The maximum number of files stores as backups for the
rotating file handler, note that these values are stored
just for extra debugging purposes """
RUNNING = "running"
""" The running state for the app, indicating that the
complete api set is being served correctly """
STOPPED = "stopped"
""" The stopped state for the app, indicating that some
of the api components may be down """
CACHE_CONTROL = "private, no-cache, no-store, must-revalidate"
""" The default/fallback value that is going to be used in the
"Cache-Control" header for the dynamic requests, should be restrictive
in terms of re-validation of content """
ALLOW_ORIGIN = "*"
""" The default value to be used in the "Access-Control-Allow-Origin"
header value, this should not be too restrictive """
ALLOW_HEADERS = "*, X-Requested-With"
""" The default value to be used in the "Access-Control-Allow-Headers"
header value, this should not be too restrictive """
CONTENT_SECURITY = "default-src * ws://* wss://* data: blob:; script-src * 'unsafe-inline' 'unsafe-eval'; style-src * 'unsafe-inline';"
""" The default value to be used in the "Content-Security-Policy"
header value, this should not be too restrictive """
FRAME_OPTIONS = "SAMEORIGIN"
""" The value to be as the default/original for the "X-Frame-Options"
header, this should ensure that the same origin is always used when
trying to embed a dynamic content into a web page """
XSS_PROTECTION = "1; mode=block"
""" Value to be used as the original one for the "X-XSS-Protection"
header value, should provide a way of preventing XSS attach under the
internet explorer browser """
CONTENT_OPTIONS = "nosniff"
""" Default "X-Content-Type-Options" header value to be used to prevent
the sniffing of content type values, ensuring that the browser sticks to
value of content type provided by the server """
OCTET_TYPE = "application/octet-stream"
""" The mime/content type to be used for octet stream based message payloads
so that the legacy byte oriented value is readable """
REPLACE_REGEX = re.compile("(?<!\(\?P)\<((\w+)(\([\"'].*?[\"']\))?:)?(\w+)\>")
""" The regular expression to be used in the replacement
of the capture groups for the urls, this regex will capture
any named group not changed until this stage (eg: int,
string, regex, etc.) """
INT_REGEX = re.compile("\<int:(\w+)\>")
""" The regular expression to be used in the replacement
of the integer type based groups for the urls """
REGEX_REGEX = re.compile("\<regex\([\"'](.*?)[\"']\):(\w+)\>")
""" Regular expression that is going to be used for the
replacement of regular expression types with the proper
group in the final URL based route regex """
SLUGIER_REGEX_1 = re.compile(r"[^\w]+", re.UNICODE)
""" The first regular expression that is going to be used
by the slugier sub system to replace some of its values """
SLUGIER_REGEX_2 = re.compile(r"[-]+", re.UNICODE)
""" The second regular expression that is going to be used
by the slugier sub system to replace some of its values """
CSS_ABS_REGEX = re.compile(b"url\((?!(http:\/\/|https:\/\/|\/\/|\/))([^\)]+)\)")
""" The regular expression that is going to be used to capture
the relative CSS URL values, so that they may be converted into
absolute ones for proper inlining, note that the regex is defined
as a negation of the absolute URL values """
BODYLESS_METHODS = (
"GET",
"HEAD",
"OPTIONS",
"DELETE"
)
""" The sequence that defines the complete set of
HTTP methods that are considered to be bodyless,
meaning that no contents should be expected under
it's body, content length should be zero """
ESCAPE_EXTENSIONS = (
".xml",
".html",
".xhtml",
".liquid",
".xml.tpl",
".html.tpl",
".xhtml.tpl"
)
""" The sequence containing the various extensions
for which the autoescape mode will be enabled by
default as expected by the end developer """
TYPES_R = dict(
int = int,
str = legacy.UNICODE,
regex = legacy.UNICODE
)
""" Map that resolves a data type from the string representation
to the proper type value to be used in casting """
EXCLUDED_NAMES = (
"server",
"host",
"port",
"ssl",
"key_file",
"cer_file"
)
""" The sequence that contains the names that are considered
excluded from the auto parsing of parameters """
EMPTY_METHODS = (
"HEAD",
)
""" Sequence containing the complete set of HTTP methods, that
should have an empty body as defined by HTTP specification """
BASE_HEADERS = (
("X-Powered-By", IDENTIFIER),
)
""" The sequence containing the headers considered to be basic
and that are going to be applied to all of the requests received
by the appier framework (water marking each of the requests) """
REQUEST_LOCK = threading.RLock()
""" The lock to be used in the application handling of request
so that no two request get handled at the same time for the current
app instance, as that would create some serious problems """
CASTERS = {
list : lambda v: [y for y in itertools.chain(*[x.split(",") for x in v])],
bool : lambda v: v if isinstance(v, bool) else\
not v in ("", "0", "false", "False")
}
""" The map associating the various data types with a proper custom
caster to be used for special data types (more complex) under some
of the simple casting operations """
CASTER_MULTIPLE = {
list : True,
"list" : True
}
""" Map that associates the various data type values with the proper
value for the multiple (fields) for the (get) field operation, this
way it's possible to defined a pre-defined multiple value taking into
account the target data type """
class App(
legacy.with_meta(
meta.Indexed,
observer.Observable,
compress.Compress,
mock.MockApp
)
):
"""
The base application object that should be inherited
from all the application in the appier environment.
This object is responsible for the starting of all the
structures and for the routing of the request.
It should also be compliant with the WSGI specification.
"""
_BASE_ROUTES = []
""" Set of routes meant to be enable in a static
environment using for instance decorators this is
required because at the time of application loading
there's no application instance available """
_ERROR_HANDLERS = {}
""" The dictionary associating the error object (may be
both an integer code or an exception class) with the
proper method that is going to be used to handle that
error when it is raised """
_CUSTOM_HANDLERS = {}
""" Map that associates the various custom key values and
the tuples that describe the various handlers associated
with such actions (this is considered a generic value) """
def __init__(
self,
name = None,
locales = ("en_us",),
parts = (),
level = None,
handlers = None,
service = True,
safe = False,
lazy = False,
payload = False,
cache_s = 604800,
cache_c = cache.MemoryCache,
preferences_c = preferences.MemoryPreferences,
bus_c = bus.MemoryBus,
session_c = session.FileSession
):
observer.Observable.__init__(self)
compress.Compress.__init__(self)
self.name = name or self.__class__.__name__
self.name_b = self.name
self.name_i = self.name
self.locales = locales
self.parts = parts
self.service = service
self.safe = safe
self.lazy = lazy
self.payload = payload
self.cache_s = cache_s
self.cache_c = cache_c
self.preferences_c = preferences_c
self.bus_c = bus_c
self.session_c = session_c
self.description = self._description()
self.logo_url = None
self.logo_square_url = None
self.copyright = None
self.copyright_year = None
self.copyright_url = None
self.server = None
self.server_version = None
self.host = None
self.port = None
self.ssl = False
self.local_url = None
self.adapter = data.MongoAdapter()
self.manager = asynchronous.QueueManager(self)
self.routes_v = None
self.tid = None
self.type = "default"
self.status = STOPPED
self.start_time = None
self.start_date = None
self.touch_time = None
self.sort_headers = False
self.secure_headers = True
self.random = str(uuid.uuid4())
self.secret = self.random
self.cache = datetime.timedelta(seconds = cache_s)
self.cache_control = CACHE_CONTROL
self.allow_origin = ALLOW_ORIGIN
self.allow_headers = ALLOW_HEADERS
self.content_security = CONTENT_SECURITY
self.frame_options = FRAME_OPTIONS
self.xss_protection = XSS_PROTECTION
self.content_options = CONTENT_OPTIONS
self.login_route = "base.login"
self.part_routes = []
self.context = {}
self.models = {}
self.models_l = []
self.controllers = {}
self.controllers_l = []
self.names = {}
self.libraries = {}
self.lib_loaders = {}
self.parts_l = []
self.parts_m = {}
self._loaded = False
self._resolved = False
self._locale_d = locales[0]
self._server = None
self._user_routes = None
self._core_routes = None
self._own = self
self.__routes = []
self.load(level = level, handlers = handlers)
def __getattr__(self, name):
if not name in ("session",):
raise AttributeError("'%s' not found" % name)
if not hasattr(self, "request"):
raise AttributeError("'%s' not found" % name)
if not hasattr(self.request, name):
raise AttributeError("'%s' not found" % name)
return getattr(self.request, name)
@property
def request(self):
if not self.safe: return self._request
if self.is_main(): return self._request
return self.mock
@property
def mock(self):
return self._mock
@property
def own(self):
if not self.safe: return self._own
if self.is_main(): return self._own
return self
@property
def crypt_secret(self):
if not self.secret: return None
if self.secret == self.random: return None
return self.secret
@property
def server_full(self):
if not self.server_version: return self.server
return self.server + "/" + str(self.server_version)
@staticmethod
def load_g():
logging.basicConfig(format = log.LOGGING_FORMAT)
@staticmethod
def unload_g():
pass
@staticmethod
def add_route(*args, **kwargs):
route = App.norm_route(*args, **kwargs)
App._BASE_ROUTES.append(route)
@staticmethod
def add_error(error, method, scope = None, json = False, context = None):
error_handlers = App._ERROR_HANDLERS.get(error, [])
error_handlers.append([method, scope, json, context])
App._ERROR_HANDLERS[error] = error_handlers
if APP and APP._resolved: APP._add_error(
error,
method,
scope = scope,
json = json,
context = context
)
@staticmethod
def remove_error(error, method, scope = None, json = False, context = None):
error_handlers = App._ERROR_HANDLERS[error]
error_handlers.remove([method, scope, json, context])
if APP and APP._resolved: APP._remove_error(
error,
method,
scope = scope,
json = json,
context = context
)
@staticmethod
def add_exception(exception, method, scope = None, json = False, context = None):
error_handlers = App._ERROR_HANDLERS.get(exception, [])
error_handlers.append([method, scope, json, context])
App._ERROR_HANDLERS[exception] = error_handlers
if APP and APP._resolved: APP._add_exception(
exception,
method,
scope = scope,
json = json,
context = context
)
@staticmethod
def remove_exception(exception, method, scope = None, json = False, context = None):
error_handlers = App._ERROR_HANDLERS[exception]
error_handlers.remove([method, scope, json, context])
if APP and APP._resolved: APP._remove_exception(
exception,
method,
scope = scope,
json = json,
context = context
)
@staticmethod
def add_custom(key, method, context = None):
custom_handlers = App._CUSTOM_HANDLERS.get(key, [])
custom_handlers.append([method, context])
App._CUSTOM_HANDLERS[key] = custom_handlers
if is_loaded(): APP._add_custom(key, method, context = context)
@staticmethod
def remove_custom(key, method, context = None):
custom_handlers = App._CUSTOM_HANDLERS[key]
custom_handlers.remove([method, context])
if is_loaded(): APP._remove_custom(key, method, context = context)
@staticmethod
def norm_route(
method,
expression,
function,
asynchronous = False,
json = False,
context = None
):
# creates the list that will hold the various parameters (type and
# name tuples) and the map that will map the name of the argument
# to the string representing the original expression of it so that
# it may be latter used for reference (as specified in definition)
param_t = []
names_t = {}
# retrieves the data type of the provided method and in case it
# references a string type converts it into a simple tuple otherwise
# uses it directly, then creates the options dictionary with the
# series of values that are going to be used as options in the route
method_t = type(method)
method = (method,) if method_t in legacy.STRINGS else method
opts = dict(
json = json,
asynchronous = asynchronous,
base = expression,
param_t = param_t,
names_t = names_t
)
# creates a new match based iterator to try to find all the parameter
# references in the provided expression so that meta information may
# be created on them to be used latter in replacements
iterator = REPLACE_REGEX.finditer(expression)
for match in iterator:
# retrieves the group information on the various groups and unpacks
# them creating the param tuple from the resolved type and the name
# of the parameter (to be used in parameter passing casting)
_type_s, type_t, extras, name = match.groups()
type_r = TYPES_R.get(type_t, str)
param = (type_r, name)
# creates the target (replacement) expression taking into account if
# the type values has been provided or not, note that for expression
# with type the extras value is used in case it exists
if type_t: target = "<" + type_t + (extras or "") + ":" + name + ">"
else: target = "<" + name + ">"
# adds the parameter to the list of parameter tuples and then sets the
# target replacement association (name to target string)
param_t.append(param)
names_t[name] = target
# runs the regex based replacement chain that should translate
# the expression from a simplified domain into a regex based domain
# that may be correctly compiled into the rest environment then
# creates the route list, compiling the expression and returns it
# to the caller method so that it may be used in the current environment
expression = "^" + expression + "$"
expression = INT_REGEX.sub(r"(?P[\1>[\\d]+)", expression)
expression = REGEX_REGEX.sub(r"(?P[\2>\1)", expression)
expression = REPLACE_REGEX.sub(r"(?P[\4>[\\@\\+\\:\\.\\s\\w-]+)", expression)
expression = expression.replace("?P[", "?P<")
return [method, re.compile(expression, re.UNICODE), function, context, opts]
def load(self, *args, **kwargs):
level = kwargs.get("level", None)
handlers = kwargs.get("handlers", None)
self._set_global()
self._load_paths()
self._load_config()
self._load_logging(level)
self._load_settings()
self._load_handlers(handlers)
self._load_cache()
self._load_preferences()
self._load_bus()
self._load_session()
self._load_adapter()
self._load_manager()
self._load_execution()
self._load_request()
self._load_context()
self._load_templating()
self._load_imaging()
self._load_slugification()
self._load_bundles()
self._load_controllers()
self._load_models()
self._load_parts()
self._load_libraries()
self._load_patches()
self._set_config()
self._set_variables()
self._loaded = True
def unload(self, *args, **kwargs):
self._unload_parts()
self._unload_models()
self._unload_execution()
self._unload_bus()
self._unload_preferences()
self._unload_cache()
self._unload_logging()
self._loaded = False
def start(self, refresh = True):
if self.status == RUNNING: return
self._print_welcome()
self.tid = threading.current_thread().ident
self.start_time = time.time()
self.start_date = datetime.datetime.utcnow()
self.touch_time = "t=%d" % self.start_time
self._start_models()
if refresh: self.refresh()
if self.manager: self.manager.start()
self.status = RUNNING
self.trigger("start")
def stop(self, refresh = True):
if self.status == STOPPED: return
self._print_bye()
self.tid = None
self._stop_models()
if refresh: self.refresh()
self.status = STOPPED
self.trigger("stop")
def refresh(self):
self._set_url()
def info_dict(self):
return dict(
name = self.name,
instance = self.instance,
service = self.service,
type = self.type,
server = self.server,
server_version = self.server_version,
server_full = self.server_full,
host = self.host,
port = self.port,
ssl = self.ssl,
status = self.status,
uptime = self.get_uptime_s(),
routes = len(self._routes()),
configs = len(config.CONFIGS),
parts = self.get_parts(simple = True),
libraries = self.get_libraries(map = True),
platform = PLATFORM,
identifier = IDENTIFIER,
appier = VERSION,
api_version = API_VERSION,
date = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
)
def fork(self):
"""
Called upon process forking should be able to restore the child
process state to a situation where no issue arises.
This method should be called from within the child process.
"""
# verifies if there's an already started manager and adapter and
# if that's the case resets their state (avoids parent process issues)
if self.manager: self.manager.start()
if self.adapter: self.adapter.reset()
def loop(self, callable = lambda: time.sleep(60)):
# prints a small information message about the event loop that is
# just going t be started
self.logger.info("Starting event loop ...")
# creates the proper handler function that is going to be used in
# case of signal throwing operation (as expected)
handler = lambda s, f: sys.exit(0)
# registers for the proper signal handler so that the system exit
# exception is raised upon signal trigger
signint_old = signal.signal(signal.SIGINT, handler)
sigterm_old = signal.signal(signal.SIGTERM, handler)
# runs the start operation, effectively starting the infra-structure
# for the main event loop (as expected)
self.start()
# loops continuously over the callable function, waiting
# for an interruption that will break the loop
while True:
try: callable()
except (KeyboardInterrupt, SystemExit): break
# restores the old signal handler so that everything remains the same
# as it's expected by interface (proper base handlers)
signal.signal(signal.SIGINT, signint_old)
signal.signal(signal.SIGTERM, sigterm_old)
# runs the "final" stop operation that will restore the data structures
# back to the "original"/expected state
self.stop()
def serve(
self,
server = "legacy",
host = "127.0.0.1",
port = 8080,
ipv6 = False,
ssl = False,
key_file = None,
cer_file = None,
backlog = socket.SOMAXCONN,
threaded = False,
conf = True,
**kwargs
):
server = config.conf("SERVER", server) if conf else server
host = config.conf("HOST", host) if conf else host
port = config.conf("PORT", port, cast = int) if conf else port
ipv6 = config.conf("IPV6", ipv6, cast = bool) if conf else cer_file
ssl = config.conf("SSL", ssl, cast = bool) if conf else ssl
key_file = config.conf("KEY_FILE", key_file) if conf else key_file
cer_file = config.conf("CER_FILE", cer_file) if conf else cer_file
backlog = config.conf("BACKLOG", backlog, cast = int) if conf else backlog
servers = config.conf_prefix("SERVER_") if conf else dict()
for name, value in servers.items():
name_s = name.lower()[7:]
if name_s in EXCLUDED_NAMES: continue
kwargs[name_s] = value
kwargs["handlers"] = self.handlers
kwargs["level"] = self.level
self.logger.info("Starting '%s' with '%s' ..." % (self.name, server))
self.server = server
self.host = host
self.port = port
self.ssl = ssl
self.start()
method = getattr(self, "serve_" + server)
names = method.__code__.co_varnames
if "ipv6" in names: kwargs["ipv6"] = ipv6
if "ssl" in names: kwargs["ssl"] = ssl
if "key_file" in names: kwargs["key_file"] = key_file
if "cer_file" in names: kwargs["cer_file"] = cer_file
if "backlog" in names: kwargs["backlog"] = backlog
if threaded: util.BaseThread(
target = self.serve_final,
args = (server, method, host, port, kwargs),
daemon = True
).start()
else: self.serve_final(server, method, host, port, kwargs)
def serve_final(self, server, method, host, port, kwargs):
try: return_value = method(host = host, port = port, **kwargs)
except BaseException as exception:
lines = traceback.format_exc().splitlines()
self.logger.critical("Unhandled exception received: %s" % legacy.UNICODE(exception))
for line in lines: self.logger.warning(line)
raise
self.stop()
self.logger.info("Stopped '%s'' in '%s' ..." % (self.name, server))
return return_value
def serve_legacy(self, host, port, **kwargs):
"""
Starts the serving process for the application using the python's
legacy wsgi server implementation, this server is considered unstable
and should only be used for development/testing purposes.
:type host: String
:param host: The host name of ip address to bind the server
to, this value should be represented as a string.
:type port: int
:param port: The tcp port for the bind operation of the
server (listening operation).
"""
import wsgiref.simple_server
httpd = wsgiref.simple_server.make_server(host, port, self.application)
httpd.serve_forever()
def serve_netius(
self,
host,
port,
ipv6 = False,
ssl = False,
key_file = None,
cer_file = None,
backlog = socket.SOMAXCONN,
**kwargs
):
"""
Starts serving the current application using the hive solutions
python based web server netius HTPP, this is supposed to be used
with care as the server is still under development.
For more information on the netius HTTP servers please refer
to the https://github.com/hivesolutions/netius site.
:type host: String
:param host: The host name of IP address to bind the server
to, this value should be represented as a string.
:type port: int
:param port: The tcp port for the bind operation of the
server (listening operation).
:type ipv6: bool
:param ipv6: If the server should be started under the IPv6 mode
meaning that a socket is opened for that protocol, instead of the
typical IPv4 version.
:type ssl: bool
:param ssl: If the ssl framework for encryption should be used
in the creation of the server socket.
:type key_file: String
:param key_file: The path to the file containing the private key
that is going to be used in the SSL communication.
:type cer_file: String
:param cer_file: The path to the certificate file to be used in
the ssl based communication.
:type backlog: int
:param backlog: Size of the backlog structure that is going to be
used to store connections pending to be accepted, the larger the
value is the bigger is the capacity of the server to accept many
connections in a short time span.
"""
util.ensure_pip("netius")
import netius.servers
self.server_version = netius.VERSION
self._server = netius.servers.WSGIServer(self.application, **kwargs)
self._server.bind("child", lambda s: self.fork())
self._server.serve(
host = host,
port = port,
ipv6 = ipv6,
ssl = ssl,
key_file = key_file,
cer_file = cer_file,
backlog = backlog
)
def serve_waitress(self, host, port, **kwargs):
"""
Starts the serving of the current application using the
python based waitress server in the provided host and
port as requested.
For more information on the waitress HTTP server please
refer to https://pypi.python.org/pypi/waitress.
:type host: String
:param host: The host name of ip address to bind the server
to, this value should be represented as a string.
:type port: int
:param port: The tcp port for the bind operation of the
server (listening operation).
"""
waitress = util.import_pip("waitress")
waitress.serve(self.application, host = host, port = port)
def serve_tornado(self, host, port, ssl = False, key_file = None, cer_file = None, **kwargs):
util.ensure_pip("tornado")
import tornado.wsgi
import tornado.httpserver
self.server_version = tornado.version
ssl_options = ssl and dict(
keyfile = key_file,
certfile = cer_file
) or None
container = tornado.wsgi.WSGIContainer(self.application)
self._server = tornado.httpserver.HTTPServer(container, ssl_options = ssl_options)
self._server.listen(port, address = host)
instance = tornado.ioloop.IOLoop.instance()
instance.start()
def serve_cherry(self, host, port, **kwargs):
util.ensure_pip("cherrypy")
import cherrypy.wsgiserver
self.server_version = cherrypy.__version__
self._server = cherrypy.wsgiserver.CherryPyWSGIServer(
(host, port),
self.application
)
try: self._server.start()
except (KeyboardInterrupt, SystemExit): self._server.stop()
def serve_gunicorn(self, host, port, workers = 1, **kwargs):
util.ensure_pip("gunicorn")
import gunicorn.app.base
self.server_version = gunicorn.__version__
class GunicornApplication(gunicorn.app.base.BaseApplication):
def __init__(self, application, options = None):
self.application = application
self.options = options or {}
gunicorn.app.base.BaseApplication.__init__(self)
def load_config(self):
for key, value in legacy.iteritems(self.options):
self.cfg.set(key, value)
def load(self):
return self.application
options = dict(
bind = "%s:%d" % (host, port),
workers = workers
)
self._server = GunicornApplication(self.application, options)
self._server.run()
def load_jinja(self, **kwargs):
try: import jinja2
except: self.jinja = None; return
has_async = hasattr(jinja2, "asyncfilters")
use_cache = not self.is_devel()
use_cache = config.conf("TEMPLATE_CACHE", use_cache, cast = bool)
loader = jinja2.FileSystemLoader(self.templates_path)
auto_reload = False if use_cache else True
bytecode_cache = jinja2.FileSystemBytecodeCache() if use_cache else None
self.jinja = jinja2.Environment(
loader = loader,
auto_reload = auto_reload,
bytecode_cache = bytecode_cache,
extensions = ("jinja2.ext.do",),
**kwargs
)
self.jinja_cache = dict()
if has_async: self.jinja_async = jinja2.Environment(
loader = loader,
auto_reload = auto_reload,
bytecode_cache = bytecode_cache,
extensions = ("jinja2.ext.do",),
enable_async = True,
**kwargs
)
else: self.jinja_async = self.jinja
self.add_filter(self.to_locale_jinja, "locale", type = "context")
self.add_filter(self.nl_to_br_jinja, "nl_to_br", type = "eval")
self.add_filter(self.sp_to_nbsp_jinja, "sp_to_nbsp", type = "eval")
self.add_filter(self.echo, "echo")
self.add_filter(self.echo, "handle")
self.add_filter(self.dumps, "dumps")
self.add_filter(self.loads, "loads")