Django项目中通过页面展示txt等文本文件内容
关键代码就一行:通过for迭代器用open打开文件逐行读取后写入数组。
log_content += [line for line in open(log_file, 'r', encoding='UTF-8')]
其中加encoding参数的目的是避免报错:
"UnicodeDecodeError: 'gbk' codec can't decode byte 0x80 in position 205: illegal multibyte sequence"
然后再模板中再加个highlight.js,效果就更好了。
view.py
class JobLogView(LoginRequiredMixin, View):
template_name = 'config/joblog.html'
def get(self, request, *args, **kwargs):
job_id = kwargs.get('job_id')
log_id = kwargs.get('log_id')
log_file = 'logs/tasks/' + log_id + '.log'
log_content = []
log_content += [line for line in open(log_file, 'r', encoding='UTF-8')]
context = {
'page_name': '作业日志',
'log_content': log_content,
}
return render(request, self.template_name, context=context)
joblog.html
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/9.18.1/styles/default.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/9.18.1/highlight.min.js"></script>
<script>hljs.initHighlightingOnLoad();</script>
<pre><code>
{% for line in log_content %}{{ line }}{% endfor %}
</code></pre>
针对pre不换行的问题,可以增加css样式如下:
pre {
white-space: pre-wrap;
word-wrap: break-word;
}