我正在尝试从内部数据库中获取的JSON数据创建HTML格式(用于发送自动电子邮件),我收到以下错误“无”#39;类型,我想捕捉'无'键入以及如何不输错误即使'无'类型?
INPUT: -
{'total': 0, 'Resolution': None, 'key': u'CNSSDEBUG-151394', 'summary': u'[Lenovo][NFA344A][Win10] - [QCA6174_9377.WIN.1.0-10366-QCARMTFX86WZ-2] - Undetermined crash root cause'}
代码: -
........
for item in jiradb :
MailBody = MailBody + "<tr>"
MailBody = MailBody + "<td>" + str(icount) + "</td>"
print item['key']
MailBody = MailBody + "<td>" + item['key'].rstrip('\n!') + "</td>"
MailBody = MailBody + "<td>" + item['summary'].rstrip('\n!') + "</td>"
MailBody = MailBody + "<td>" + item['Resolution'].rstrip('\n!') + "</td>"
icount = icount + 1
.......................
错误: -
Traceback (most recent call last):
File "sns.py", line 217, in <module>
main()
File "sns.py", line 215, in main
sendmail(meta,jiradb,total_no_crashes)
File "sns.py", line 47, in sendmail
MailBody = MailBody + "<td>" + item['Resolution'].rstrip('\n!') + "</td>"
AttributeError: 'NoneType' object has no attribute 'rstrip'
答案 0 :(得分:4)
这听起来似乎过于宽泛,但我建议切换到模板引擎,如mako
或jinja2
,而不是尝试手动构建HTML使用字符串连接。您只需使用变量占位符和内置或自定义过滤器即可解决此类问题。
作为奖励,您可以很好地分离逻辑(您的Python代码)和演示文稿 - 生成的HTML。一个更清洁,更可测试的代码。
以下是使用jinja2
(创建custom rstrip
filter)的工作示例:
from jinja2 import Environment, FileSystemLoader
jiradb = [
{'total': 0, 'Resolution': None, 'key': u'CNSSDEBUG-151394', 'summary': u'[Lenovo][NFA344A][Win10] - [QCA6174_9377.WIN.1.0-10366-QCARMTFX86WZ-2] - Undetermined crash root cause'},
{'total': 1, 'Resolution': 'fixed', 'key': u'CNSSDEBUG-151395', 'summary': u'Some other summary'},
]
env = Environment(loader=FileSystemLoader('.'))
env.filters['rstrip'] = lambda value, s: value.rstrip(s) if value else ''
template = env.get_template('index.html')
print(template.render(jiradb=jiradb))
index.html
内容:
<table>
{% for item in jiradb %}
<tr>
<td>{{ loop.index }}</td>
<td>{{ item.key|rstrip("\n!") }}</td>
<td>{{ item.summary|rstrip("\n!") }}</td>
<td>{{ item.Resolution|rstrip("\n!") }}</td>
</tr>
{% endfor %}
</table>
打印:
<table>
<tr>
<td>1</td>
<td>CNSSDEBUG-151394</td>
<td>[Lenovo][NFA344A][Win10] - [QCA6174_9377.WIN.1.0-10366-QCARMTFX86WZ-2] - Undetermined crash root cause</td>
<td></td>
</tr>
<tr>
<td>2</td>
<td>CNSSDEBUG-151395</td>
<td>Some other summary</td>
<td>fixed</td>
</tr>
</table>
答案 1 :(得分:2)
使用dict.get(key,default)
从字典中提取每个字段以避免丢失字段,然后使用or
来涵盖None
案例
例如
item['Resolution'].rstrip('\n!')
变为
(item.get('Resolution', None) or '').rstrip('\n!')
然后你可能想要一个辅助函数
def get_field(item, field, default=''):
return (item.get(field, None) or default).rstrip('\n!')
然后你的循环更清洁一点,而你从错别字更安全
........
for item in jiradb :
MailBody = MailBody + "<tr>"
MailBody = MailBody + "<td>" + str(icount) + "</td>"
print get_field(item, 'key')
MailBody = MailBody + "<td>" + get_field(item,'key') + "</td>"
MailBody = MailBody + "<td>" + get_field(item,'summary') + "</td>"
MailBody = MailBody + "<td>" + get_field(item,'Resolution') + "</td>"
icount = icount + 1