• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Python util.get_pylons函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Python中pylons.decorators.util.get_pylons函数的典型用法代码示例。如果您正苦于以下问题:Python get_pylons函数的具体用法?Python get_pylons怎么用?Python get_pylons使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。



在下文中一共展示了get_pylons函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。

示例1: check_methods

 def check_methods(func, *args, **kwargs):
     """Wrapper for restrict"""
     if get_pylons(args).request.method not in methods:
         if get_pylons(args).request.params.get('_method') not in methods:
             log.debug("Method not allowed by restrict")
             abort(405, headers=[('Allow', ','.join(methods))])
     return func(*args, **kwargs)
开发者ID:camerontt2000,项目名称:inphosite,代码行数:7,代码来源:rest.py


示例2: dispatcher

 def dispatcher(func, self, *args, **kwargs):
     """Wrapper for dispatch_on"""
     alt_method = method_map.get(get_pylons(args).request.params.get('_method'))
     alt_method = method_map.get(get_pylons(args).request.method, alt_method)
     if alt_method:
         alt_method = getattr(self, alt_method)
         log.debug("Dispatching to %s instead", alt_method)
         return self._inspect_call(alt_method, **kwargs)
     return func(self, *args, **kwargs)
开发者ID:camerontt2000,项目名称:inphosite,代码行数:9,代码来源:rest.py


示例3: api_response

def api_response(func, *args, **kwargs):
    pylons = get_pylons(args)
    data = func(*args, **kwargs)
    format = pylons.request.params.get('format', 'json')

    if format == 'test':
        pylons.response.headers['Content-Type'] = 'text/plain'
        return pprint.pformat(data)
    elif format == 'xml':
        # a quick-dirty dict serializer
        def ser(d):
            r = ""
            for k,v in d.items():
                if isinstance(v, dict):
                    r += "<%s>%s</%s>" % (k, ser(v), k)
                elif isinstance(v, list):
                    for i in v:
                        #print k,i
                        r += ser({k:i})
                else:
                    r += "<%s>%s</%s>" % (k, escape("%s"%v), k)
            return r
        pylons.response.headers['Content-Type'] = 'text/xml'
        return '<?xml version="1.0" encoding="UTF-8"?>' + ser({'response': data}).encode('utf-8')
    pylons.response.headers['Content-Type'] = 'application/json'
    res = json.dumps(data)
    #import sys;print >> sys.stderr, res
    return res
开发者ID:jrburke,项目名称:f1,代码行数:28,代码来源:helpers.py


示例4: cacheable

def cacheable(func, *args, **kwargs):
    pylons = get_pylons(args)
    del pylons.response.headers['Pragma']
    del pylons.response.headers['Cache-Control']
    pylons.response.cache_control = {'public': None}
    
    return func(*args, **kwargs)
开发者ID:gjn,项目名称:mf-chsdi,代码行数:7,代码来源:base.py


示例5: wrapper

    def wrapper(func, *args, **kwargs):
        """Decorator Wrapper function"""
        request = get_pylons(args).request
        if request.scheme.lower() == 'https':
            return func(*args, **kwargs)
        if request.method.upper() == 'POST':
            # don't allow POSTs (raises an exception)
            abort(405, headers=[('Allow', 'GET')])

        if redirect_kwargs:
            # XXX: not a foolproof check for url_for arguments, but the
            # best we can do
            import warnings
            from routes import url_for
            warnings.warn('Calling https with url_for args is deprecated, use '
                          'https(lambda: url(*args, **kwargs)) instead',
                          DeprecationWarning, 2)
            redirect_kwargs['protocol'] = 'https'
            url = url_for(*redirect_args, **redirect_kwargs)
        elif not redirect_args:
            url = request.url
        else:
            url = redirect_args[0]
            if callable(url):
                url = url()
        # Ensure an https scheme, which also needs a host
        parts = urlparse.urlparse(url)
        url = urlparse.urlunparse(('https', parts[1] or request.host) +
                                  parts[2:])

        log.debug('Redirecting non-https request: %s to: %s',
                  request.path_info, url)
        redirect(url)
开发者ID:adrianpike,项目名称:wwscc,代码行数:33,代码来源:secure.py


示例6: wrapper

    def wrapper(func, *args, **kwargs):
        """Decorator wrapper"""
        pylons = get_pylons(args)
        log.debug("Wrapped with key: %s, expire: %s, type: %s, query_args: %s", key, expire, type, query_args)
        enabled = pylons.config.get("cache_enabled", "True")
        if not asbool(enabled):
            log.debug("Caching disabled, skipping cache lookup")
            return func(*args, **kwargs)

        if key:
            if query_args:
                key_dict = pylons.request.GET.mixed()
            else:
                key_dict = kwargs.copy()
                key_dict.update(_make_dict_from_args(func, args))

            if key != "cache_default":
                if isinstance(key, list):
                    key_dict = dict((k, key_dict[k]) for k in key)
                else:
                    key_dict = {key: key_dict[key]}
        else:
            key_dict = None

        self = None
        if args:
            self = args[0]
        namespace, cache_key = create_cache_key(func, key_dict, self)

        if type:
            b_kwargs["type"] = type

        my_cache = pylons.cache.get_cache(namespace, **b_kwargs)

        if expire == "never":
            cache_expire = None
        else:
            cache_expire = expire

        def create_func():
            log.debug("Creating new cache copy with key: %s, type: %s", cache_key, type)
            result = func(*args, **kwargs)
            glob_response = pylons.response
            headers = glob_response.headerlist
            status = glob_response.status
            full_response = dict(headers=headers, status=status, cookies=None, content=result)
            return full_response

        response = my_cache.get_value(cache_key, createfunc=create_func, expiretime=cache_expire, starttime=starttime)
        if cache_response:
            glob_response = pylons.response
            glob_response.headerlist = [header for header in response["headers"] if header[0].lower() in cache_headers]
            glob_response.status = response["status"]

        return response["content"]
开发者ID:poojapauskar,项目名称:vzcards-api,代码行数:55,代码来源:cache.py


示例7: jsonify

def jsonify(f, *args, **kwargs):
	pylons = get_pylons(args)
	pylons.response.headers['Content-Type'] = 'application/json'
	
	try:
		data = f(*args, **kwargs)
		return json.dumps(data, cls = ClassEncoder, indent = 2, sort_keys = True)
	except HTTPException, e:
		jsonError = {'status': e.status, 'message': e.detail}
		resp = Response(json.dumps(jsonError),
						status = e.status,
						content_type='application/json')
		return resp(kwargs['environ'], kwargs['start_response'])
开发者ID:mhellmic,项目名称:fts3,代码行数:13,代码来源:helpers.py


示例8: wrapper

 def wrapper(func, *args, **kwargs):
     """Decorator Wrapper function"""
     request = get_pylons(args).request
     if request.scheme.lower() == 'https':
         return func(*args, **kwargs)
     else:
         if request.method.upper() != 'POST':
             redirect_kwargs['protocol'] = 'https' # ensure https
             log.debug('Redirecting non-https request: %s to redirect '
                       'args: *%r, **%r', request.path_info, redirect_args,
                       redirect_kwargs)
             redirect_to(*redirect_args, **redirect_kwargs)
         else:
             abort(405, headers=[('Allow', 'GET')]) # don't allow POSTs.
开发者ID:douglasd,项目名称:pylons,代码行数:14,代码来源:secure.py


示例9: jsonify

def jsonify(func, *args, **kwargs):
    pylons = get_pylons(args)
    pylons.response.headers["Content-Type"] = "application/json"
    data = func(*args, **kwargs)
    if isinstance(data, (list, tuple)):
        msg = (
            "JSON responses with Array envelopes are susceptible to "
            "cross-site data leak attacks, see "
            "http://pylonshq.com/warnings/JSONArray"
        )
        warnings.warn(msg, Warning, 2)
        log.warning(msg)
    log.debug("Returning JSON wrapped action output")
    return json.dumps(data, default=object_encoder)
开发者ID:sakthi,项目名称:Kingdoms,代码行数:14,代码来源:base.py


示例10: kjsonify

def kjsonify(func, *args, **kwargs):
    """Action decorator that formats output for JSON

    Given a function that will return content, this decorator will turn
    the result into JSON, with a content-type of 'application/json' and
    output it.

    CUSTOM: On exception, raise a KJsonifyException with keys:
        - in debug mode: type, exception, trace
        - in production: exception
    """
    pylons = get_pylons(args)
    pylons.response.headers['Content-Type'] = 'application/json'
    try:
        data = func(*args, **kwargs)

        # Accept only dict objects for returned data.
        if not isinstance(data, (dict)):
            raise Exception("kjsonify: bad data: only dictionaries are accepted.")
            warnings.warn(msg, Warning, 2)
            log.warning(msg)

        # Append global messages if any.
        if len(c.glob_messages):
            data['glob_msgs'] = map(lambda x: x.to_dict(), c.glob_messages)

        return simplejson.dumps(data)

    except Exception, e:
        exceptionType, exceptionValue, exceptionTraceback = sys.exc_info()
        if config['debug']:

            # Log exception and debugging informations.
            log.debug("JSON exception:")
            for t in traceback.format_tb(exceptionTraceback):
                log.debug("%-9s: '%s'" % ( "trace", str(t) ) )
            log.debug("%-9s: '%s'" % ( "exception", str(e) ) )

            # Return ajax dictionary with exception details.
            raise KJsonifyException(str(exceptionType), str(exceptionValue), traceback.format_tb(exceptionTraceback))

        else:
            # Log exception.
            log.debug("JSON exception: '%s'" % ( str(e) ) )

            # Return generic error.
            raise KJsonifyException(str(exceptionType), 'Internal error')
开发者ID:fdgonthier,项目名称:kas,代码行数:47,代码来源:jsonify.py


示例11: json_exception_response

def json_exception_response(func, *args, **kwargs):
    try:
        return func(*args, **kwargs)
    except HTTPException:
        raise
    except Exception, e:
        log.exception("%s(%s, %s) failed", func, args, kwargs)
        #pylons = get_pylons(args)
        #pylons.response.status_int = 500
        metrics.track(get_pylons(args).request, 'unhandled-exception',
                      function=func.__name__, error=e.__class__.__name__)
        return {
            'result': None,
            'error': {
                'name': e.__class__.__name__,
                'message': str(e)
            }
        }
开发者ID:SriramBms,项目名称:f1,代码行数:18,代码来源:helpers.py


示例12: ourjsonify

def ourjsonify(func, *args, **kwargs):
    """Action decorator that formats output for JSON

    Given a function that will return content, this decorator will turn
    the result into JSON, with a content-type of 'application/json' and
    output it.
    
    """
    pylons = get_pylons(args)
    pylons.response.headers['Content-Type'] = 'application/json'
    data = func(*args, **kwargs)
    if isinstance(data, (list, tuple)):
        msg = "JSON responses with Array envelopes are susceptible to " \
              "cross-site data leak attacks, see " \
              "http://pylonshq.com/warnings/JSONArray"
        warnings.warn(msg, Warning, 2)
        log.warning(msg)
    return jsonpickle.encode(data, unpicklable=False)
开发者ID:droot,项目名称:tweetboard,代码行数:18,代码来源:helpers.py


示例13: jsonify

def jsonify(f, *args, **kwargs):
    """
    Decorates methods in the controllers, and converts the output to a JSON
    serialization

    Args:
        f:      The method to be called
        args:   Parameters for f
        kwargs: Named parameters for f

    Returns:
        A string with the JSON representation of the value returned by f()
    """
    pylons = get_pylons(args)
    pylons.response.headers['Content-Type'] = 'application/json'

    data = f(*args, **kwargs)
    return [json.dumps(data, cls=ClassEncoder, indent=2, sort_keys=True)]
开发者ID:andrea-manzi,项目名称:fts3-rest,代码行数:18,代码来源:jsonify.py


示例14: jsonify

def jsonify(func, *args, **kwargs):
    """Action decorator that formats output for JSON

    Given a function that will return content, this decorator will turn
    the result into JSON, with a content-type of 'application/json' and
    output it.

    """
    pylons = get_pylons(args)
    pylons.response.headers['Content-Type'] = 'application/json; charset=utf-8'
    data = func(*args, **kwargs)
    if isinstance(data, (list, tuple)):
        msg = "JSON responses with Array envelopes are susceptible to " \
              "cross-site data leak attacks, see " \
              "http://wiki.pylonshq.com/display/pylonsfaq/Warnings"
        warnings.warn(msg, Warning, 2)
        log.warning(msg)
    log.debug("Returning JSON wrapped action output")
    return simplejson.dumps(data, cls=JSONEncoder, encoding='utf-8')
开发者ID:AlexanderYAPPO,项目名称:pylons,代码行数:19,代码来源:__init__.py


示例15: wrapper

    def wrapper(func, *args, **kwargs):
        result = func(*args, **kwargs)

        pylons = get_pylons(args)
        if not cache_enabled:
            log.debug("Caching disabled, skipping cache lookup")
            return result

        cfg_expires = "%s.expires" % _func_cname(func)
        cache_expires = expires if expires else int(pylons.config.get(cfg_expires, 0))

        headers = pylons.response.headers
        status = pylons.response.status
        if pylons.response.status[0] not in ("4", "5"):
            if "Pragma" in headers: del headers["Pragma"]
            if "Cache-Control" in headers: del headers["Cache-Control"]
            headers["Last-Modified"] = strftime("%a, %d %b %Y %H:%M:%S GMT", gmtime())
            pylons.response.cache_expires(seconds=cache_expires)
        return result
开发者ID:AdamJensen-dk,项目名称:ckan-drupal,代码行数:19,代码来源:cache.py


示例16: authenticate_form

def authenticate_form(func, *args, **kwargs):
    """Decorator for authenticating a form
    
    This decorator uses an authorization token stored in the client's
    session for prevention of certain Cross-site request forgery (CSRF)
    attacks (See
    http://en.wikipedia.org/wiki/Cross-site_request_forgery for more
    information).

    For use with the ``webhelpers.html.secure_form`` helper functions.
    
    """
    request = get_pylons(args).request
    if authenticated_form(request.POST):
        del request.POST[secure_form.token_key]
        return func(*args, **kwargs)
    else:
        log.warn('Cross-site request forgery detected, request denied: %r '
                 'REMOTE_ADDR: %s' % (request, request.remote_addr))
        abort(403, detail=csrf_detected_message)
开发者ID:douglasd,项目名称:pylons,代码行数:20,代码来源:secure.py


示例17: wrapper

 def wrapper(func, *args, **kwargs):
     pylons = get_pylons(args)
     cb_name = pylons.request.params.get(cb)
     if cb_name is not None:
         pylons.response.headers['Content-Type'] = 'text/javascript'
     else:
         pylons.response.headers['Content-Type'] = 'application/json'
     data = func(*args, **kwargs)
     output = simplejson.dumps(data, **dumps_kwargs)
     if cb_name is not None:
         output = str(cb_name) + '(' + output + ');'
         log.debug("Returning JS wrapped action output")
     else:
         if isinstance(data, (list, tuple)):
             msg = "JSON responses with Array envelopes are susceptible to " \
                   "cross-site data leak attacks, see " \
                   "http://pylonshq.com/warnings/JSONArray"
             warnings.warn(msg, Warning, 2)
             log.warning(msg)
         log.debug("Returning JSON wrapped action output")
     return output
开发者ID:123rohan123,项目名称:mapfish,代码行数:21,代码来源:__init__.py


示例18: wrapper

    def wrapper(func, *args, **kwargs):
        """Decorator Wrapper function"""
        request = get_pylons(args).request
        if request.scheme.lower() == 'https':
            return func(*args, **kwargs)
        if request.method.upper() == 'POST':
            # don't allow POSTs (raises an exception)
            abort(405, headers=[('Allow', 'GET')])

        if url_or_callable is None:
            url = request.url
        elif callable(url_or_callable):
            url = url_or_callable()
        else:
            url = url_or_callable
        # Ensure an https scheme, which also needs a host
        parts = urlparse.urlparse(url)
        url = urlparse.urlunparse(('https', parts[1] or request.host) +
                                  parts[2:])

        log.debug('Redirecting non-https request: %s to: %s',
                  request.path_info, url)
        redirect(url)
开发者ID:AntonNguyen,项目名称:easy_api,代码行数:23,代码来源:secure.py


示例19: wrapper

    def wrapper(func, *args, **kwargs):
        """Decorator wrapper"""
        pylons = get_pylons(args)
        log.debug("Wrapped with key: %s, expire: %s, type: %s, query_args: %s",
                  key, expire, type, query_args)
        enabled = pylons.config.get("cache_enabled", "True")
        if not asbool(enabled):
            log.debug("Caching disabled, skipping cache lookup")
            return func(*args, **kwargs)

        if key:
            key_dict = kwargs.copy()
            key_dict.update(_make_dict_from_args(func, args))

            ## FIXME: if we can stop there variables from being passed to the
            # controller action (also the Genshi Markup/pickle problem is
            # fixed, see below) then we can use the stock beaker_cache.
            # Remove some system variables that can cause issues while generating cache keys
            [key_dict.pop(x, None) for x in ("pylons", "start_response", "environ")]

            if query_args:
                key_dict.update(pylons.request.GET.mixed())

            if key != "cache_default":
                if isinstance(key, list):
                    key_dict = dict((k, key_dict[k]) for k in key)
                else:
                    key_dict = {key: key_dict[key]}
        else:
            key_dict = None

        self = None
        if args:
            self = args[0]
        namespace, cache_key = create_cache_key(func, key_dict, self)

        if type:
            b_kwargs['type'] = type

        cache_obj = getattr(pylons.app_globals, 'cache', None)
        if not cache_obj:
            cache_obj = getattr(pylons, 'cache', None)
        if not cache_obj:
            raise Exception('No cache object found')
        my_cache = cache_obj.get_cache(namespace, **b_kwargs)

        if expire == "never":
            cache_expire = None
        else:
            cache_expire = expire

        def create_func():
            log.debug("Creating new cache copy with key: %s, type: %s",
                      cache_key, type)
            result = func(*args, **kwargs)
            # This is one of the two changes to the stock beaker_cache
            # decorator
            if hasattr(result, '__html__'):
                # Genshi Markup object, can not be pickled
                result = unicode(result.__html__())
            glob_response = pylons.response
            headers = glob_response.headerlist
            status = glob_response.status
            full_response = dict(headers=headers, status=status,
                                 cookies=None, content=result)
            return full_response

        response = my_cache.get_value(cache_key, createfunc=create_func,
                                      expiretime=cache_expire,
                                      starttime=starttime)
        if cache_response:
            glob_response = pylons.response
            glob_response.headerlist = [header for header in response['headers']
                                        if header[0].lower() in cache_headers]
            glob_response.status = response['status']

        return response['content']
开发者ID:Jpoudrier,项目名称:mediacore-community,代码行数:77,代码来源:decorators.py


示例20: _jsonpify

 def _jsonpify(*args, **kwargs):
     pylons = get_pylons(args)
     pylons.response.headers['Content-Type'] = 'application/json'
     data = func(*args, **kwargs)
     log.debug("Returning JSONP wrapped action output")
     return prefix + '(' + simplejson.dumps(data) + ')'
开发者ID:nous-consulting,项目名称:ututi,代码行数:6,代码来源:decorators.py



注:本文中的pylons.decorators.util.get_pylons函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python g.make_lock函数代码示例发布时间:2022-05-25
下一篇:
Python util.redirect_to函数代码示例发布时间:2022-05-25
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap