在Django中实例化“模块级”对象

时间:2014-02-10 21:08:35

标签: python django python-3.x

我想在Django项目中使用mpd client,并希望避免与mpd服务器建立更多连接。我认为最简单的方法是重用mpd-client对象,而不是为每个请求创建一个新对象。

简而言之,我想做一些非常类似的事情:Django: Keep a persistent reference to an object?

@ daniel-roseman表示,只需在模块级别实例化对象即可轻松实现。但是,作为一个蟒蛇新手,我不太明白这意味着什么。

到目前为止,我已经创建了一个模块(见下文),如果断开连接并将此模块保存到<Project>/<app>/lib/MPDProxy.py,它将重新连接到mpd。

如何在模块级别实例化此(mpd-)对象?

# MPDProxy.py
from mpd import MPDClient, MPDError

class MPDProxy:
    def __init__(self, host="localhost", port=6600, timeout=10):
        self.client = MPDClient()
        self.host = host
        self.port = port

        self.client.timeout = timeout
        self.connect(host, port)

    def connect(self, host, port):
        self.client.connect(host, port)
        self.client.consume(1) # when we call self.client.next() the previous stream is deleted from the playlist
        if len(self.client.playlist()) > 1:
            cur =  (self.client.playlist()[0][6:])
            self.client.clear()
            self.add(cur)

    def add(self, url):
        try:
            self.client.add(url)
        except ConnectionError:
            self.connect(self.host, self.port)
            self.client.add(url)

    def play(self):
        try:
            self.client.play()
        except ConnectionError:
            self.connect(self.host, self.port)
            self.client.play()

    def stop(self):
        try:
            self.client.stop()
        except ConnectionError:
            self.connect(self.host, self.port)
            self.client.stop()

    def next(self):
        try:
            self.client.next()
        except ConnectionError:
            self.connect(self.host, self.port)
            self.client.next()

    def current_song(self):
        try:
            return self.client.currentsong()
        except ConnectionError:
            self.connect(self.host, self.port)
            return self.client.current_song()

    def add_and_play(self, url):
        self.add(url)

        if self.client.status()['state'] != "play":
            self.play()

        self.next()

1 个答案:

答案 0 :(得分:1)

我只是指该模块的底层,与“from mpd ...”和“class MPDProxy ...”行相同的缩进。

因此,在文件底部,根本没有缩进,放置proxy = MPDProxy() - 现在您可以通过from lib.MPDProxy import proxy导入该实例来引用该实例。