Skip to content

Instantly share code, notes, and snippets.

@MOON-CLJ
Last active December 14, 2015 16:19
Show Gist options
  • Save MOON-CLJ/5114072 to your computer and use it in GitHub Desktop.
Save MOON-CLJ/5114072 to your computer and use it in GitHub Desktop.
some python usage snippet
3,
def timeit(method):
def timed(*args, **kw):
ts = time()
result = method(*args, **kw)
te = time()
logging.info('%r %2.2f sec' % (method.__name__, te-ts))
return result
return timed
def pretty_json(f):
@wraps(f)
def decorated(*args, **kwargs):
pretty_print = request.args.get('pretty', 0)
if pretty_print and pretty_print.isdigit():
pretty_print = int(pretty_print)
js, status, mimetype = f(*args, **kwargs)
if pretty_print:
resp = jsonify(**js)
resp.status_code = status
return resp
else:
return Response(json.dumps(js), status, mimetype=mimetype)
return decorated
def http_method(methods=None):
def decorator(f):
def decorated(*args, **kwargs):
if methods is not None:
for arg in args:
if isinstance(arg, quixote.http_request.HTTPRequest):
request = arg
break
if request.method in methods:
return f(*args, **kwargs)
else:
raise TraversalError()
return f(*args, **kwargs)
return decorated
return decorator
1,
>>> def f1():
... def f2():
... pass
... f2.__name__ = 'ehe'
... return f2
...
>>> f1()
<function ehe at 0x10ef761b8>
>>> def f1():
... def f2():
... pass
... return f2
...
>>> f1()
<function f2 at 0x10ef71b18>
2,
>>> class f:
... dumps = lambda self: `self`
...
>>> f().dumps()
'<__main__.f instance at 0x10fb8df38>'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment