本文整理汇总了Python中pylons.decorators.util.get_pylons函数的典型用法代码示例。如果您正苦于以下问题:Python get_pylons函数的具体用法?Python get_pylons怎么用?Python get_pylons使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了get_pylons函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的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)
示例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)
示例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
示例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)
示例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)
示例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"]
示例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'])
示例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.
示例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)
示例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')
示例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)
}
}
示例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)
示例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)]
示例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')
示例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