python ast.literal_eval和datetime

python ast.literal_eval和datetime,第1张

python ast.literal_eval和datetime

跟随伊格纳西奥·巴斯克斯(Ignacio Vazquez-brams)的想法:

import astimport datetimedef parse_datetime_dict(astr,debug=False):    try: tree=ast.parse(astr)    except SyntaxError: raise ValueError(astr)    for node in ast.walk(tree):        if isinstance(node,(ast.Module,ast.Expr,ast.Dict,ast.Str,      ast.Attribute,ast.Num,ast.Name,ast.Load, ast.Tuple)): continue        if (isinstance(node,ast.Call)     and isinstance(node.func, ast.Attribute)     and node.func.attr == 'datetime'): continue        if debug: attrs=[attr for attr in dir(node) if not attr.startswith('__')] print(node) for attrname in attrs:     print('    {k} ==> {v}'.format(k=attrname,v=getattr(node,attrname)))        raise ValueError(astr)    return eval(astr)good_strings=["{'the_datetime': datetime.datetime(2010, 11, 21, 0, 56, 58)}"]bad_strings=["__import__('os'); os.unlink",  "import os; os.unlink",  "import(os)", # SyntaxError  ]for astr in good_strings:    result=parse_datetime_dict(astr)        print('{s} ... [PASSED]'.format(s=astr))for astr in bad_strings:    try:        result=parse_datetime_dict(astr)    except ValueError:        print('{s} ... [REJECTED]'.format(s=astr))    else:        sys.exit('ERROR: failed to catch {s!r}'.format(s=astr))

产量

{'the_datetime': datetime.datetime(2010, 11, 21, 0, 56, 58)} ... [PASSED]__import__('os'); os.unlink ... [REJECTED]import os; os.unlink ... [REJECTED]import(os) ... [REJECTED]


欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5630748.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-15
下一篇 2022-12-15

发表评论

登录后才能评论

评论列表(0条)

保存