Python:pickling locals(),还是本地人有一个更轻的表亲?

Python:pickling locals(),还是本地人有一个更轻的表亲?,python,django,django-templates,Python,Django,Django Templates,我在Django工作。在Django中,当您呈现模板时,您会向其发送一个上下文词典以替换它。因为我很懒,所以我经常使用locals()作为快捷方式,而不是发送类似于{'my_var':my_var,'var2':var2}的字典 这通常效果很好,并且避免了大量令人麻木的重复 我使用django通知在某些事件发生时发送电子邮件,比如说你收到一条私人消息。Django通知带有一个内置的队列功能,我现在正在集成该功能 但是,问题是django通知在队列时对上下文字典进行pickle处理。这就是loca

我在Django工作。在Django中,当您呈现模板时,您会向其发送一个上下文词典以替换它。因为我很懒,所以我经常使用locals()作为快捷方式,而不是发送类似于{'my_var':my_var,'var2':var2}的字典

这通常效果很好,并且避免了大量令人麻木的重复

我使用django通知在某些事件发生时发送电子邮件,比如说你收到一条私人消息。Django通知带有一个内置的队列功能,我现在正在集成该功能

但是,问题是django通知在队列时对上下文字典进行pickle处理。这就是locals()技巧失败的地方——来自locals的字典除了局部变量之外还有很多垃圾(例如,它有import和int())。当地人编的字典不难理解

我看到了三个选项:1)重写django通知的排队方法,以便在存储模板之前呈现模板(简单但有点乏味,并且具有可升级性);2)停止使用局部变量技巧,开始重复我自己的操作;3)尝试找到局部变量的较轻版本(或一种pickle局部变量的方法)

我在这里希望有人能在#3方向找到线索

如果可能与此相关,以下是我尝试使用locals()快捷方式进行pickle时遇到的错误:

TypeError: can't pickle ellipsis objects
此外,locals()的字典输出:

{
'内置''
{
“bytearray”:,
“索引器”:,
“全部”:,
“帮助”:键入help()以获取交互式帮助,
或帮助(对象)获取有关对象的帮助。,
“vars”:,
“SyntaxError”:,
“unicode”:,
“UnicodeCodeError”:,
“isinstance”:,
“版权”:Copyright(C)2001-2010 Python软件基金会。
版权所有。
版权所有(c)2000 BeOpen.com。
版权所有。
版权所有(c)1995-2001国家研究计划公司。
版权所有。
版权所有(c)1991-1995 Stichting Mathematisch Centrum,
阿姆斯特丹。
版权所有。,
“NameError”:,
“BytesWarning”:,
“dict”:,
“输入”:,
“十月”:,
“bin”:,
“系统退出”:,
“StandardError”:,
“格式”:,
“repr”:,
“已排序”:,
“假”:假,
“RuntimeWarning”:,
“列表”:,
“国际热核实验堆”:,
“重新加载”:,
“警告”:,
“\uuuu包”:无,
“圆形”:,
"dir":,,
“cmp”:,
“集”:,
“字节”:,
“减少”:,
“实习生”:,
“issubclass”:,
“省略号”:省略号,
“EOFError”:,
“本地人”:,
“BufferError”:,
“切片”:,
“FloatingPointError”:,
“总和”:,
“getattr”:,
“abs”:,
“退出”:使用exit()或Ctrl-D(即EOF)退出,
“打印”:,
"真":真,,
“未来警告”:,
“导入警告”:,
“无”:无,
“哈希”:,
“ReferenceError”:,
“len”:,
“学分”:多亏了CWI,
CNRI,
BeOpen.com,
Zope公司和数千名演员
有关支持Python开发的详细信息,请访问www.Python.org。,
“frozenset”:,
“\uuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuu,
“ord”:,
“超级”:,
":"无,,
“TypeError”:,
“许可证”:键入license()以查看完整的许可证文本,
“键盘中断”:,
“用户警告”:,
“过滤器”:,
“范围”:,
“静态方法”:,
“系统错误”:,
“BaseException”:,
"战俘":,,
“RuntimeError”:,
“浮动”:,
“MemoryError”:,
“停止迭代”:,
“全局”:,
“divmod”:,
“枚举”:,
“应用”:,
“LookupError”:,
“打开”:,
“退出”:使用quit()或Ctrl-D(即EOF)退出,
“basestring”:,
“UnicodeError”:,
“zip”:,
“十六进制”:,
“长”:,
“下一步”:,
"恐怖":,
‘chr’:,
“xrange”:,
“类型”:,
“\uuuu doc\uuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuu,
例外情况,
和其他对象。\n\n值得注意的是:None是“nil”对象;省略号表示切片中的“…”,
“例外”:,
“tuple”:,
“UnicodeTranslateError”:,
“反向”:,
“UnicodeEncodeError”:,
“IOError”:,
“hasattr”:,
“delattr”:,
“setattr”:,
“原始输入”:,
“SyntaxWarning”:,
“编译”:,
“算术错误”:,
“str”:,
“财产”:,
“GeneratorExit”:,
“int”:,
“\uuuu导入”:,
“KeyError”:,
“胁迫”:,
“PendingDeprecationWarning”:,
“文件”:,
“环境错误”:,
“联合国人权中心”:,
“id”:,
“OSError”:,
“弃用警告”:,
“min”:,
‘独角兽’:,
“execfile”:,
“任何”:,
“复杂”:,
“bool”:,
“ValueError”:,
“未实施”:未实施,
“地图”:,
“缓冲区”:,
“max”:,
“对象”:,
“TabError”:,
“可调用”:,
“零错误”:,
“eval”:,
“uuu调试”:正确,
“缩进错误”:,
“断言者错误”:,
“类方法”:,
“UnboundLocalError”:,
“未实现错误”:,
“AttributeError”:,
“飞越错误”:
},
“通知”:,
"u":,,
“用户”:
}

您可能可以将所有不在globals中的内容存储在local中。

请允许我提出一种替代使用
locals()的方法。

另一个选择是
{
    '__builtins__': 
    {
        'bytearray': <type 'bytearray'>,
         'IndexError': <type 'exceptions.IndexError'>,
         'all': <built-in function all>,
         'help': Type help() for interactive help,
         or help(object) for help about object.,
         'vars': <built-in function vars>,
         'SyntaxError': <type 'exceptions.SyntaxError'>,
         'unicode': <type 'unicode'>,
         'UnicodeDecodeError': <type 'exceptions.UnicodeDecodeError'>,
         'isinstance': <built-in function isinstance>,
         'copyright': Copyright (c) 2001-2010 Python Software Foundation.
All Rights Reserved.

Copyright (c) 2000 BeOpen.com.
All Rights Reserved.

Copyright (c) 1995-2001 Corporation for National Research Initiatives.
All Rights Reserved.

Copyright (c) 1991-1995 Stichting Mathematisch Centrum,
         Amsterdam.
All Rights Reserved.,
         'NameError': <type 'exceptions.NameError'>,
         'BytesWarning': <type 'exceptions.BytesWarning'>,
         'dict': <type 'dict'>,
         'input': <built-in function input>,
         'oct': <built-in function oct>,
         'bin': <built-in function bin>,
         'SystemExit': <type 'exceptions.SystemExit'>,
         'StandardError': <type 'exceptions.StandardError'>,
         'format': <built-in function format>,
         'repr': <built-in function repr>,
         'sorted': <built-in function sorted>,
         'False': False,
         'RuntimeWarning': <type 'exceptions.RuntimeWarning'>,
         'list': <type 'list'>,
         'iter': <built-in function iter>,
         'reload': <built-in function reload>,
         'Warning': <type 'exceptions.Warning'>,
         '__package__': None,
         'round': <built-in function round>,
         'dir': <built-in function dir>,
         'cmp': <built-in function cmp>,
         'set': <type 'set'>,
         'bytes': <type 'str'>,
         'reduce': <built-in function reduce>,
         'intern': <built-in function intern>,
         'issubclass': <built-in function issubclass>,
         'Ellipsis': Ellipsis,
         'EOFError': <type 'exceptions.EOFError'>,
         'locals': <built-in function locals>,
         'BufferError': <type 'exceptions.BufferError'>,
         'slice': <type 'slice'>,
         'FloatingPointError': <type 'exceptions.FloatingPointError'>,
         'sum': <built-in function sum>,
         'getattr': <built-in function getattr>,
         'abs': <built-in function abs>,
         'exit': Use exit() or Ctrl-D (i.e. EOF) to exit,
         'print': <built-in function print>,
         'True': True,
         'FutureWarning': <type 'exceptions.FutureWarning'>,
         'ImportWarning': <type 'exceptions.ImportWarning'>,
         'None': None,
         'hash': <built-in function hash>,
         'ReferenceError': <type 'exceptions.ReferenceError'>,
         'len': <built-in function len>,
         'credits':     Thanks to CWI,
         CNRI,
         BeOpen.com,
         Zope Corporation and a cast of thousands
    for supporting Python development.  See www.python.org for more information.,
         'frozenset': <type 'frozenset'>,
         '__name__': '__builtin__',
         'ord': <built-in function ord>,
         'super': <type 'super'>,
         '_': None,
         'TypeError': <type 'exceptions.TypeError'>,
         'license': Type license() to see the full license text,
         'KeyboardInterrupt': <type 'exceptions.KeyboardInterrupt'>,
         'UserWarning': <type 'exceptions.UserWarning'>,
         'filter': <built-in function filter>,
         'range': <built-in function range>,
         'staticmethod': <type 'staticmethod'>,
         'SystemError': <type 'exceptions.SystemError'>,
         'BaseException': <type 'exceptions.BaseException'>,
         'pow': <built-in function pow>,
         'RuntimeError': <type 'exceptions.RuntimeError'>,
         'float': <type 'float'>,
         'MemoryError': <type 'exceptions.MemoryError'>,
         'StopIteration': <type 'exceptions.StopIteration'>,
         'globals': <built-in function globals>,
         'divmod': <built-in function divmod>,
         'enumerate': <type 'enumerate'>,
         'apply': <built-in function apply>,
         'LookupError': <type 'exceptions.LookupError'>,
         'open': <built-in function open>,
         'quit': Use quit() or Ctrl-D (i.e. EOF) to exit,
         'basestring': <type 'basestring'>,
         'UnicodeError': <type 'exceptions.UnicodeError'>,
         'zip': <built-in function zip>,
         'hex': <built-in function hex>,
         'long': <type 'long'>,
         'next': <built-in function next>,
         'ImportError': <type 'exceptions.ImportError'>,
         'chr': <built-in function chr>,
         'xrange': <type 'xrange'>,
         'type': <type 'type'>,
         '__doc__': "Built-in functions,
         exceptions,
         and other objects.\n\nNoteworthy: None is the `nil' object; Ellipsis represents `...' in slices.",
         'Exception': <type 'exceptions.Exception'>,
         'tuple': <type 'tuple'>,
         'UnicodeTranslateError': <type 'exceptions.UnicodeTranslateError'>,
         'reversed': <type 'reversed'>,
         'UnicodeEncodeError': <type 'exceptions.UnicodeEncodeError'>,
         'IOError': <type 'exceptions.IOError'>,
         'hasattr': <built-in function hasattr>,
         'delattr': <built-in function delattr>,
         'setattr': <built-in function setattr>,
         'raw_input': <built-in function raw_input>,
         'SyntaxWarning': <type 'exceptions.SyntaxWarning'>,
         'compile': <built-in function compile>,
         'ArithmeticError': <type 'exceptions.ArithmeticError'>,
         'str': <type 'str'>,
         'property': <type 'property'>,
         'GeneratorExit': <type 'exceptions.GeneratorExit'>,
         'int': <type 'int'>,
         '__import__': <built-in function __import__>,
         'KeyError': <type 'exceptions.KeyError'>,
         'coerce': <built-in function coerce>,
         'PendingDeprecationWarning': <type 'exceptions.PendingDeprecationWarning'>,
         'file': <type 'file'>,
         'EnvironmentError': <type 'exceptions.EnvironmentError'>,
         'unichr': <built-in function unichr>,
         'id': <built-in function id>,
         'OSError': <type 'exceptions.OSError'>,
         'DeprecationWarning': <type 'exceptions.DeprecationWarning'>,
         'min': <built-in function min>,
         'UnicodeWarning': <type 'exceptions.UnicodeWarning'>,
         'execfile': <built-in function execfile>,
         'any': <built-in function any>,
         'complex': <type 'complex'>,
         'bool': <type 'bool'>,
         'ValueError': <type 'exceptions.ValueError'>,
         'NotImplemented': NotImplemented,
         'map': <built-in function map>,
         'buffer': <type 'buffer'>,
         'max': <built-in function max>,
         'object': <type 'object'>,
         'TabError': <type 'exceptions.TabError'>,
         'callable': <built-in function callable>,
         'ZeroDivisionError': <type 'exceptions.ZeroDivisionError'>,
         'eval': <built-in function eval>,
         '__debug__': True,
         'IndentationError': <type 'exceptions.IndentationError'>,
         'AssertionError': <type 'exceptions.AssertionError'>,
         'classmethod': <type 'classmethod'>,
         'UnboundLocalError': <type 'exceptions.UnboundLocalError'>,
         'NotImplementedError': <type 'exceptions.NotImplementedError'>,
         'AttributeError': <type 'exceptions.AttributeError'>,
         'OverflowError': <type 'exceptions.OverflowError'>
    },
     'notification': <module 'notification.models' from '/home/b/webapps/myapp/notification/models.pyc'>,
     'u': <User: abcd>,
     'User': <class 'django.contrib.auth.models.User'>
}
class Object(object):
    pass

def foo():
    result = Object()
    result.my_var = 'bar'
    your_var = 'not to be returned'
    result.var2 = 'baz' + result.my_var + len(your_var)
    return result.__dict__
def foo():
    result = {}
    result['my_var'] = my_var = 'bar'
    your_var = 'not to be returned'
    result['var2'] = var2 = 'baz' + my_var + len(your_var)
    return result
this_is_for_me = 'foo'
result['this_is_for_you'] = 'bar'
>>> import dill
>>> # this will enable python's pickle to pickle almost everything dill can pickle
>>> 
>>> # on the full set of dill's types, this usually works unless there's a generator
>>> # or an interator-type or something odd like a traceback object in locals
>>> dill.loads(dill.dumps(locals()))
>>> ...
>>> # if you get a pickling error, use dill's tools to figure out a workaround
>>> dill.detect.badobjects(your_bad_object, depth=0)
>>> dill.detect.badobjects(your_bad_object, depth=1)
>>> ...