在 django 中创建单例,或以任何其他方式为全局、每个请求可用对象创建单例
在开发“小部件”(渲染的对象,使用一些自定义 JavaScript 文件的对象)时,我面临着创建一种“包含脚本管理器”的需要(以避免在渲染多个小部件时重复包含相同的 JS 文件)为了视图)。
我的第一个想法是编写自定义模板渲染上下文,它将在模板中提供 EXTRA_SCRIPTS 变量。但是我不知道在请求处理期间应该在哪里收集脚本列表?我认为这就是我需要单例对象的地方。
有什么建议吗?
While developing "widgets" (objects, which - rendered - use some custom javascript files), I faced the need of creating kind of "included-scripts-manager" (to avoid double inclusion of same JS file when more than one widget is rendered for the view).
My first idea was to write custom template rendering Context which would provide EXTRA_SCRIPTS variable in the template. However I have no idea where should I collect the list of scripts during request processing? I think that's where I'd need singleton object.
Any suggestions?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果您使用单例,您将遇到线程安全问题。例如,您的应用程序在多个线程中运行,一个线程处理单个请求,因此您的全局对象应该是每个线程的,但单例是每个进程唯一的。
您可以使用本问题中描述的
threading.local
技术。它将为您提供每个线程和每个请求唯一的对象。但是,不建议这样做,因此不要使用全局变量
对于您使用小部件的情况,Django 中的小部件和表单中有媒体设置。 https://docs.djangoproject.com/en/1.3/topics/forms /media/
媒体对象也可以添加在一起。添加两个媒体对象时,生成的媒体对象包含两个文件中媒体的并集。
所以你可以用媒体来对抗重复项。
您还可以将媒体直接合并到模板中
If you use singleton you will run into thread-safety issue. E.g. your application run in several threads, one thread process single request, so you global object should be per thread, but singleton is unique per process.
You can use
threading.local
technique like described in this question. It will provide you object that is unique per thread and so per request.However it's not recommended, so don't use global variables
For your situation with widgets there are Media settings in widgets and forms in Django. https://docs.djangoproject.com/en/1.3/topics/forms/media/
Media objects can also be added together. When two media objects are added, the resulting Media object contains the union of the media from both files.
So you can fight duplicates with media.
Also you can combine media right into the template