Exemplo n.º 1
0
def test_verify_login_record_is_updated():
    # Use a fake session for this test.
    user_id = db_utils.create_user()
    sess = get_current_request().weasyl_session = create_session(user_id)
    db = d.connect()
    db.add(sess)
    db.flush()
    d.engine.execute("UPDATE login SET last_login = -1 WHERE userid = %(id)s", id=user_id)
    login.signin(get_current_request(), user_id)
    last_login = d.engine.scalar("SELECT last_login FROM login WHERE userid = %(id)s", id=user_id)
    assert last_login > -1
Exemplo n.º 2
0
def linkFrom(validator, linkFrom, instance, schema):
    # avoid circular import
    from contentbase import Item, TYPES

    linkType, linkProp = linkFrom.split('.')
    if validator.is_type(instance, "string"):
        request = get_current_request()
        base = request.root.by_item_type[linkType]
        try:
            item = find_resource(base, instance.replace(':', '%3A'))
            if item is None:
                raise KeyError()
        except KeyError:
            error = "%r not found" % instance
            yield ValidationError(error)
            return
        if not isinstance(item, Item):
            error = "%r is not a linkable resource" % instance
            yield ValidationError(error)
            return
        if linkType not in set([item.item_type] + item.base_types):
            error = "%r is not of type %s" % (instance, repr(linkType))
            yield ValidationError(error)
            return
        pass
    else:
        path = instance.get('@id')
        request = get_current_request()
        if validator._serialize:
            lv = len(validator._validated)
        if '@id' in instance:
            del instance['@id']

        # treat the link property as not required
        # because it will be filled in when the child is created/updated
        subschema = request.registry[TYPES][linkType].schema
        subschema = copy.deepcopy(subschema)
        if linkProp in subschema['required']:
            subschema['required'].remove(linkProp)

        for error in validator.descend(instance, subschema):
            yield error

        if validator._serialize:
            validated_instance = validator._validated[lv]
            del validator._validated[lv:]
            if path is not None:
                item = find_resource(request.root, path.replace(':', '%3A'))
                validated_instance['uuid'] = str(item.uuid)
            elif 'uuid' in validated_instance:  # where does this come from?
                del validated_instance['uuid']
            validator._validated[-1] = validated_instance
Exemplo n.º 3
0
def test_start_scheduler(mock):
    from papaye import start_scheduler
    config = Configurator()
    config.registry.settings = {
        'papaye.cache': 'true',
        'papaye.scheduler': 'papaye.tests.test_config:TestScheduler',
    }

    start_scheduler(config)

    get_current_request()

    assert isinstance(mock.call_args[0][0], TestScheduler)
Exemplo n.º 4
0
def test_start_scheduler_without_cache_in_configuration(mock):
    from papaye import start_scheduler
    from papaye.tasks.devices import DummyScheduler
    config = Configurator()
    config.registry.settings = {
        'papaye.cache': 'true',
    }

    start_scheduler(config)

    get_current_request()

    assert isinstance(mock.call_args[0][0], DummyScheduler)
Exemplo n.º 5
0
def task_prerun_signal(task_id, task, args, kwargs, **kwaargs):
    if hasattr(celery, "pyramid"):
        env = celery.pyramid
        env = prepare(registry=env["request"].registry)
        proper_base_url = env["request"].registry.settings["base_url"]
        tmp_request = Request.blank("/", base_url=proper_base_url)
        # ensure tasks generate url for right domain from config
        env["request"].environ["HTTP_HOST"] = tmp_request.environ["HTTP_HOST"]
        env["request"].environ["SERVER_PORT"] = tmp_request.environ["SERVER_PORT"]
        env["request"].environ["SERVER_NAME"] = tmp_request.environ["SERVER_NAME"]
        env["request"].environ["wsgi.url_scheme"] = tmp_request.environ[
            "wsgi.url_scheme"
        ]
    get_current_request().tm.begin()
Exemplo n.º 6
0
 def push(self, message):
     collection = get_current_request().db[self.__collection__]
     now = datetime.datetime.utcnow()
     message['created'] = now 
     request = get_current_request()
     for _id in self.shared_by:
         if request.user._id != _id:
             other_id = _id
     
     collection.update({'_id': self._id, 'user_data._id': other_id}, 
                       {'$push': {'messages': message},
                        '$set': {'date_modified': now },
                        '$inc': {'user_data.$.new' : 1},  
                        })
Exemplo n.º 7
0
def test_start_scheduler(mock):
    from papaye.config.startup import start_scheduler
    from papaye.config.utils import SettingsReader
    config = Configurator()
    config.registry.settings = {
        'papaye.cache': 'true',
        'papaye.scheduler': 'papaye.tests.test_config:SchedulerTest',
    }
    config.add_directive('settings_reader', lambda c: SettingsReader(c))

    start_scheduler(config)

    get_current_request()

    assert isinstance(mock.call_args[0][0], SchedulerTest)
Exemplo n.º 8
0
def test_start_scheduler_without_cache_in_configuration(mock):
    from papaye.config.startup import start_scheduler
    from papaye.tasks.devices import DummyScheduler
    from papaye.config.utils import SettingsReader
    config = Configurator()
    config.registry.settings = {
        'papaye.cache': 'true',
    }
    config.add_directive('settings_reader', lambda c: SettingsReader(c))

    start_scheduler(config)

    get_current_request()

    assert isinstance(mock.call_args[0][0], DummyScheduler)
Exemplo n.º 9
0
Arquivo: util.py Projeto: igudym/Kotti
def translate(*args, **kwargs):
    request = get_current_request()
    if request is None:
        localizer = get_localizer_for_locale_name('en')
    else:
        localizer = get_localizer(request)
    return localizer.translate(*args, **kwargs)
Exemplo n.º 10
0
    def check_password(cls, **kwargs):
        if kwargs.has_key('id'):
            user = cls.get_by_id(kwargs['id'])
        if kwargs.has_key('login'):
            user = cls.get_by_login(kwargs['login'])

        request = get_current_request()
        use_sha256 = asbool(request.registry.settings.get('apex.use_sha256'))

        if not user:
            return False

        try:
            if use_sha256:
                pw = kwargs['password']
                if CRYPTPasswordManager(SHA256CRYPT).check(user.password, pw):
                    return True
            else:
                pw = kwargs['password'] + user.salt
                if BCRYPTPasswordManager().check(user.password, pw):
                    return True
        except TypeError:
            pass

        fallback_auth = request.registry.settings.get('apex.fallback_auth')
        if fallback_auth:
            resolver = DottedNameResolver(fallback_auth.split('.', 1)[0])
            fallback = resolver.resolve(fallback_auth)
            pw = kwargs['password']
            return fallback().check(DBSession, request, user, pw)

        return False
Exemplo n.º 11
0
def mailer_send(subject="!",
                sender=None,
                recipients=[],
                body=None,
                html=None,
                attachments=[]):
    try:
        request = get_current_request()
        if sender is None:
            sender = request.registry.settings['mail.default_sender']

        mailer = get_mailer(request)
        message = Message(subject=subject,
                          sender=sender,
                          recipients=recipients,
                          body=body,
                          html=html)
        for attachment in attachments:
            attachment = Attachment(attachment.title,
                                    attachment.mimetype,
                                    attachment)
            message.attach(attachment)

        if transaction.get().status == Status.COMMITTED:
            mailer.send_immediately(message)
        else:
            mailer.send(message)

    except Exception:
        pass
Exemplo n.º 12
0
def timestruct(jinja_ctx, context, **kw):
    """Render both humanized time and accurate time.

    * show_timezone

    * target_timezone

    * source_timezone

    * format
    """

    if not context:
        return ""

    assert type(context) in (datetime.datetime, datetime.time,)

    request = jinja_ctx.get('request') or get_current_request()
    if not jinja_ctx:
        return ""

    kw = kw.copy()
    kw["time"] = context
    kw["format"] = kw.get("format") or "YYYY-MM-DD HH:mm"

    return Markup(render("core/timestruct.html", kw, request=request))
Exemplo n.º 13
0
Arquivo: store.py Projeto: mrienstra/h
def after_request(response):
    if flask.request.method == 'OPTIONS':
        in_value = response.headers.get('Access-Control-Allow-Headers', '')
        allowed = [h.strip() for h in in_value.split(',')]
        allowed.append('X-Client-ID')
        out_value = ', '.join(allowed)
        response.headers['Access-Control-Allow-Headers'] = out_value
        return response

    if 200 <= response.status_code < 300:
        match = re.match(r'^store\.(\w+)_annotation$', flask.request.endpoint)
        if match:
            request = get_current_request()

            action = match.group(1)
            if action == 'delete':
                data = json.loads(flask.request.data)
            else:
                data = json.loads(response.data)

            annotation = wrap_annotation(data)
            event = events.AnnotationEvent(request, annotation, action)

            request.registry.notify(event)
    return response
Exemplo n.º 14
0
    def get_profile(self, request=None):
        """
        Returns AuthUser.profile object, creates record if it doesn't exist.

        .. code-block:: python

           from apex.models import AuthUser

           user = AuthUser.get_by_id(1)
           profile = user.get_profile(request)

        in **development.ini**

        .. code-block:: python

           apex.auth_profile = 
        """
        if not request:
            request = get_current_request()

        auth_profile = request.registry.settings.get('apex.auth_profile')
        if auth_profile:
            resolver = DottedNameResolver(auth_profile.split('.')[0])
            profile_cls = resolver.resolve(auth_profile)
            return get_or_create(DBSession, profile_cls, auth_id=self.id)
Exemplo n.º 15
0
    def local_manager_gid(self):
        """Group id of local manager group of current authenticated member.

        Currently a user can be assigned only to one local manager group. If
        mode than one local manager group is configured, an error is raised.
        """
        config = self.root['settings']['ugm_localmanager'].attrs
        user = security.authenticated_user(get_current_request())
        if not user:
            return None
        gids = user.group_ids
        adm_gids = list()
        for gid in gids:
            rule = config.get(gid)
            if rule:
                adm_gids.append(gid)
        if len(adm_gids) == 0:
            return None
        if len(adm_gids) > 1:
            msg = (u"Authenticated member defined in local manager "
                   u"groups %s but only one management group allowed for "
                   u"each user. Please contact System Administrator in "
                   u"order to fix this problem.")
            exc = msg % ', '.join(["'%s'" % gid for gid in adm_gids])
            raise Exception(exc)
        return adm_gids[0]
Exemplo n.º 16
0
def resolve_next_date(self, args, info):
    """Return first date in the start_end interval.
    """
    request = get_current_request()
    start, end = getattr(request, 'start_end', (None, None))
    dates = occurences_start(self._root, 'dates', from_=start, until=end)
    return dates[0].date() if dates else None
Exemplo n.º 17
0
def add_renderer_globals(event):
    """ add globals to templates

    csrf_token - bare token
    csrf_token_field - hidden input field with token inserted
    flash - flash messages
    """

    request = event.get('request')
    settings = get_current_registry().settings
    template = settings['apex.apex_render_template']

    if request is None:
        request = get_current_request()

    csrf_token = request.session.get_csrf_token()

    globs = {
        'csrf_token': csrf_token,
        'csrf_token_field': '<input type="hidden" name="csrf_token" value="%s" />' % csrf_token,
        'flash': flash,
    }


    if template.endswith('.pt'):
        globs['flash_t'] = get_renderer('apex:templates/flash_template.pt').implementation()
    event.update(globs)
Exemplo n.º 18
0
 def local_manager_acl(self):
     if not self.name in self.local_manager_target_gids:
         return []
     permissions = ['view', 'manage_membership']
     return [(Allow,
              authenticated_userid(get_current_request()),
              permissions)]
Exemplo n.º 19
0
def assetmutator_source(path, **kw):
    """
    Returns the source data/contents of the mutated asset (and mutates the
    asset if needed). This is useful when you want to output inline data (e.g.
    for inline JavaScript blocks).
    
    :param path: The Pyramid asset path to process.
    :type path: string - Required
    
    :type mutator: dict or string - Optional
    :param mutator: Allows you to override/specify a specific mutator to use
                     (e.g. ``coffee``), or assign a brand new mutator
                     dictionary to be used (e.g. ``{'cmd': 'lessc', 'ext':
                     'css'}``)
    
    .. note:: Many template packages escape output by default. Consult your
              template language's syntax to output an unescaped string.
    """
    request = get_current_request()
    settings = request.registry.settings
    
    mutant = Mutator(settings, path, **kw)
    
    if not settings['assetmutator.each_request']:
        if not mutant.mutated:
            # TODO: Error?
            return None
        
        return mutant.mutated_data()
    else:
        if mutant.mutated:
            return mutant.mutated_data()
        else:
            mutant.process()
            return mutant.mutated_data()
Exemplo n.º 20
0
def assetmutator_url(path, **kw):
    """
    Returns a Pyramid :meth:`~pyramid.request.Request.static_url` of the mutated
    asset (and mutates the asset if needed).
    
    :param path: The Pyramid asset path to process.
    :type path: string - Required
    
    :type mutator: dict or string - Optional
    :param mutator: Allows you to override/specify a specific mutator to use
                     (e.g. ``coffee``), or assign a brand new mutator
                     dictionary to be used (e.g. ``{'cmd': 'lessc', 'ext':
                     'css'}``)
    """
    request = get_current_request()
    settings = request.registry.settings
    
    mutant = Mutator(settings, path, **kw)
    
    if not settings['assetmutator.each_request']:
        if not mutant.mutated:
            # TODO: Error?
            pass
        
        return request.static_url(mutant.new_path)
    else:
        if mutant.mutated:
            return request.static_url(mutant.new_path)
        else:
            return request.static_url(mutant.process())
Exemplo n.º 21
0
 def language_priors(self, translation_service):
     from .auth import User, UserLanguagePreferenceCollection
     priors = super(Post, self).language_priors(translation_service)
     creator = self.creator or AgentProfile.get(self.creator_id)
     if creator and isinstance(creator, User):
         # probably a language that the user knows
         try:
             prefs = UserLanguagePreferenceCollection(creator.id)
             known_languages = prefs.known_languages()
         except AssertionError:  # user without prefs
             from pyramid.threadlocal import get_current_request
             request = get_current_request()
             if request:
                 known_languages = [request.locale_name]
             else:
                 return priors
             known_languages = []
         known_languages = {translation_service.asKnownLocale(loc)
                            for loc in known_languages}
         priors = {k: v * (1 if k in known_languages else 0.7)
                   for (k, v) in priors.iteritems()}
         for lang in known_languages:
             if lang not in priors:
                 priors[lang] = 1
     return priors
Exemplo n.º 22
0
 def tags(self, value):
     request = get_current_request()
     root = find_root(request.context)
     ctags = IClusterTags(root, None)
     assert self.cluster
     if ctags is not None:
         ctags[self.cluster] = value
Exemplo n.º 23
0
Arquivo: api.py Projeto: nlholdem/h
def before_request():
    request = get_current_request()
    annotation_ctor = request.registry.getUtility(interfaces.IAnnotationClass)
    flask.g.annotation_class = annotation_ctor
    flask.g.auth = Authenticator(request)
    flask.g.authorize = functools.partial(authorize, request)
    flask.g.before_annotation_update = anonymize_deletes
Exemplo n.º 24
0
 def indirect_idea_content_links(self):
     from pyramid.threadlocal import get_current_request
     request = get_current_request()
     if request:
         return self.indirect_idea_content_links_with_cache()
     else:
         return self.indirect_idea_content_links_without_cache()
Exemplo n.º 25
0
def add_get_user(event):
    request = event.get('request') or threadlocal.get_current_request()

    try:
        event['user'] = request.user
    except:
        return
Exemplo n.º 26
0
    def resolve_output_to_url(self, item):
        request = get_current_request()

        # Attempt to resolve the output item. First, resolve the item if its
        # an asset spec. If it's a relative path, construct a url from the
        # environment base url, which may be an asset spec that the base class
        # cannot handle. Try to resolve this url and the item against the
        # `static_url` method.
        url = None
        package, filepath = self._split_asset_spec(item)
        if package is None:
            if not path.isabs(filepath):
                item = path.join(self.env.directory, filepath)
                url = path.join(self.env.url, filepath)
        else:
            item = path.join(package, filepath)

        if url is None:
            url = super(PyramidResolver, self).resolve_output_to_url(item)

        for attempt in (url, item):
            try:
                return request.static_url(attempt)
            except:
                pass

        return url
Exemplo n.º 27
0
def add_renderer_globals(event):
    request = event.get('request')
    if request is None:
        request = get_current_request()

    globs = {}
    event.update(globs)
Exemplo n.º 28
0
    def get_url(self, namespace, key, seconds=3600, https=False):
        """Returns a Pyramid static URL.
            If you use another web framework, please override this method.
            """
        from pyramid.threadlocal import get_current_request

        return get_current_request().static_url("/".join((self.storage_path, str(namespace), key)))
Exemplo n.º 29
0
def user_tagged_content(event):
    if ITagAddedEvent.providedBy(event):
        request = get_current_request()
        context = getattr(request, "context", None)
        if context is None:
            return
        events = find_events(context)
        if not events:
            return
        site = find_site(context)
        catalog = find_catalog(context)
        path = catalog.document_map.address_for_docid(event.item)
        tagged = find_resource(site, path)
        if tagged is None:
            return
        profile_id = event.user
        if profile_id in (None, "None"):
            return
        profile = site["profiles"][profile_id]
        info = _getInfo(profile, tagged)
        if info is None:
            return
        if info["content_type"] == "Community":
            info["flavor"] = "tagged_community"
        elif info["content_type"] == "Person":
            info["flavor"] = "tagged_profile"
        else:
            info["flavor"] = "tagged_other"
        info["operation"] = "tagged"
        info["tagname"] = event.name
        events.push(**info)
Exemplo n.º 30
0
def beforerender_subscriber(event):
    request = event['request']
    if request is None:
        request = get_current_request()
    if getattr(request, 'debug_toolbar', None) is not None:
        for panel in request.debug_toolbar.panels:
            panel.process_beforerender(event)
Exemplo n.º 31
0
 def exc_view(exc, request):
     self.assertTrue(request is other_req)
     from pyramid.threadlocal import get_current_request
     self.assertTrue(get_current_request() is other_req)
     return DummyResponse(b'foo')
Exemplo n.º 32
0
 def session(self):
     return get_session(get_current_request())
Exemplo n.º 33
0
 def test_includeme_invalid_logger(self):
     request = get_current_request()  # noqa: F841
     logging_func = self.settings["redis.sessions.func_invalid_logger"]
     raised_error = InvalidSession_DeserializationError("foo")
     # check to ensure this is an InvalidSession instance
     self.assertTrue(logging_func(raised_error))
Exemplo n.º 34
0
def getSession():
    return threadlocal.get_current_request().dbsession
Exemplo n.º 35
0
def local_arrow(dt):
    tz = get_current_request().weasyl_session.timezone
    return arrow.Arrow.fromdatetime(tz.localtime(dt))
Exemplo n.º 36
0
 def _localize(message, **kwargs):
     request = get_current_request()
     return request.localizer.translate(_translation_factory(message, **kwargs))
Exemplo n.º 37
0
def update_object_in_snapshot(args):
    uuid, xmin, snapshot_id, restart = args
    with snapshot(xmin, snapshot_id):
        request = get_current_request()
        indexer = request.registry[INDEXER]
        return indexer.update_object(request, uuid, xmin, restart)
Exemplo n.º 38
0
def _get_pyramid_request():
    if WebobBaseRequest is None:
        return None
    from pyramid.threadlocal import get_current_request
    return get_current_request()
Exemplo n.º 39
0
 def set_password(self, password):
     from pyramid.threadlocal import get_current_request
     request = get_current_request()
     self.password = request.secret_manager.get_hash_password(password)
Exemplo n.º 40
0
 def ngettext(self, ctx, *args, **kwargs):
     request = ctx.get("request") or get_current_request()
     return request.translation.ngettext(*args, **kwargs)
Exemplo n.º 41
0
def format_number(ctx, number, locale=None):
    request = ctx.get("request") or get_current_request()
    if locale is None:
        locale = request.locale
    return babel.numbers.format_number(number, locale=locale)
Exemplo n.º 42
0
 def location(self):
     request = get_current_request()
     return velruse.login_url(request, self.id)
Exemplo n.º 43
0
 def dumps(self, value):
     request = get_current_request()
     default = json_renderer._make_default(request)
     return self.serializer(value, default=default, **self.kw)
Exemplo n.º 44
0
 def localizer(self):
     request = get_current_request()
     try:
         return request.localizer
     except AttributeError:  # pragma: nocover (pyramid < 1.5)
         return i18n.get_localizer(request)
Exemplo n.º 45
0
def translate(ctx, text, *elements, **kw):
    request = ctx.get("request") or get_current_request()
    tsf = TranslationStringFactory("thinkhazard")
    localizer = get_localizer(request)
    return localizer.translate(tsf(text))
Exemplo n.º 46
0
def format_datetime(ctx, *args, **kwargs):
    request = ctx.get("request") or get_current_request()
    kwargs.setdefault("locale", request.locale)
    return babel.dates.format_datetime(*args, **kwargs)
Exemplo n.º 47
0
    def _post_process_for_output(self, model, output):
        """
        Add some extra stuff for the videographer's use.
        Legend:
            / Have already
            - Can get, somehow
            X Not there at all

        fields that Carl wants:
        / name - title of talk
        / room - "room1" if there is only one room.
        / start - datetime in some parsable format
        / duration -- int minutes or "hh:mm:ss"
        / end - datetime in some parsable format
        - authors - list of people's names.
        - contact - list of email(s) of presenters.
        X released - permission to release.
        X license - CC license
        / description - used as the description of the video
          (paragraphs are fine)
        / conf_key - PK in source database - unique, used to update this item
        / conf_url - URL of talk page
        X tags - comma separated list - search terms, including sub topics
          briefly discussed in your talk.
        """
        request = get_current_request()
        new_output = output.copy()
        new_output.update({
            # Extra fields for Carl
            'name':
            output['title'],
            'description':
            output['abstract'],
            'conf_key':
            output['id'],
            'conf_url':
            route_url('talk_get', request, id=output['id']),
        })
        schedule = {
            'room': None,
            'start': None,
            'end': None,
            'duration': None,
        }
        if model.schedule_slot:
            assert model.schedule_slot.start < model.schedule_slot.end
            duration_delta = model.schedule_slot.end - model.schedule_slot.start
            assert duration_delta.days == 0
            schedule.update({
                'room':
                model.schedule_slot.room,
                'start':
                self._local_isoformat(model.schedule_slot.start),
                'end':
                self._local_isoformat(model.schedule_slot.end),
                'duration':
                (model.schedule_slot.end - model.schedule_slot.start).seconds /
                60,
            })
        new_output.update(schedule)
        return new_output
Exemplo n.º 48
0
def clear_cache():  # only useful for tests really
    request = get_current_request()
    if request is not None:
        setattr(request, _CACHE_ATTR, None)
    _lru_cache.clear()
Exemplo n.º 49
0
def add_pyramid_paths(spec,
                      route_name,
                      request=None,
                      request_method=None,
                      operations=None,
                      **kwargs):
    """

    Adds a route and view info to spec

    :param spec:
        ApiSpec object
    :param route_name:
        Route name to inspect
    :param request:
        Request object, if `None` then `get_current_request()` will be used
    :param request_method:
        Request method predicate
    :param operations:
        Operations dict that will be used instead of introspection
    :param kwargs:
        Additional kwargs for predicate matching
    :return:

    """
    from pyramid.threadlocal import get_current_request

    if request is None:
        request = get_current_request()

    registry = request.registry
    introspector = registry.introspector
    route = introspector.get("routes", route_name)
    views = introspector.related(route)

    # needs to be rewritten to internal name
    if request_method:
        kwargs["request_methods"] = request_method
        # kwargs.setdefault('route_name', route_name)

    for view in views:
        matches = True
        for kw in kwargs.keys():
            # request_methods can be either a list of strings or a string
            # so lets normalize via sets
            if kw == "request_methods":
                if is_string(kwargs[kw]):
                    kwargs[kw] = [kwargs[kw]]
                methods = view.get(kw) or ALL_METHODS
                if is_string(methods):
                    methods = [methods]
                if not set(kwargs[kw] or []).intersection(methods):
                    matches = False
            else:
                if not view.get(kw) == kwargs[kw]:
                    matches = False

        if not matches:
            continue

        final_operations = {}

        # views can be class based
        if view.get("attr"):
            global_meta = load_operations_from_docstring(
                view["callable"].__doc__)
            if global_meta:
                final_operations.update(global_meta)
            f_view = getattr(view["callable"], view["attr"])
        # or just function callables
        else:
            f_view = view.get("callable")

        if operations is None:
            methods = view.get("request_methods")
            view_operations = load_operations_from_docstring(f_view.__doc__)
            if not view_operations:
                view_operations = {}
                if is_string(methods):
                    methods = [methods]
                if not methods:
                    methods = ALL_METHODS[:]
                operation = load_yaml_from_docstring(f_view.__doc__)
                if operation:
                    for method in methods:
                        view_operations[method.lower()] = operation
            final_operations.update(view_operations)
        else:
            final_operations = operations
        spec.add_path(route["pattern"], operations=final_operations)
Exemplo n.º 50
0
 def __init__(self):
     self.session = threadlocal.get_current_request().dbsession
Exemplo n.º 51
0
def absolutify_url(url):
    cdn_root = config_read_setting("cdn_root")
    if cdn_root and url.startswith(cdn_root):
        return url

    return urlparse.urljoin(get_current_request().application_url, url)
Exemplo n.º 52
0
def add_pyramid_paths(
    spec,
    route_name,
    request=None,
    request_method=None,
    operations=None,
    autodoc=True,
    **kwargs
):
    """

    Adds a route and view info to spec

    :param spec:
        ApiSpec object
    :param route_name:
        Route name to inspect
    :param request:
        Request object, if `None` then `get_current_request()` will be used
    :param request_method:
        Request method predicate
    :param operations:
        Operations dict that will be used instead of introspection
    :param autodoc:
        Include information about endpoints without markdown docstring
    :param kwargs:
        Additional kwargs for predicate matching
    :return:

    """
    if request is None:
        request = get_current_request()

    registry = request.registry
    introspector = registry.introspector
    route = introspector.get("routes", route_name)
    introspectables = introspector.related(route)
    ignored_view_names = kwargs.pop("ignored_view_names", None)
    # needs to be rewritten to internal name
    if request_method:
        kwargs["request_methods"] = request_method

    for maybe_view in introspectables:
        # skip excluded views/non-views
        if (
            not is_view(maybe_view)
            or not check_methods_matching(maybe_view, **kwargs)
            or should_ignore_view(maybe_view, ignored_views=ignored_view_names)
        ):
            continue

        pattern = route["pattern"]
        pattern = reformat_pattern(pattern)
        if maybe_view.get("match_param"):
            # replace route patterns that are specified in the view's match_param argument,
            # so that route URLs are unique and accurate
            match_params = MatchParamPredicate(maybe_view["match_param"], None)
            for key, value in match_params.reqs:
                pattern = pattern.replace("{%s}" % key, value)
        spec.path(
            pattern, operations=get_operations(maybe_view, operations, autodoc=autodoc)
        )
Exemplo n.º 53
0
 def test_includeme_id_generator(self):
     request = get_current_request()  # noqa: F841
     generator = self.settings["redis.sessions.id_generator"]
     self.assertEqual(generator(), 42)
Exemplo n.º 54
0
 def url(self, ):
     request = get_current_request()
     return self.get_url(request)
Exemplo n.º 55
0
def log_exc(**kwargs):
    """
    Logs an exception. This is essentially a wrapper around the current request's log_exc.
    It's provided for compatibility for methods that depended on web.ctx.log_exc().
    """
    return get_current_request().log_exc(**kwargs)
Exemplo n.º 56
0
 def test_includeme_serialize_deserialize(self):
     request = get_current_request()  # noqa: F841
     serialize = self.settings["redis.sessions.serialize"]
     deserialize = self.settings["redis.sessions.deserialize"]
     result = deserialize(serialize("test"))
     self.assertEqual(result, "test")
Exemplo n.º 57
0
 def translator(term):
     return get_localizer(get_current_request()).translate(term)
Exemplo n.º 58
0
def after_cursor_execute(conn, cursor, statement, parameters, context, executemany):
    total = time.time() - context._query_start_time
    request = get_current_request()  # TODO: There should be a better way to save this.
    if hasattr(request, 'sql_times'):
        request.sql_times.append(total)
Exemplo n.º 59
0
def add_localizer(event, request=None):
    if request is None:
        request = getattr(event, 'request', get_current_request())

    request.translate = lambda string: _(string, request=request)
Exemplo n.º 60
0
 def test_includeme_client_callable(self):
     request = get_current_request()
     get_client = self.settings["redis.sessions.client_callable"]
     self.assertEqual(get_client(request), "client")