##// END OF EJS Templates
requests: cleaned / unified way of handling requests generation from non-web scope....
super-admin -
r4873:d49e3bd8 default
parent child Browse files
Show More
@@ -381,15 +381,6 b' def includeme(config, auth_resources=Non'
381 config.add_subscriber(write_js_routes_if_enabled,
381 config.add_subscriber(write_js_routes_if_enabled,
382 pyramid.events.ApplicationCreated)
382 pyramid.events.ApplicationCreated)
383
383
384 # request custom methods
385 config.add_request_method(
386 'rhodecode.lib.partial_renderer.get_partial_renderer',
387 'get_partial_renderer')
388
389 config.add_request_method(
390 'rhodecode.lib.request_counter.get_request_counter',
391 'request_count')
392
393 # Set the authorization policy.
384 # Set the authorization policy.
394 authz_policy = ACLAuthorizationPolicy()
385 authz_policy = ACLAuthorizationPolicy()
395 config.set_authorization_policy(authz_policy)
386 config.set_authorization_policy(authz_policy)
@@ -35,7 +35,6 b' from paste.httpexceptions import HTTPUna'
35 from paste.httpheaders import WWW_AUTHENTICATE, AUTHORIZATION
35 from paste.httpheaders import WWW_AUTHENTICATE, AUTHORIZATION
36
36
37 import rhodecode
37 import rhodecode
38 from rhodecode.apps._base import TemplateArgs
39 from rhodecode.authentication.base import VCS_TYPE
38 from rhodecode.authentication.base import VCS_TYPE
40 from rhodecode.lib import auth, utils2
39 from rhodecode.lib import auth, utils2
41 from rhodecode.lib import helpers as h
40 from rhodecode.lib import helpers as h
@@ -460,12 +459,7 b' def attach_context_attributes(context, r'
460 context.rhodecode_user = request.rpc_user
459 context.rhodecode_user = request.rpc_user
461
460
462 # attach the whole call context to the request
461 # attach the whole call context to the request
463 # use set_call_context method if request has it
464 # sometimes in Celery context requests is "different"
465 if hasattr(request, 'set_call_context'):
466 request.set_call_context(context)
462 request.set_call_context(context)
467 else:
468 request.call_context = context
469
463
470
464
471 def get_auth_user(request):
465 def get_auth_user(request):
@@ -577,9 +571,9 b' def add_events_routes(config):'
577 pattern='/_hovercard/commit/{repo_name}/{commit_id}')
571 pattern='/_hovercard/commit/{repo_name}/{commit_id}')
578
572
579
573
580 def bootstrap_config(request):
574 def bootstrap_config(request, registry_name='RcTestRegistry'):
581 import pyramid.testing
575 import pyramid.testing
582 registry = pyramid.testing.Registry('RcTestRegistry')
576 registry = pyramid.testing.Registry(registry_name)
583
577
584 config = pyramid.testing.setUp(registry=registry, request=request)
578 config = pyramid.testing.setUp(registry=registry, request=request)
585
579
@@ -594,42 +588,24 b' def bootstrap_config(request):'
594
588
595
589
596 def bootstrap_request(**kwargs):
590 def bootstrap_request(**kwargs):
597 import pyramid.testing
591 """
592 Returns a thin version of Request Object that is used in non-web context like testing/celery
593 """
598
594
599 class TestRequest(pyramid.testing.DummyRequest):
595 import pyramid.testing
596 from rhodecode.lib.request import ThinRequest as _ThinRequest
597
598 class ThinRequest(_ThinRequest):
600 application_url = kwargs.pop('application_url', 'http://example.com')
599 application_url = kwargs.pop('application_url', 'http://example.com')
601 host = kwargs.pop('host', 'example.com:80')
600 host = kwargs.pop('host', 'example.com:80')
602 domain = kwargs.pop('domain', 'example.com')
601 domain = kwargs.pop('domain', 'example.com')
603
602
604 def translate(self, msg):
603 class ThinSession(pyramid.testing.DummySession):
605 return msg
606
607 def plularize(self, singular, plural, n):
608 return singular
609
610 def get_partial_renderer(self, tmpl_name):
611
612 from rhodecode.lib.partial_renderer import get_partial_renderer
613 return get_partial_renderer(request=self, tmpl_name=tmpl_name)
614
615 _call_context = TemplateArgs()
616 _call_context.visual = TemplateArgs()
617 _call_context.visual.show_sha_length = 12
618 _call_context.visual.show_revision_number = True
619
620 @property
621 def call_context(self):
622 return self._call_context
623
624 def set_call_context(self, new_context):
625 self._call_context = new_context
626
627 class TestDummySession(pyramid.testing.DummySession):
628 def save(*arg, **kw):
604 def save(*arg, **kw):
629 pass
605 pass
630
606
631 request = TestRequest(**kwargs)
607 request = ThinRequest(**kwargs)
632 request.session = TestDummySession()
608 request.session = ThinSession()
633
609
634 return request
610 return request
635
611
@@ -45,7 +45,7 b' import rhodecode'
45 from rhodecode.lib.auth import AuthUser
45 from rhodecode.lib.auth import AuthUser
46 from rhodecode.lib.celerylib.utils import parse_ini_vars, ping_db
46 from rhodecode.lib.celerylib.utils import parse_ini_vars, ping_db
47 from rhodecode.lib.ext_json import json
47 from rhodecode.lib.ext_json import json
48 from rhodecode.lib.pyramid_utils import bootstrap, setup_logging, prepare_request
48 from rhodecode.lib.pyramid_utils import bootstrap, setup_logging
49 from rhodecode.lib.utils2 import str2bool
49 from rhodecode.lib.utils2 import str2bool
50 from rhodecode.model import meta
50 from rhodecode.model import meta
51
51
@@ -271,10 +271,20 b' class RequestContextTask(Task):'
271 link=None, link_error=None, shadow=None, **options):
271 link=None, link_error=None, shadow=None, **options):
272 """ queue the job to run (we are in web request context here) """
272 """ queue the job to run (we are in web request context here) """
273
273
274 req = get_current_request()
274 req = self.app.conf['PYRAMID_REQUEST'] or get_current_request()
275
275 log.debug('Running Task with class: %s. Request Class: %s',
276 log.debug('Running Task with class: %s. Request Class: %s',
276 self.__class__, req.__class__)
277 self.__class__, req.__class__)
277
278
279 proxy_data = getattr(self.request, 'rhodecode_proxy_data', None)
280 log.debug('celery proxy data:%r', proxy_data)
281
282 user_id = None
283 ip_addr = None
284 if proxy_data:
285 user_id = proxy_data['auth_user']['user_id']
286 ip_addr = proxy_data['auth_user']['ip_addr']
287
278 # web case
288 # web case
279 if hasattr(req, 'user'):
289 if hasattr(req, 'user'):
280 ip_addr = req.user.ip_addr
290 ip_addr = req.user.ip_addr
@@ -285,12 +295,16 b' class RequestContextTask(Task):'
285 ip_addr = req.rpc_user.ip_addr
295 ip_addr = req.rpc_user.ip_addr
286 user_id = req.rpc_user.user_id
296 user_id = req.rpc_user.user_id
287 else:
297 else:
298 if user_id and ip_addr:
299 log.debug('Using data from celery proxy user')
300
301 else:
288 raise Exception(
302 raise Exception(
289 'Unable to fetch required data from request: {}. \n'
303 'Unable to fetch required data from request: {}. \n'
290 'This task is required to be executed from context of '
304 'This task is required to be executed from context of '
291 'request in a webapp. Task: {}'.format(
305 'request in a webapp. Task: {}'.format(
292 repr(req),
306 repr(req),
293 self
307 self.__class__
294 )
308 )
295 )
309 )
296
310
@@ -311,19 +325,3 b' class RequestContextTask(Task):'
311
325
312 return super(RequestContextTask, self).apply_async(
326 return super(RequestContextTask, self).apply_async(
313 args, kwargs, task_id, producer, link, link_error, shadow, **options)
327 args, kwargs, task_id, producer, link, link_error, shadow, **options)
314
315 def __call__(self, *args, **kwargs):
316 """ rebuild the context and then run task on celery worker """
317
318 proxy_data = getattr(self.request, 'rhodecode_proxy_data', None)
319 if not proxy_data:
320 return super(RequestContextTask, self).__call__(*args, **kwargs)
321
322 log.debug('using celery proxy data to run task: %r', proxy_data)
323 # re-inject and register threadlocals for proper routing support
324 request = prepare_request(proxy_data['environ'])
325 request.user = AuthUser(user_id=proxy_data['auth_user']['user_id'],
326 ip_addr=proxy_data['auth_user']['ip_addr'])
327
328 return super(RequestContextTask, self).__call__(*args, **kwargs)
329
@@ -37,24 +37,7 b' def get_app_config(ini_path):'
37 return appconfig('config:{}'.format(ini_path), relative_to=os.getcwd())
37 return appconfig('config:{}'.format(ini_path), relative_to=os.getcwd())
38
38
39
39
40 class BootstrappedRequest(Request):
40 def bootstrap(config_uri, options=None, env=None):
41 """
42 Special version of Request Which has some available methods like in pyramid.
43 Some code (used for template rendering) requires this, and we unsure it's present.
44 """
45
46 def translate(self, msg):
47 return msg
48
49 def plularize(self, singular, plural, n):
50 return singular
51
52 def get_partial_renderer(self, tmpl_name):
53 from rhodecode.lib.partial_renderer import get_partial_renderer
54 return get_partial_renderer(request=self, tmpl_name=tmpl_name)
55
56
57 def bootstrap(config_uri, request=None, options=None, env=None):
58 if env:
41 if env:
59 os.environ.update(env)
42 os.environ.update(env)
60
43
@@ -65,12 +48,7 b' def bootstrap(config_uri, request=None, '
65 except (configparser.NoSectionError, configparser.NoOptionError):
48 except (configparser.NoSectionError, configparser.NoOptionError):
66 pass
49 pass
67
50
68 request = request or BootstrappedRequest.blank('/', base_url=base_url)
51 request = Request.blank('/', base_url=base_url)
69
52
70 return pyramid_bootstrap(config_uri, request=request, options=options)
53 return pyramid_bootstrap(config_uri, request=request, options=options)
71
54
72
73 def prepare_request(environ):
74 request = Request.blank('/', environ=environ)
75 prepare(request) # set pyramid threadlocal request
76 return request
@@ -19,13 +19,24 b''
19 # and proprietary license terms, please see https://rhodecode.com/licenses/
19 # and proprietary license terms, please see https://rhodecode.com/licenses/
20
20
21 from uuid import uuid4
21 from uuid import uuid4
22 import pyramid.testing
22 from pyramid.decorator import reify
23 from pyramid.decorator import reify
23 from pyramid.request import Request as _Request
24 from pyramid.request import Request as _Request
24 from rhodecode.translation import _ as tsf
25 from rhodecode.translation import _ as tsf
26 from rhodecode.lib.utils2 import StrictAttributeDict
27
28
29 class TemplateArgs(StrictAttributeDict):
30 pass
25
31
26
32
27 class Request(_Request):
33 # Base Class with DummyMethods, testing / CLI scripts
34 class RequestBase(object):
28 _req_id_bucket = list()
35 _req_id_bucket = list()
36 _call_context = TemplateArgs()
37 _call_context.visual = TemplateArgs()
38 _call_context.visual.show_sha_length = 12
39 _call_context.visual.show_revision_number = True
29
40
30 @reify
41 @reify
31 def req_id(self):
42 def req_id(self):
@@ -38,6 +49,47 b' class Request(_Request):'
38 def req_id_records_init(self):
49 def req_id_records_init(self):
39 self._req_id_bucket = list()
50 self._req_id_bucket = list()
40
51
52 def translate(self, *args, **kwargs):
53 raise NotImplementedError()
54
55 def plularize(self, *args, **kwargs):
56 raise NotImplementedError()
57
58 def get_partial_renderer(self, tmpl_name):
59 raise NotImplementedError()
60
61 @property
62 def call_context(self):
63 return self._call_context
64
65 def set_call_context(self, new_context):
66 self._call_context = new_context
67
68
69 # for thin non-web/cli etc
70 class ThinRequest(RequestBase, pyramid.testing.DummyRequest):
71
72 def translate(self, msg):
73 return msg
74
75 def plularize(self, singular, plural, n):
76 return singular
77
78 def get_partial_renderer(self, tmpl_name):
79 from rhodecode.lib.partial_renderer import get_partial_renderer
80 return get_partial_renderer(request=self, tmpl_name=tmpl_name)
81
82
83 # for real-web-based
84 class RealRequest(RequestBase, _Request):
85 def get_partial_renderer(self, tmpl_name):
86 from rhodecode.lib.partial_renderer import get_partial_renderer
87 return get_partial_renderer(request=self, tmpl_name=tmpl_name)
88
89 def request_count(self):
90 from rhodecode.lib.request_counter import get_request_counter
91 return get_request_counter()
92
41 def plularize(self, *args, **kwargs):
93 def plularize(self, *args, **kwargs):
42 return self.localizer.pluralize(*args, **kwargs)
94 return self.localizer.pluralize(*args, **kwargs)
43
95
@@ -48,3 +100,10 b' class Request(_Request):'
48 return localizer.translate(tsf(*_args, **_kwargs))
100 return localizer.translate(tsf(*_args, **_kwargs))
49
101
50 return auto_translate(*args, **kwargs)
102 return auto_translate(*args, **kwargs)
103
104
105 class Request(RealRequest):
106 """
107 This is the main request object used in web-context
108 """
109 pass
@@ -21,7 +21,7 b''
21 counter = 0
21 counter = 0
22
22
23
23
24 def get_request_counter(request):
24 def get_request_counter():
25 global counter
25 global counter
26 counter += 1
26 counter += 1
27 return counter
27 return counter
General Comments 0
You need to be logged in to leave comments. Login now