Esempio n. 1
0
 def test_json_query(self):
     q = self.s.query(Test2)
     p = Page(q, items_per_page=1, page=1)
     res = json.loads(json_encode(p))
     assert len(res['entries']) == 1
     assert res['total'] == 2
     assert res['entries'][0]['val'] == 'fred'
Esempio n. 2
0
def abort(status_code=None, detail="", headers=None, comment=None,
          passthrough=False):
    """Aborts the request immediately by returning an HTTP exception

    In the event that the status_code is a 300 series error, the detail
    attribute will be used as the Location header should one not be
    specified in the headers attribute.

    **passthrough**
        When ``True`` instead of displaying the custom error
        document for errors or the authentication page for
        failed authorizations the response will just pass
        through as is.

        Set to ``"json"`` to send out the response body in
        JSON format.

    """
    exc = status_map[status_code](detail=detail, headers=headers,
                                  comment=comment)

    if passthrough == 'json':
        exc.content_type = 'application/json'
        exc.charset = 'utf-8'
        exc.body = tg.json_encode(dict(status=status_code,
                                       detail=str(exc))).encode('utf-8')

    if passthrough:
        tg.request.environ['tg.status_code_redirect'] = False
        tg.request.environ['tg.skip_auth_challenge'] = False

    raise exc
Esempio n. 3
0
 def test_json_query(self):
     q = self.s.query(Test2)
     p = Page(q, items_per_page=1, page=1)
     res = json.loads(json_encode(p))
     assert len(res['entries']) == 1
     assert res['total'] == 2
     assert res['entries'][0]['val'] == 'fred'
Esempio n. 4
0
    def prepare(self):
        super(RactiveWidget, self).prepare()
        self.safe_modify('attrs')
        self.attrs['id'] = self.id

        if self.value is None:
            self.value = {}

        ractive_params = dict([(prop, getattr(self, prop))
                               for prop in self.ractive_params])

        try:
            self.value = self.value.copy()
        except:
            # Value must be a dictionary and so support copy
            self.value = {}

        self.value.update(ractive_params)

        self.safe_modify('resources')
        self.resources.append(
            JSSource(src='''
document.RAWidgets.display("%(id)s", %(RactiveClass)s, %(value)s);
''' % dict(id=self.id,
           RactiveClass=self.ractive_class,
           value=json_encode(self.value))))
Esempio n. 5
0
def abort(status_code=None,
          detail="",
          headers=None,
          comment=None,
          passthrough=False,
          error_handler=False):
    """Aborts the request immediately by returning an HTTP exception

    In the event that the status_code is a 300 series error, the detail
    attribute will be used as the Location header should one not be
    specified in the headers attribute.

    **passthrough**
        When ``True`` instead of displaying the custom error
        document for errors or the authentication page for
        failed authorizations the response will just pass
        through as is.

        Set to ``"json"`` to send out the response body in
        JSON format.

    **error_handler**
        When ``True`` instead of immediately abort the request
        it will create a callable that can be used as ``@validate``
        error_handler.

        A common case is ``abort(404, error_handler=True)`` as
        ``error_handler`` for validation that retrieves objects
        from database::

            from formencode.validators import Wrapper

            @validate({'team': Wrapper(to_python=lambda value:
                                        Group.query.find({'group_name': value}).one())},
                      error_handler=abort(404, error_handler=True))
            def view_team(self, team):
                return dict(team=team)

    """
    exc = status_map[status_code](detail=detail,
                                  headers=headers,
                                  comment=comment)

    if passthrough == 'json':
        exc.content_type = 'application/json'
        exc.charset = 'utf-8'
        exc.body = tg.json_encode(dict(status=status_code,
                                       detail=str(exc))).encode('utf-8')

    def _abortion(*args, **kwargs):
        if passthrough:
            tg.request.environ['tg.status_code_redirect'] = False
            tg.request.environ['tg.skip_auth_challenge'] = True
        raise exc

    if error_handler is False:
        return _abortion()
    else:
        return _abortion
Esempio n. 6
0
 def test_json_query(self):
     q = self.WikiPage.query.find().sort([('order', ASCENDING)])
     p = Page(q, items_per_page=1, page=1)
     res = json.loads(json_encode(p))
     assert len(res['entries']) == 1
     assert res['total'] == 3
     assert res['entries'][0]['title'] == 'Hello', res['entries']
     assert res['entries'][0]['author_id'] == str(self.author._id), res['entries']
Esempio n. 7
0
 def test_json_query(self):
     q = self.WikiPage.query.find().sort([('order', ASCENDING)])
     p = Page(q, items_per_page=1, page=1)
     res = json.loads(json_encode(p))
     assert len(res['entries']) == 1
     assert res['total'] == 3
     assert res['entries'][0]['title'] == 'Hello', res['entries']
     assert res['entries'][0]['author_id'] == str(self.author._id), res['entries']
Esempio n. 8
0
File: util.py Progetto: DINKIN/tg2
def abort(status_code=None, detail="", headers=None, comment=None,
          passthrough=False, error_handler=False):
    """Aborts the request immediately by returning an HTTP exception

    In the event that the status_code is a 300 series error, the detail
    attribute will be used as the Location header should one not be
    specified in the headers attribute.

    **passthrough**
        When ``True`` instead of displaying the custom error
        document for errors or the authentication page for
        failed authorizations the response will just pass
        through as is.

        Set to ``"json"`` to send out the response body in
        JSON format.

    **error_handler**
        When ``True`` instead of immediately abort the request
        it will create a callable that can be used as ``@validate``
        error_handler.

        A common case is ``abort(404, error_handler=True)`` as
        ``error_handler`` for validation that retrieves objects
        from database::

            from formencode.validators import Wrapper

            @validate({'team': Wrapper(to_python=lambda value:
                                        Group.query.find({'group_name': value}).one())},
                      error_handler=abort(404, error_handler=True))
            def view_team(self, team):
                return dict(team=team)

    """
    exc = status_map[status_code](detail=detail, headers=headers,
                                  comment=comment)

    if passthrough == 'json':
        exc.content_type = 'application/json'
        exc.charset = 'utf-8'
        exc.body = tg.json_encode(dict(status=status_code,
                                       detail=str(exc))).encode('utf-8')

    def _abortion(*args, **kwargs):
        if passthrough:
            tg.request.environ['tg.status_code_redirect'] = False
            tg.request.environ['tg.skip_auth_challenge'] = False
        raise exc

    if error_handler is False:
        return _abortion()
    else:
        return _abortion
Esempio n. 9
0
def calendar(cal, event_sources=None, start_from=datetime.utcnow(), view='month', all_day_slot=False, slot_minutes='00:15:00',
             first_hour='08:00:00', column_format="D/M", time_format="HH:mm", first_day=0, day_to_show=8,
             slotLabelInterval='01:00:00'):
    if isinstance(first_hour, int):
        first_hour = "%s:00:00" % first_hour
    if isinstance(slot_minutes, int):
        first_hour = "00:%s:00" % slot_minutes

    if event_sources is None:
        event_sources = {'event_sources': [{'events': cal.active_events_calendar_data}]}

    if view not in ('month', 'basicWeek', 'basicDay', 'agendaWeek', 'agendaDay', 'custom_days'):
        view = 'month'

    for res in cal.events_type_info.resources:
        res.inject()

    return dict(cal=cal, values=tg.json_encode(event_sources), start_from=start_from, view=view,
                all_day_slot=all_day_slot,  slot_minutes=slot_minutes, first_hour=first_hour,
                column_format=column_format, time_format=time_format, first_day=first_day, day_to_show=day_to_show,
                slot_label_interval=slotLabelInterval)
Esempio n. 10
0
def render_json(template_name, template_vars, **kwargs):
    return tg.json_encode(template_vars)
Esempio n. 11
0
File: plugin.py Progetto: raiju/bs
def jsonp_response(**kw):
    debug('JSONP response %s' % kw, 3)
    # encode in JSONP here cauz there is a problem with custom renderer
    tg.response.headers['Content-Type'] = 'text/javascript'
    return '%s(%s)' % (kw.get('callback', 'callback'), tg.json_encode(kw))
Esempio n. 12
0
def render_json(template_name, template_vars, **kwargs):
    return tg.json_encode(template_vars)
Esempio n. 13
0
File: plugin.py Progetto: yjarosz/bs
def jsonp_response(**kw):
    debug('JSONP response %s' % kw, )
    # encode in JSONP here cauz there is a problem with custom renderer
    tg.response.headers['Content-Type'] = 'text/javascript'
    return '%s(%s)' % (kw.get('callback', 'callback'), tg.json_encode(kw))