Django:保持对对象的持久引用? [英] Django: Keep a persistent reference to an object?

查看:65
本文介绍了Django:保持对对象的持久引用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我很高兴接受这不可能,更不用说明智了,但是是否可以持久引用我创建的对象?

I'm happy to accept that this might not be possible, let alone sensible, but is it possible to keep a persistent reference to an object I have created?

例如,在我的一些视图中,我的代码看起来像这样(为简化起见简化):

For example, in a few of my views I have code that looks a bit like this (simplified for clarity):

api = Webclient()
api.login(GPLAY_USER,GPLAY_PASS)
url = api.get_stream_urls(track.stream_id)[0]

client = mpd.MPDClient()
client.connect("localhost", 6600)
client.clear()
client.add(url)
client.play()
client.disconnect()

如果我仅保留对 api的引用,那真的很整洁。 code>和 client ,尤其是避免使用 gmusicapi 重复进行api登录。我可以在 settings.py 中声明它们吗? (我猜这是一个糟糕的主意),还是通过其他方式与他们保持持久的联系?

It would be really neat if I could just keep one reference to api and client throughout my project, especially to avoid repeated api logins with gmusicapi. Can I declare them in settings.py? (I'm guessing this is a terrible idea), or by some other means keep a connection to them that's persistent?

理想情况下,我将拥有像 get_api()可以检查现有对象是否还可以并返回它或根据需要创建一个新对象。

Ideally I would then have functions like get_api() which would check the existing object was still ok and return it or create a new one as required.

推荐答案

每个应用程序都不能实例化一次,因为几乎可以肯定有多个服务器进程,并且对象不容易在进程之间共享。但是,每个过程一个绝对是可能的,而且值得。为此,您只需要在相关文件(例如views.py)中的模块级别实例化它即可。这意味着当Django首次导入该文件时(在该过程中),它将自动实例化,您可以在该文件中将其称为全局变量。只要该过程执行,它将一直存在,并且在创建新过程时,将实例化一个新的全局变量。

You can't have anything that's instantiated once per application, because you'll almost certainly have more than one server process, and objects aren't easily shared across processes. However, one per process is definitely possible, and worthwhile. To do that, you only need to instantiate it at module level in the relevant file (eg views.py). That means it will be automatically instantiated when Django first imports that file (in that process), and you can refer to it as a global variable in that file. It will persist as long as the process does, and when as new process is created, a new global var will be instantiated.

这篇关于Django:保持对对象的持久引用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆