Python 非类型不可编辑
我正在使用Django 2.0和Python 3构建一个应用程序,但在使用自定义类解析文件时遇到了一些问题 我创建了这个类:Python 非类型不可编辑,python,django,python-3.x,Python,Django,Python 3.x,我正在使用Django 2.0和Python 3构建一个应用程序,但在使用自定义类解析文件时遇到了一些问题 我创建了这个类: class MailWareConfiguration: _configuration = {} def __init__(self, data, *args, **kwargs): if self._configuration == {}: self._configuration = self.dot(data)
class MailWareConfiguration:
_configuration = {}
def __init__(self, data, *args, **kwargs):
if self._configuration == {}:
self._configuration = self.dot(data)
def accessible(self,key):
if self.exists(key) and (self._configuration[key] and not self._configuration[key] == ''):
return True
else:
return False
def dot(self, data, prepend = ''):
print('MailwareConfiguration.dot started')
results = {}
print('RAW: ' + str(data))
for key,value in data.items():
print('RAW VAL: '+str(value))
if isinstance(value, dict):
print('KEY: ' + str(key) + ' DICT: '+str(value))
results = results.update(self.dot(value,prepend+key+'.'))
else:
print('KEY: ' + str(key) + ' VALUE: '+str(value))
results[prepend+key] = value
print('RAW PROCESSED: ' + str(data))
print('MailwareConfiguration.dot finished')
return results
def exists(self, key):
if key in self._configuration:
return True
else:
return False
def get(self, key, default):
if self.accessible(key):
return self._configuration[key]
else:
return default
这个类的目的是将一个dict
处理成一个平面结构dict
,其中每个后续级别将由一个点分隔,类似于Laravel PHP中的config
函数
这样做的目的是,我可以在Git
之外轻松地提供一个.json
文件的可读实现,这样敏感信息(如数据库凭据)就不会存储在版本控制中,但仍然具有分配给settings.py中变量的值
我的示例配置文件如下所示:
{
"debug": true,
"hosts": [
"localhost"
],
"database": {
"name": "mailware",
"user": "mailware",
"password": "mailware",
"host": "localhost",
"port": "5432",
"options": {
"sslmode": "require"
}
},
"language_code": "en-us",
"time_zone": "UTC",
"api_only_mode": false,
"hostconfig": {
"salearn_bin":"/usr/bin/salearn",
"sa_bin": "/usr/bin/spamassassin",
"mailscanner_bin":"/usr/sbin/MailScanner",
"mailscanner_config_dir": "/etc/MailScanner",
"mailscanner_share_dir": "/usr/share/MailScanner",
"mailscanner_lib_dir": "/usr/lib/MailScanner",
"tmp_dir":"/tmp",
"sa_rules_dir":"/usr/share/spamassassin",
"sendmail_bin":"/usr/sbin/sendmail"
},
"retention": {
"records":60,
"audit":60,
"quarantine":60
},
"mta": "sendmail"
}
它在MailWareConfiguration.dot
期间运行良好,但一旦我们处理完json
数据的database
属性,它就会与dot中的File/code/mailware/src/core/helpers.py”第22行崩溃
results=results.update(self.dot(值,前置+键+'))
TypeError:“非类型”对象不可编辑
,并且不处理文件的其余部分
如何在不更改文件结构的情况下解决此问题重申我先前的评论:
您收到错误NoneType不可编辑
,因为您将void方法的输出-dict.update()
-分配给字典。引用说明:
使用其他键/值对更新字典,覆盖现有键。返回None
执行此操作的代码是
for key,value in data.items():
print('RAW VAL: '+str(value))
if isinstance(value, dict):
print('KEY: ' + str(key) + ' DICT: '+str(value))
---> results = results.update(self.dot(value,prepend+key+'.'))
标记行可以简单地
results.update(self.dot(value, prepend + key + '.'))
results.update()
自身变异-它不会返回带有更改的自身副本。因此results=results.update()
将Nonetype
分配给results
。