【发布时间】:2014-02-10 21:08:35
【问题描述】:
我想在 Django 项目中使用 mpd client,并希望避免与 mpd 服务器的连接过多。我认为实现这一点的最简单方法是重用 mpd-client 对象,而不是为每个请求创建一个新对象。
简而言之,我想做一些与此非常相似的事情:Django: Keep a persistent reference to an object?。
@daniel-roseman 表示这很容易通过在模块级别简单地实例化对象来实现。但是,作为一个 python 新手,我不太明白这是什么意思。
到目前为止,我已经创建了一个模块(见下文),它会在断开连接时重新连接到 mpd,并将此模块保存到 <Project>/<app>/lib/MPDProxy.py。
如何在模块级别实例化这个 (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()
【问题讨论】:
标签: python django python-3.x