我在这里遇到了一个奇怪的问题。它伤害了我的大脑思考它。 我有一个包含多个应用程序的Django项目。今天我添加了另一个应用程序。
(的 views.py )
from %app_name%.%class_file% import %class_name%
def api(request):
t = %class_name%()
data = {}
data['listOtherDevices'] = t.listOtherDevices
logger = logging.getLogger(__name__)
logger.error(len(t.listOtherDevices))
return JsonResponse(data)
导入的类通过填充'listOtherDevices'数组
当我在控制台中运行时,__init__
完全没问题。当我这样做时,这个数组中正好有3个元素(因为我的局域网中有3个设备可以找到)。因此,当我访问链接到此方法的url(开发服务器 - > manage.py runserver)时,我可以看到一个正好有3个条目的JSON。到目前为止一直很好,但现在变成了奇怪的部分。当我在浏览器中刷新网址或再次访问它时,有超过3个条目。该计划是这样的:
opened url 1 time: 3 entries
opened url 2 times: 9 entries (+ 6)
opened url 3 times: 18 entries (+ 9)
opened url 4 times: 30 entries (+ 12)
opened url 5 times: 45 entries (+ 15)
opened url 6 times: 63 entries (+ 18)
我可以在那里看到一种模式,但我无法理解为什么会发生这种情况。
sudo sysdig -c spy_users
告诉我,该课程正在使用
正确收集信息3次subprocess.check_output
响应的JSON在语法上是正常的。似乎班级会“找到”9或18个设备。
请帮助我,因为正如我之前所说:这会让我的大脑受伤:)。
import json
import subprocess
class tradfri:
tradfriIPv4 = 'blablabla'
tradfriUser = 'blablabla'
tradfriPassword = 'blablabla'
pathToCoap = '/blablabla/coap-client'
listDevices = []
listGroups = []
listDevicesDetails = []
listGroupsDetails = []
listLightbulbs = []
listOtherDevices = []
def __init__(self):
self.getDevices()
self.getGroups()
self.getArrayLightbulbs()
self.getArrayOtherDevices()
def getDevices(self):
method = 'get'
stdoutdata = subprocess.check_output( self.pathToCoap
+ ' -m ' + method
+ ' -u "' + self.tradfriUser + '"'
+ ' -k "' + self.tradfriPassword + '"'
+ ' coaps://' + self.tradfriIPv4 + ':5684/15001'
+ " | awk 'NR==4'",
shell=True).decode("utf-8")
self.listDevices = json.loads(stdoutdata)
for ID in self.listDevices:
stdoutdata = subprocess.check_output( self.pathToCoap
+ ' -m ' + method
+ ' -u "' + self.tradfriUser + '"'
+ ' -k "' + self.tradfriPassword + '"'
+ ' coaps://' + self.tradfriIPv4 + ':5684/15001/' + str(ID)
+ " | awk 'NR==4'",
shell=True).decode("utf-8")
self.listDevicesDetails.append(json.loads(stdoutdata))
def getGroups(self):
method = 'get'
stdoutdata = subprocess.check_output( self.pathToCoap
+ ' -m ' + method
+ ' -u "' + self.tradfriUser + '"'
+ ' -k "' + self.tradfriPassword + '"'
+ ' coaps://' + self.tradfriIPv4 + ':5684/15004'
+ " | awk 'NR==4'",
shell=True).decode("utf-8")
self.listGroups = json.loads(stdoutdata)
for ID in self.listGroups:
stdoutdata = subprocess.check_output( self.pathToCoap
+ ' -m ' + method
+ ' -u "' + self.tradfriUser + '"'
+ ' -k "' + self.tradfriPassword + '"'
+ ' coaps://' + self.tradfriIPv4 + ':5684/15004/' + str(ID)
+ " | awk 'NR==4'",
shell=True).decode("utf-8")
raw = json.loads(stdoutdata)
tmpMembers = []
for id in raw['9018']['15002']['9003']:
tmpMembers.append( { 'ID': str( id ), 'name': self.getDeviceNameByID(id) } )
self.listGroupsDetails.append( { 'ID': str( raw['9003'] ),
'name': raw['9001'],
'isGroupOn': False,
'members': tmpMembers } )
def getArrayLightbulbs(self):
for item in self.listDevicesDetails:
if item['3']['6'] == 1: # is lightbulb
id = item['9003']
name = item['9001']
groupID = self.getGroupIDByID(id)
groupName = self.getGroupNameByID(id)
manufacturer = item['3']['0']
description = item['3']['1']
isReachable = True
isBulbOn = False
isDimmable = False
isWhiteSpectrum = False
isColorSpectrum = False
brightnessOfBulb = ''
currentColor = ''
#isReachable
if len(item['3311'][0]) == 1:
isReachable = False;
else:
#isBulbOn
if item['3311'][0]['5850'] == 1:
isBulbOn = True
#dimmable & brightnessOfBulb
if '5851' in item['3311'][0]:
brightnessOfBulb = str( item['3311'][0]['5851'] )
isDimmable = True
#currentColor
if '5706' in item['3311'][0]:
currentColor = item['3311'][0]['5706']
#isWhiteSpectrum
if ' WS ' in description:
isWhiteSpectrum = True
#isColorSpectrum
if ' CWS ' in description:
isWhiteSpectrum = True
isColorSpectrum = True
self.listLightbulbs.append( { 'ID': str( id ),
'Name': name,
'groupID': str( groupID ),
'groupName' : groupName,
'manufacturer': manufacturer,
'description' : description,
'isReachable': isReachable,
'isBulbOn': isBulbOn,
'isDimmable': isDimmable,
'isWhiteSpectrum': isWhiteSpectrum,
'isColorSpectrum': isColorSpectrum,
'brightnessOfBulb': brightnessOfBulb,
'currentColor': currentColor } )
def getArrayOtherDevices(self):
for device in self.listDevicesDetails:
if device['3']['6'] == 3:
self.listOtherDevices.append( { 'ID': str( device['9003'] ),
'Name': device['9001'],
'groupID': str( self.getGroupIDByID(str( device['9003']) ) ),
'groupName': self.getGroupNameByID(str( device['9003']) ),
'manufacturer': device['3']['0'],
'description': device['3']['1'] } )
def getDeviceNameByID(self, id):
name = ''
for key in self.listDevicesDetails:
if key['9003'] == id:
name = key['9001']
return name
def getGroupIDByID(self, id):
groupID = ''
for group in self.listGroupsDetails:
for member in group['members']:
if member['ID'] == id:
groupID = group['ID']
return groupID
def getGroupNameByID(self, id):
groupName = ''
for group in self.listGroupsDetails:
for member in group['members']:
if member['ID'] == id:
groupName = group['name']
return groupName
答案 0 :(得分:0)
您使用类范围属性来保存数据。
每当您创建tradfri
的新实例时,您的方法都会在相同的类范围属性listOtherDevices
上工作。请注意,在重新启动服务器之前,该类将存在于内存中。因此,当您将值附加到列表中时,每个请求的值都会增加。
您应该使用每个实例可用的属性。在python中,这是通过初始化__init__()
内的属性来实现的。它可能看起来像这样:
class tradfri:
def __init__(self):
self.tradfriIPv4 = 'blablabla'
self.tradfriUser = 'blablabla'
self.tradfriPassword = 'blablabla'
self.pathToCoap = '/blablabla/coap-client'
self.listDevices = []
self.listGroups = []
self.listDevicesDetails = []
self.listGroupsDetails = []
self.listLightbulbs = []
self.listOtherDevices = []
self.getDevices()
self.getGroups()
self.getArrayLightbulbs()
self.getArrayOtherDevices()
阅读python class attribute了解更多详情。 official documentation on that topic也值得一读。