def djangoURLPatterns(self): """Returns the URL patterns for the tasks in this module """ patterns = [ django_url(r'^tasks/gsoc/accept_proposals/main$', self.convertProposals), django_url(r'^tasks/gsoc/accept_proposals/accept$', self.acceptProposals), django_url(r'^tasks/gsoc/accept_proposals/status$', self.status), django_url(r'^tasks/gsoc/accept_proposals/reject$', self.rejectProposals)] return patterns
def djangoURLPatterns(self): """Returns the URL patterns for the tasks in this module. """ patterns = [ django_url(r'^tasks/gsoc/proposal_duplicates/start$', self.start, name='proposal_duplicates_task_start'), django_url(r'^tasks/gsoc/proposal_duplicates/calculate$', self.calculate, name='proposal_duplicates_task_calculate'), ] return patterns
def djangoURLPatterns(self): return [ url(r'document/show/%s$' % gsoc_url_patterns.DOCUMENT, self, name='show_gsoc_document'), url(r'document/show/%s$' % gsoc_url_patterns.ORG_DOCUMENT, self, name='show_gsoc_document'), django_url(r'^document/show/%s$' % gsoc_url_patterns.DOCUMENT, self), django_url(r'^document/show/%s$' % gsoc_url_patterns.ORG_DOCUMENT, self), ]
def url(*args, **kwargs): if "js" not in kwargs: return django_url(*args, **kwargs) if "name" not in kwargs: raise ValueError("url name attribute required for js parameter") name = pythonize_name(kwargs["name"]) for subdomain in subdomains: subsite = JS_URLS.get(subdomain, {}) subsite[name] = kwargs["js"] JS_URLS[subdomain] = subsite kwargs.pop("js") return django_url(*args, **kwargs)
def djangoURLPatterns(self): """Returns the URL patterns for the tasks in this module """ patterns = [ django_url(r'^tasks/gsoc/shipment_tracking/sync/start$', self.startShipmentSync, name=url_names.GSOC_SHIPMENT_TASK_START), django_url(r'^tasks/gsoc/shipment_tracking/sync/continue$', self.continueShipmentSync, name=url_names.GSOC_SHIPMENT_TASK_CONTINUE), ] return patterns
def include_urls(self): urls = list() for url in self.urls: if isinstance(url, UrlInfo): if hasattr(url.view, "as_view"): urls.append(django_url(url.path, url.view.as_view(**url.initkwargs), name=url.name)) else: urls.append(django_url(url.path, url.view, url.initkwargs, url.name)) else: collection = url.collection_class(instance_namespace=url.instance_namespace, **url.initkwargs) include_urls = collection.include_urls() urls.append((url.path, include_urls)) return include(patterns("", *urls), self._application_namespace, self.instance_namespace)
def djangoURLPatterns(self): """Returns the URL patterns for the tasks in this module. """ return [ django_url(r'^tasks/mail/send_mail$', self.sendMail, name='send_email_task'), ]
def url(regex, view, kwargs=None, name=None): if callable(view) and hasattr(view, '__name__'): view_name = "%s.%s" % (view.__module__, view.__name__) else: view_name = regex if name: branch = 'name' elif isinstance(view, (list, tuple)): branch = 'list' elif isinstance(view, six.string_types): branch = 'string' name = view elif callable(view) and hasattr(view, '__name__'): branch = 'callable' name = view_name elif isinstance(view, View): branch = 'view' elif isclass(view) or hasattr(view, '__class__'): branch = 'class' else: branch = 'notimpl' raise NotImplementedError("Auto-named url from view of type %s: %s" % (type(view), view)) if branch == 'name': # List explicit url names with accompanying view dotted-path: #debug.say("%s %s" % (view_name, name)) pass if name: branch = branch # silent pyflakes #debug.show('branch') #debug.show('name') pass return django_url(regex, view, kwargs=kwargs, name=name)
def paramed_decorator(func): @functools.wraps(func) def decorated(self, *args, **kwargs): return func(self, *args, **kwargs) url_key = func.__module__ + url_pattern mapping = url_mapping.get(url_key, None) if mapping is None: url_mapping.update({url_key: {}}) if type(method) in (list, tuple, set): for m in method: url_mapping[url_key].update({m: decorated}) else: url_mapping[url_key].update({method: decorated}) module = sys.modules[func.__module__] if not hasattr(module, 'urlpatterns'): module.urlpatterns = patterns('', ) module.urlpatterns += \ patterns('', django_url(url_pattern, url_dispatch, {'url_pattern': url_key, 'is_json': is_json}, *p_args, **p_kwargs), ) return decorated
def test_behave_like_default_url_function(self): default = django_url(*self.args, **self.kwargs) new = url(*self.args, **self.kwargs) self.assertEqual(default._callback, new._callback) self.assertEqual(default.regex, new.regex) self.assertEqual(default.default_args, new.default_args) self.assertEqual(default.name, new.name)
def url(self, regex, view, kwargs=None, name=None, prefix=''): """ Modifies url's url pattern view and name only. """ url_args = self._resolve(regex, view, kwargs, name, prefix) url_obj = django_url(*url_args) self._add_child(url_obj) return url_obj
def djangoURLPatterns(self): """See base.RequestHandler.getDjangoURLPatterns for specification.""" callback_path = decorator.callback_path.lstrip('/') return [ django_url(callback_path, self, name=url_names.GSOC_PICKER_CALLBACK), ]
def url(regex, view, kwargs=None, name=None, prefix=''): """ Shortcut for ``url`` method of current scope. Acts like native django's ``url`` if is defined outside scope. """ scope = Scope.get_current() url_args = (regex, view, kwargs, name, prefix) return scope.url(*url_args) if scope else django_url(*url_args)
def url(regex, view, kwargs=None, name=None, prefix="", view_attrs=None): """ this is a passthrough to Django's url function that also accepts a view_attrs keyword argument this allows view_attrs to be attached to Django's URL Regex resolver """ url_object = django_url(regex, view, kwargs, name, prefix) url_object.view_attrs = view_attrs return url_object
def __call__(self, f): self.slug = self.slug or f.__name__ self.f = f @wraps(f) def wrapped_f(request, *args, **kwargs): self.request = request try: self.after_request_set() for auth_func in self.auth_checks: response = auth_func(request) if response: return response after_auth_result = self.after_auth() if isinstance(after_auth_result, Response): return after_auth_result self.get_data() try: self.validate_data() except ValidationError as e: return self.error(BadRequest(message=str(e), extra=e.errors)) kwargs['request'] = request self.before_view() result = f(self.data, *args, **kwargs) except WebError as e: return self.error(e) except Exception as e: message = 'Unexpected API error' logger.error(message, exc_info=True) return self.error(WebError(message=message)) if result is None: if self.opt: return self.response('null') else: return self.error(UnexpectedResult()) if isinstance(result, Response): return result elif not self.result_spec: return self.response(ujson.dumps(result)) elif not isinstance(result, self.result_spec): return self.error(UnexpectedResult()) else: return self.response(self.result_spec.dumps(result)) if self.url: urlconf = __import__(settings.ROOT_URLCONF, {}, {}, ['']) urlconf.urlpatterns.append(django_url(self.url, wrapped_f, name=self.slug)) return wrapped_f
def djangoURLPatterns(self): """Returns the list of tuples for containing URL to view method mapping. """ return [ url(r'homepage/%s$' % url_patterns.PROGRAM, self, name='gsoc_homepage'), url(r'program/home/%s$' % url_patterns.PROGRAM, self), django_url(r'^program/home/%s$' % url_patterns.PROGRAM, self), ]
def url(pattern, view, kwargs=None, name=None, prefix='', constraints={}): ''' url('/path/:id/to/:something/', some_view, constraints={'id': r'\d{4}'}) ''' def convert(match): name = match.group(1) default = r'\d+' if name.endswith('id') else r'\w+' return r"(?P<%s>%s)%s" %(name, constraints.get(name, default), match.group(2) or '') url_pattern = re.sub(r':([a-z\_]+)(/)?', convert, pattern) return django_url(url_pattern, view, kwargs, name, prefix)
def _wrapper(cls): if module: if 'urlpatterns' not in module.__dict__: module.urlpatterns = [] view = cls.as_view() view_name = kwargs.get('name') or cls.__name__ url_kwargs = dict(kwargs) url_kwargs['name'] = view_name for regex in regexes: module.urlpatterns += patterns( '', django_url(regex, view, **url_kwargs)) return cls
def __call__(self, f): self.slug = self.slug or f.__name__ self.f = f @wraps(f) def wrapped_f(request, *args, **kwargs): self.request = request view_result = error = None self.request_id = request.META.get("HTTP_REQUEST_ID") self.format = request.META.get("HTTP_ACCEPT") try: if self.format not in self.ACCEPTED_FORMATS: raise BaseError(code=BaseError.ERROR_UNKNOWN_ACCEPT) self.auth_check() self._get_data() self._validate_data() kwargs["request"] = request view_result = f(self.data, *args, **kwargs) except BaseError as e: error = e except Exception as e: self._log_error(msg=str(e)) error = unknown_error() if error: result = BaseResult(error=error) status = 500 else: status = 200 if isinstance(view_result, HttpResponse): return view_result result = BaseResult(data=view_result) body = result.dumps(result) if self.format == self.ACCEPT_JSON: return HttpResponse(body, status=status, content_type=self.format) else: return HttpResponse(body, status=status, content_type=self.ACCEPT_JSON) if self.url: urlconf = __import__(settings.ROOT_URLCONF, {}, {}, [""]) url = django_url(self.url, wrapped_f, name=self.slug) urlconf.urlpatterns.append(url) return wrapped_f
def url(regex, view, healthcheck=None, **kwargs): """ Drop-in replacement for django.conf.urls.url to create and update a Cronitor healthcheck when your app restarts. See https://cronitor.io/docs/django-health-checks for details. regex (str): Route regex, passed to `django.conf.urls.url()` view (mixed): Attached view for this route, passed to `django.conf.urls.url()` healthcheck (Healthcheck): Define your healthcheck with a `Healthcheck()` instance. :return RegexURLPattern """ if isinstance(healthcheck, Healthcheck): if isinstance(view, (list, tuple)): if settings.DEBUG: raise HealthcheckError( 'Healthchecks must be defined on individual routes') else: healthcheck.route = kwargs.get('name') Client.enqueue(healthcheck) return django_url(regex, view, **kwargs)
def djangoURLPatterns(self): return [ django_url(r'^site/edit$', self, name='edit_site_settings'), ]
def djangoURLPatterns(self): """See base.RequestHandler.getDjangoURLPatterns for specification.""" return [django_url(r'^$', self, name='landing_page')]
def djangoURLPatterns(self): return [ django_url(r'^(login)$', self, name='login'), django_url(r'^(logout)$', self, name='logout'), ]
def url(pat, target, **kwargs): return django_url(pat, target, {'data': datastore}, **kwargs)
def url(prefix, regex, view, kwargs=None, name=None): """Constructs an url pattern prefixed with an arbitrary prefix Args: see django.conf.urls.url """ return django_url('^%s/%s' % (prefix, regex), view, kwargs=kwargs, name=name)
def urlcls(regex, cls, **kw): url_obj = django_url(regex, cls.as_view(), **kw) url_obj.viewcls = cls return url_obj
def djangoURLPatterns(self): return [ django_url(r'^user/edit', self, name='edit_user'), ]
def url(regex, view, kwargs=None, name=None): """Constructs an url pattern prefixed with ^gsoc/. Args: see django.conf.urls.url """ return django_url('^gsoc/%s' % regex, view, kwargs=kwargs, name=name)
def construct(self, regex, view, kwargs=None, name=None): """See url_patterns.UrlPatternConstructor.construct for specification.""" return django_url('^gci/%s' % regex, view, kwargs=kwargs, name=name)
def include_url(path, *args, **kwargs): return django_url('^' + route(path), *args, **kwargs)
app_handler_patterns = harvester.get_handler_patterns() app_http_handler_patterns = app_handler_patterns['http_handler_patterns'] app_ws_handler_patterns = app_handler_patterns['ws_handler_patterns'] ws_routing_patterns = [] for namespace, urls in app_ws_patterns.items(): for url in urls: ws_routing_patterns.append(url) http_routing_patterns = [] for namespace, urls in app_http_handler_patterns.items(): for url in urls: http_routing_patterns.append(url) for namespace, urls in app_ws_handler_patterns.items(): for url in urls: ws_routing_patterns.append(url) application = ProtocolTypeRouter({ # 'http' -> django views are added automatically 'websocket': AuthMiddlewareStack(URLRouter(ws_routing_patterns)) }) if http_routing_patterns: http_routing_patterns.append(django_url(r'', AsgiHandler)) application.application_mapping['http'] = AuthMiddlewareStack( URLRouter(http_routing_patterns))
def url(regex, view, kwargs=None, name=None): """Constructs an url pattern prefixed with ^gci/. Args: see django.conf.urls.url """ return django_url('^gci/%s' % regex, view, kwargs=kwargs, name=name)
def construct(self, regex, view, kwargs=None, name=None): """See url_patterns.UrlPatternConstructor.construct for specification.""" return django_url('^gsoc/%s' % regex, view, kwargs=kwargs, name=name)
def djangoURLPatterns(self): return [ django_url(r'^user/create$', self, name='create_user'), ]
def endpoint_url(path, *args, **kwargs): return django_url('^%s$' % route(path), *args, **kwargs)