Repository navigation
Expand file tree
/
Copy pathSimpleFrame.py
More file actions
1344 lines (1118 loc) · 46 KB
/
Copy pathSimpleFrame.py
File metadata and controls
1344 lines (1118 loc) · 46 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
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
####################################################################
# Author: Limodou@gmail.com
# License: BSD
####################################################################
import os, sys
import cgi
import inspect
import re
import types
import warnings
try:
set
except:
from sets import Set as set
from werkzeug import ClosingIterator, Local, LocalManager
from werkzeug.exceptions import HTTPException, NotFound, BadRequest
from werkzeug.routing import Map
from . import template
from .js import json_dumps
from . import dispatch
from uliweb.utils.storage import Storage
from uliweb.utils.common import (pkg, log, import_attr,
myimport, wraps, norm_path)
import uliweb.utils.pyini as pyini
from uliweb.i18n import gettext_lazy, i18n_ini_convertor
from uliweb.utils.localproxy import LocalProxy, Global
from uliweb import UliwebError
#from rules import Mapping, add_rule
from . import rules
local = Local()
__global__ = Global()
local_manager = LocalManager([local])
url_map = Map()
static_views = []
use_urls = False
url_adapters = {}
__app_dirs__ = {}
__app_alias__ = {}
_xhr_redirect_json = True
request = None
response = None
make_request = None
make_response = None
r_callback = re.compile(r'^[\w_]+$')
#Initialize pyini env
pyini.set_env({
'env':{'_':gettext_lazy, 'gettext_lazy':gettext_lazy},
'convertors':i18n_ini_convertor,
})
__global__.settings = pyini.Ini(lazy=True)
#User can defined decorator functions in settings DECORATORS
#and user can user @decorators.function_name in views
#and this usage need settings be initialized before decorator invoking
class Finder(object):
def __init__(self, section):
self.__objects = {}
self.__section = section
def __contains__(self, name):
if name in self.__objects:
return True
if name not in settings[self.__section]:
return False
else:
return True
def __getattr__(self, name):
if name in self.__objects:
return self.__objects[name]
if name not in settings[self.__section]:
raise UliwebError("Object %s is not existed!" % name)
obj = import_attr(settings[self.__section].get(name))
self.__objects[name] = obj
return obj
def __setitem__(self, name, value):
if isinstance(value, (str, unicode)):
value = import_attr(value)
self.__objects[name] = value
decorators = Finder('DECORATORS')
functions = Finder('FUNCTIONS')
class HTTPError(Exception):
def __init__(self, errorpage=None, **kwargs):
self.errorpage = errorpage or settings.GLOBAL.ERROR_PAGE
self.errors = kwargs
def __str__(self):
return repr(self.errors)
def redirect(location, code=302):
global _xhr_redirect_json, request
if _xhr_redirect_json and request.is_xhr:
response = json({'success':False, 'redirect':location}, status=500)
else:
response = make_response(
'<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">\n'
'<title>Redirecting...</title>\n'
'<h1>Redirecting...</h1>\n'
'<p>You should be redirected automatically to target URL: '
'<a href="%s">%s</a>. If not click the link.' %
(cgi.escape(location), cgi.escape(location)), status=code, content_type='text/html')
response.headers['Location'] = location
return response
class RedirectException(Exception):
"""
This is an exception, which can be raised in view function
"""
def __init__(self, location, code=302):
self.response = redirect(location, code)
def get_response(self):
return self.response
def Redirect(url):
raise RedirectException(url)
def error(message='', errorpage=None, request=None, appname=None, **kwargs):
kwargs.setdefault('message', message)
if request:
kwargs.setdefault('link', functions.request_url())
raise HTTPError(errorpage, **kwargs)
def json(data, **json_kwargs):
if 'content_type' not in json_kwargs:
json_kwargs['content_type'] = 'application/json; charset=utf-8'
if callable(data):
@wraps(data)
def f(*arg, **kwargs):
ret = data(*arg, **kwargs)
return make_response(json_dumps(ret), **json_kwargs)
return f
else:
return make_response(json_dumps(data), **json_kwargs)
def jsonp(data, **json_kwargs):
"""
jsonp is callback key name
"""
global request
if 'jsonp' in json_kwargs:
cb = json_kwargs.pop('jsonp')
else:
cb = 'callback'
begin = str(request.GET.get(cb))
if not begin:
raise BadRequest("Can't found %s parameter in request's query_string" % cb)
if not r_callback.match(begin):
raise BadRequest("The callback name is not right, it can be alphabetic, number and underscore only")
if callable(data):
@wraps(data)
def f(*arg, **kwargs):
ret = data(*arg, **kwargs)
return make_response(begin + '(' + json_dumps(ret) + ');', **json_kwargs)
return f
else:
return make_response(begin + '(' + json_dumps(data) + ');', **json_kwargs)
def expose(rule=None, **kwargs):
e = rules.Expose(rule, **kwargs)
if e.parse_level == 1:
return rule
else:
return e
def POST(rule, **kw):
kw['methods'] = ['POST']
return expose(rule, **kw)
def GET(rule, **kw):
kw['methods'] = ['GET']
return expose(rule, **kw)
def get_url_adapter(_domain_name):
"""
Fetch a domain url_adapter object, and bind it to according domain
"""
domain = application.domains.get(_domain_name, {})
if domain.get('domain', ''):
adapter = url_map.bind(domain['host'], url_scheme=domain.get('scheme', 'http'))
else:
adapter = url_map.bind_to_environ(request.environ)
return adapter
def url_for(endpoint, **values):
point = rules.get_endpoint(endpoint)
#if the endpoint is string format, then find and replace
#the module prefix with app alias which matched
for k, v in __app_alias__.items():
if point.startswith(k):
point = v + point[len(k):]
break
if point in rules.__url_names__:
point = rules.__url_names__[point]
_domain_name = values.pop('_domain_name', 'default')
_external = values.pop('_external', False)
domain = application.domains.get(_domain_name, {})
if not _external:
_external = domain.get('display', False)
adapter = get_url_adapter(_domain_name)
return adapter.build(point, values, force_external=_external)
def get_app_dir(app):
"""
Get an app's directory
"""
path = __app_dirs__.get(app)
if path is not None:
return path
else:
p = app.split('.')
try:
path = pkg.resource_filename(p[0], '')
except ImportError as e:
log.error("Can't import app %s" % p[0])
log.exception(e)
path = ''
if len(p) > 1:
path = os.path.join(path, *p[1:])
__app_dirs__[app] = path
return path
def get_app_depends(app, existed_apps=None, installed_apps=None):
installed_apps = installed_apps or []
if existed_apps is None:
s = set()
else:
s = existed_apps
if app in s:
raise StopIteration
if isinstance(app, (tuple, list)):
app, name = app
__app_alias__[name+'.'] = app + '.'
configfile = os.path.join(get_app_dir(app), 'config.ini')
if os.path.exists(configfile):
x = pyini.Ini(configfile)
apps = x.get_var('DEPENDS/REQUIRED_APPS', [])
for i in apps:
if i not in s and i not in installed_apps:
for j in get_app_depends(i, s, installed_apps):
yield j
s.add(app)
yield app
def set_var(key, value):
"""
Default set_var function
"""
from uliweb import settings
settings.set_var(key, value)
def get_var(key, default=None):
"""
Default get_var function
"""
from uliweb import settings
return settings.get_var(key, default)
def get_local_cache(key, creator=None):
global local
if not hasattr(local, 'local_cache'):
local.local_cache = {}
value = local.local_cache.get(key)
if value:
return value
if callable(creator):
value = creator()
else:
value = creator
if value:
local.local_cache[key] = value
return value
def get_apps(apps_dir, include_apps=None, settings_file='settings.ini', local_settings_file='local_settings.ini'):
include_apps = include_apps or []
inifile = norm_path(os.path.join(apps_dir, settings_file))
apps = []
visited = set()
installed_apps = []
if not os.path.exists(apps_dir):
return apps
if os.path.exists(inifile):
x = pyini.Ini(inifile)
if x:
installed_apps.extend(x.GLOBAL.get('INSTALLED_APPS', []))
local_inifile = norm_path(os.path.join(apps_dir, local_settings_file))
if os.path.exists(local_inifile):
x = pyini.Ini(local_inifile)
if x:
installed_apps.extend(x.GLOBAL.get('INSTALLED_APPS', []))
installed_apps.extend(include_apps)
for app in installed_apps:
apps.extend(list(get_app_depends(app, visited, installed_apps)))
if not apps and os.path.exists(apps_dir):
for p in os.listdir(apps_dir):
if os.path.isdir(os.path.join(apps_dir, p)) and p not in ['.svn', 'CVS', '.git'] and not p.startswith('.') and not p.startswith('_'):
apps.append(p)
return apps
def collect_settings(project_dir, include_apps=None, settings_file='settings.ini',
local_settings_file='local_settings.ini', default_settings=None):
apps_dir = os.path.join(project_dir, 'apps')
apps = get_apps(apps_dir, None, settings_file=settings_file, local_settings_file=local_settings_file)
settings_file = os.path.join(apps_dir, settings_file)
local_settings_file = os.path.join(apps_dir, local_settings_file)
settings = []
inifile = pkg.resource_filename('uliweb.core', 'default_settings.ini')
settings.insert(0, inifile)
for p in apps:
path = get_app_dir(p)
#deal with settings
inifile =os.path.join(get_app_dir(p), 'settings.ini')
if os.path.exists(inifile):
settings.append(inifile)
if os.path.exists(settings_file):
settings.append(settings_file)
if os.path.exists(local_settings_file):
settings.append(local_settings_file)
return settings
def get_settings(project_dir, include_apps=None, settings_file='settings.ini',
local_settings_file='local_settings.ini', default_settings=None):
settings = collect_settings(project_dir, include_apps, settings_file,
local_settings_file, default_settings)
x = pyini.Ini(lazy=True)
for v in settings:
x.read(v)
x.update(default_settings or {})
x.freeze()
#process FILESYSTEM_ENCODING
if not x.GLOBAL.FILESYSTEM_ENCODING:
x.GLOBAL.FILESYSTEM_ENCODING = sys.getfilesystemencoding() or x.GLOBAL.DEFAULT_ENCODING
return x
def is_in_web():
return getattr(local, 'in_web', False)
class Loader(object):
def __init__(self, tmpfilename, vars, env, dirs, notest=False):
self.tmpfilename = tmpfilename
self.dirs = dirs
self.vars = vars
self.env = env
self.notest = notest
def get_source(self, exc_type, exc_value, exc_info, tb):
from uliweb.core.template import Template
t = Template('', self.vars, self.env, self.dirs)
t.set_filename(self.tmpfilename)
use_temp_flag, filename, text = t.get_parsed_code()
if exc_type is SyntaxError:
import re
r = re.search(r'line (\d+)', str(exc_value))
lineno = int(r.group(1))
else:
lineno = tb.tb_frame.f_lineno
return self.tmpfilename, lineno, text
def test(self, filename):
if self.notest:
return True
return filename.endswith('.html')
class DispatcherHandler(object):
def __init__(self, application):
self.application = application
def open(self, *args, **kw):
return self.application.open(*args, **kw)
def get(self, *args, **kw):
"""Like open but method is enforced to GET."""
kw['method'] = 'GET'
return self.open(*args, **kw)
def patch(self, *args, **kw):
"""Like open but method is enforced to PATCH."""
kw['method'] = 'PATCH'
return self.open(*args, **kw)
def post(self, *args, **kw):
"""Like open but method is enforced to POST."""
kw['method'] = 'POST'
return self.open(*args, **kw)
def head(self, *args, **kw):
"""Like open but method is enforced to HEAD."""
kw['method'] = 'HEAD'
return self.open(*args, **kw)
def put(self, *args, **kw):
"""Like open but method is enforced to PUT."""
kw['method'] = 'PUT'
return self.open(*args, **kw)
def delete(self, *args, **kw):
"""Like open but method is enforced to DELETE."""
kw['method'] = 'DELETE'
return self.open(*args, **kw)
class ContextStorage(object):
"""
Used to save increament vars
"""
__variables__ = {}
def __init__(self, args={}):
self.__class__.__variables__ = args
self._vars = {}
def __getattr__(self, key):
try:
return self['_vars'][key]
except KeyError as e:
try:
return self[key]
except KeyError as e:
return None
def copy(self):
n = ContextStorage(self.__variables__)
n._vars = self._vars.copy()
return n
def to_dict(self):
d = self._vars.copy()
d.update(self.__variables__)
return d
def __getitem__(self, key):
try:
return self._vars[key]
except KeyError as e:
return self.__variables__[key]
def __setitem__(self, key, value):
self._vars[key] = value
def update(self, arg):
self._vars.update(arg)
def items(self):
keys = set()
for k, v in self._vars.items():
keys.add(k)
yield k, v
for k, v in self.__variables__.items():
if k not in keys:
yield k, v
def __repr__(self):
return '<ContextStorage ' + repr(self.__variables__) + ' ' + repr(self._vars) + ' >'
class Dispatcher(object):
installed = False
def __init__(self, apps_dir='apps', project_dir=None, include_apps=None,
start=True, default_settings=None, settings_file='settings.ini',
local_settings_file='local_settings.ini', xhr_redirect_json=True):
global _xhr_redirect_json
_xhr_redirect_json = xhr_redirect_json
__global__.application = self
self.debug = False
self.include_apps = include_apps or []
self.default_settings = default_settings or {}
self.settings_file = settings_file
self.local_settings_file = local_settings_file
if not Dispatcher.installed:
self.init(project_dir, apps_dir)
dispatch.call(self, 'startup_installed')
self.init_urls()
if start:
dispatch.call(self, 'startup')
def init(self, project_dir, apps_dir):
global settings
if not project_dir:
project_dir = norm_path(os.path.join(apps_dir, '..'))
Dispatcher.project_dir = project_dir
Dispatcher.apps_dir = norm_path(os.path.join(project_dir, 'apps'))
Dispatcher.apps = get_apps(self.apps_dir, self.include_apps, self.settings_file, self.local_settings_file)
Dispatcher.modules = self.collect_modules()
self.install_settings(self.modules['settings'])
#init adapter
self.install_adapter()
#process global_objects
self.install_global_objects()
#process binds
self.install_binds()
dispatch.call(self, 'after_init_settings')
Dispatcher.settings = settings
#process domains
self.process_domains(settings)
#setup log
self.set_log()
#set app rules
rules.set_app_rules(dict(settings.get('URL', {})))
Dispatcher.env = self._prepare_env()
Dispatcher.template_dirs = self.get_template_dirs()
Dispatcher.template_processors = {}
self.install_template_processors()
#begin to start apps
self.install_apps()
dispatch.call(self, 'after_init_apps')
#process views
self.install_views(self.modules['views'])
#process exposes
self.install_exposes()
#process middlewares
self.install_middlewares()
self.debug = settings.GLOBAL.get('DEBUG', False)
dispatch.call(self, 'prepare_default_env', Dispatcher.env)
Dispatcher.default_template = pkg.resource_filename('uliweb.core', 'default.html')
Dispatcher.installed = True
def _prepare_env(self):
env = {}
env['url_for'] = url_for
env['redirect'] = redirect
env['Redirect'] = Redirect
env['error'] = error
env['application'] = self
env['settings'] = settings
env['json'] = json
env['jsonp'] = jsonp
env['functions'] = functions
env['json_dumps'] = json_dumps
c = ContextStorage(env)
return c
def set_log(self):
import logging
s = self.settings
def _get_level(level):
return getattr(logging, level.upper())
#get basic configuration
config = {}
for k, v in s.LOG.items():
if k in ['format', 'datefmt', 'filename', 'filemode']:
config[k] = v
if s.get_var('LOG/level'):
config['level'] = _get_level(s.get_var('LOG/level'))
logging.basicConfig(**config)
if config.get('filename'):
Handler = 'logging.FileHandler'
if config.get('filemode'):
_args =(config.get('filename'), config.get('filemode'))
else:
_args = (config.get('filename'),)
else:
Handler = 'logging.StreamHandler'
_args = ()
#process formatters
formatters = {}
for f, v in s.get_var('LOG.Formatters', {}).items():
formatters[f] = logging.Formatter(v)
#process handlers
handlers = {}
for h, v in s.get_var('LOG.Handlers', {}).items():
handler_cls = v.get('class', Handler)
handler_args = v.get('args', _args)
handler = import_attr(handler_cls)(*handler_args)
if v.get('level'):
handler.setLevel(_get_level(v.get('level')))
format = v.get('format')
if format in formatters:
handler.setFormatter(formatters[format])
elif format:
fmt = logging.Formatter(format)
handler.setFormatter(fmt)
handlers[h] = handler
#process loggers
for logger_name, v in s.get_var('LOG.Loggers', {}).items():
if logger_name == 'ROOT':
log = logging.getLogger('')
else:
log = logging.getLogger(logger_name)
if v.get('level'):
log.setLevel(_get_level(v.get('level')))
if 'propagate' in v:
log.propagate = v.get('propagate')
if 'handlers' in v:
for h in v['handlers']:
if h in handlers:
log.addHandler(handlers[h])
else:
raise UliwebError("Log Handler %s is not defined yet!")
sys.exit(1)
elif 'format' in v:
if v['format'] not in formatters:
fmt = logging.Formatter(v['format'])
else:
fmt = formatters[v['format']]
_handler = import_attr(Handler)(*_args)
_handler.setFormatter(fmt)
log.addHandler(_handler)
def process_domains(self, settings):
from urlparse import urlparse
Dispatcher.domains = {}
for k, v in settings.DOMAINS.items():
_domain = urlparse(v['domain'])
self.domains[k] = {'domain':v.get('domain'), 'domain_parse':_domain,
'host':_domain.netloc,
'scheme':_domain.scheme or 'http', 'display':v.get('display', False)}
def get_file(self, filename, dir='static'):
"""
get_file will search from apps directory
"""
if os.path.exists(filename):
return filename
dirs = self.apps
if dir:
fname = os.path.join(dir, filename)
else:
fname = filename
for d in reversed(dirs):
path = pkg.resource_filename(d, fname)
if os.path.exists(path):
return path
return None
def get_template_processor(self, filename):
ext = os.path.splitext(filename)[1]
if ext in self.template_processors:
return self.template_processors[ext]['func'], self.template_processors[ext]['args']
else:
return template.template_file, {}
def template(self, filename, vars=None, env=None, dirs=None, default_template=None):
vars = vars or {}
dirs = dirs or self.template_dirs
env = env or self.get_view_env()
func, kwargs = self.get_template_processor(filename)
if self.debug:
def _compile(code, filename, action, env, Loader=Loader):
env['__loader__'] = Loader(filename, vars, env, dirs, notest=True)
try:
return compile(code, filename, 'exec')
except:
# file('out.html', 'w').write(code)
raise
return func(filename, vars, env, dirs, default_template, compile=_compile, **kwargs)
else:
return func(filename, vars, env, dirs, default_template, **kwargs)
def render_text(self, text, vars=None, env=None, dirs=None, default_template=None):
vars = vars or {}
env = env or self.get_view_env()
dirs = dirs or self.template_dirs
return template.template(text, vars, env, dirs, default_template)
def render(self, templatefile, vars, env=None, dirs=None, default_template=None, content_type='text/html', status=200):
return make_response(self.template(templatefile, vars, env, dirs, default_template=default_template), status=status, content_type=content_type)
def _page_not_found(self, description=None, **kwargs):
description = 'The requested URL "{{=url}}" was not found on the server.'
text = """<h1>Page Not Found</h1>
<p>%s</p>
<h3>Current URL Mapping is</h3>
<table border="1">
<tr><th>#</th><th>URL</th><th>View Functions</th></tr>
{{for i, (url, methods, endpoint) in enumerate(urls):}}
<tr><td>{{=i+1}}</td><td>{{=url}} {{=methods}}</td><td>{{=endpoint}}</td></tr>
{{pass}}
</table>
""" % description
return make_response(template.template(text, kwargs), status=404)
def not_found(self, e):
if self.debug:
urls = []
for r in url_map.iter_rules():
if r.methods:
methods = ' '.join(list(r.methods))
else:
methods = ''
urls.append((r.rule, methods, r.endpoint))
urls.sort()
return self._page_not_found(url=local.request.path, urls=urls)
tmp_file = template.get_templatefile('404'+settings.GLOBAL.TEMPLATE_SUFFIX, self.template_dirs)
if tmp_file:
response = self.render(tmp_file, {'url':local.request.path}, status=404)
else:
response = e
return response
def internal_error(self, e):
tmp_file = template.get_templatefile('500'+settings.GLOBAL.TEMPLATE_SUFFIX, self.template_dirs)
if tmp_file:
response = self.render(tmp_file, {'url':local.request.path}, status=500)
else:
response = e
log.exception(e)
return response
def prepare_request(self, request, rule):
from uliweb.utils.common import safe_import
endpoint = rule.endpoint
#bind endpoint to request
request.rule = rule
#get handler
_klass = None
if isinstance(endpoint, (str, unicode)):
mod, handler = safe_import(endpoint)
if inspect.ismethod(handler):
if not handler.im_self: #instance method
_klass = handler.im_class()
else: #class method
_klass = handler.im_self()
#if _klass is class method, then the mod should be Class
#so the real mod should be mod.__module__
mod = sys.modules[mod.__module__]
elif callable(endpoint):
handler = endpoint
mod = sys.modules[handler.__module__]
request.appname = ''
for p in self.apps:
t = p + '.'
if handler.__module__.startswith(t):
request.appname = p
break
request.function = handler.__name__
if _klass:
request.view_class = _klass.__class__.__name__
handler = getattr(_klass, handler.__name__)
else:
request.view_class = None
return mod, _klass, handler
def call_view(self, mod, cls, handler, request, response=None, wrap_result=None, args=None, kwargs=None):
#get env
wrap = wrap_result or self.wrap_result
env = self.get_view_env()
#if there is __begin__ then invoke it, if __begin__ return None, it'll
#continue running
#there is a problem about soap view, because soap view will invoke
#call_view again, so that it may cause the __begin__ or __end__ be called
#twice, so I'll remember the function in cache, so that they'll not be invoke
#twice
def _get_name(mod, name):
if isinstance(mod, types.ModuleType):
return mod.__name__ + '.' + name
else:
return cls.__module__ + '.' + cls.__class__.__name__ + '.' + name
def _process_begin(mod):
name = '__begin__'
if hasattr(mod, name):
_name = _get_name(mod, name)
if _name not in request._invokes['begin']:
request._invokes['begin'].append(_name)
f = getattr(mod, name)
return self._call_function(f, request, response, env)
def _prepare_end(mod):
name = '__end__'
if hasattr(mod, name):
_name = _get_name(mod, name)
if _name not in request._invokes['end']:
request._invokes['end'].append(_name)
return True
def _process_end(mod):
f = getattr(mod, '__end__')
return self._call_function(f, request, response, env)
if not hasattr(request, '_invokes'):
request._invokes = {'begin':[], 'end':[]}
result = _process_begin(mod)
if result is not None:
return wrap(handler, result, request, response, env)
result = _process_begin(cls)
if result is not None:
return wrap(handler, result, request, response, env)
#preprocess __end__
mod_end = _prepare_end(mod)
cls_end = _prepare_end(cls)
result = self.call_handler(handler, request, response, env, wrap, args, kwargs)
if mod_end:
result1 = _process_end(mod)
if result1 is not None:
return wrap(handler, result1, request, response, env)
if cls_end:
result1 = _process_end(cls)
if result1 is not None:
return wrap(handler, result1, request, response, env)
return result
def wrap_result(self, handler, result, request, response, env):
# #process ajax invoke, return a json response
# if request.is_xhr and isinstance(result, dict):
# result = json(result)
if isinstance(result, dict):
result = Storage(result)
if hasattr(response, 'template'):
tmpfile = response.template
else:
args = handler.func_dict.get('__template__')
if not args:
args = {'function':request.function, 'view_class':request.view_class, 'appname':request.appname}
if isinstance(args, dict):
#TEMPLATE_TEMPLATE should be two elements tuple or list, the first one will be used for view_class is not empty
#and the second one will be used for common functions
if request.view_class:
tmpfile = settings.GLOBAL.TEMPLATE_TEMPLATE[0] % args + settings.GLOBAL.TEMPLATE_SUFFIX
else:
tmpfile = settings.GLOBAL.TEMPLATE_TEMPLATE[1] % args + settings.GLOBAL.TEMPLATE_SUFFIX
else:
tmpfile = args
response.template = tmpfile
content_type = response.content_type
#if debug mode, then display a default_template
if self.debug:
d = ['default.html', self.default_template]
else:
d = None
response.write(self.template(tmpfile, result, env, default_template=d))
elif isinstance(result, (str, unicode)):
response.write(result)
elif isinstance(result, self.Response):
response = result
#add generator support 2014-1-8
elif isinstance(result, types.GeneratorType):
return make_response(result, direct_passthrough=True)
else:
response = make_response(str(result))
return response
def get_view_env(self):
#prepare local env
local_env = {}
#process before view call
dispatch.call(self, 'prepare_view_env', local_env)
local_env['application'] = __global__.application
local_env['request'] = local.request
local_env['response'] = local.response
local_env['settings'] = __global__.settings
env = Storage(self.env.to_dict())
env.update(local_env)
return env
return self.get_env(local_env)
def _call_function(self, handler, request, response, env, args=None, kwargs=None):
handler.func_globals.update(env)
# for k, v in env.items():
# handler.func_globals[k] = v
handler.func_globals['env'] = env
args = args or ()
kwargs = kwargs or {}
result = handler(*args, **kwargs)
if isinstance(result, LocalProxy) and result._obj_name == 'response':
result = local.response
return result
def call_handler(self, handler, request, response, env, wrap_result=None, args=None, kwargs=None):
wrap = wrap_result or self.wrap_result
result = self._call_function(handler, request, response, env, args, kwargs)
return wrap(handler, result, request, response, env)
def collect_modules(self, check_view=True):
modules = {}
views = set()
settings = []
inifile = pkg.resource_filename('uliweb.core', 'default_settings.ini')
settings.insert(0, inifile)
def enum_views(views_path, appname, subfolder=None, pattern=None):
if not os.path.exists(views_path):
log.error("Can't found the app %s path, please check if the path is right" % appname)
return
for f in os.listdir(views_path):
fname, ext = os.path.splitext(f)
if os.path.isfile(os.path.join(views_path, f)) and ext in ['.py', '.pyc', '.pyo'] and fname!='__init__':
if pattern:
import fnmatch
if not fnmatch.fnmatch(f, pattern):
continue
if subfolder:
views.add('.'.join([appname, subfolder, fname]))
else:
views.add('.'.join([appname, fname]))
for p in self.apps:
path = get_app_dir(p)
#deal with views
if check_view:
views_path = os.path.join(path, 'views')
if os.path.exists(views_path) and os.path.isdir(views_path):
enum_views(views_path, p, 'views')
else:
enum_views(path, p, pattern='views*')
#deal with settings
inifile =os.path.join(get_app_dir(p), 'settings.ini')
if os.path.exists(inifile):