python + django 搭建网页(尝试4):自动显示txt文件
我想实现:
程序自动从一个文件夹中读取文档,然后呈现在一个网页上。
1. urls.py 设置
urls.py 中:
urlpatterns = [
...
path('loveread/pandawarrior/', views.collection, {'author': "熊猫酒仙"}),
#如果域名 x.x.x.x:x/loveread/pandawarrior/ 被访问,
#就调用 views.collection 函数,并传入作者名参数。
...
]
这样,访问到 .../loveread/pandawarrior/ 地址的时候,就启动 views.py 中的 colloection 函数,并且传入参数 author = "熊猫酒仙"。
2. views.py 设置
定义 collection 函数,查看 statics/works/熊猫酒仙/ 路径下的所有文件,然后将所有文件的内容载入到 content 列表中。
最后将作者名通过 author, 内容通过 content 传给 context 变量,再将 context 的值传递给 render 函数。由 render 函数读取 template/collection.html 模板,生成网页。
def collection(request, author):
print("author = ", author)
dir = "statics/works/" + author + "/" # 作者的目录
filenames = os.listdir(dir) # 作者目录下的作品列表
print("filenames = ", filenames)
content = []
for filename in filenames:
content += [ line for line in open(dir+filename, 'r', encoding='UTF-8')] # 收集作品中的所有行
print("open = ", open(dir+filename, 'r', encoding='UTF-8') )
content += [" "," "] # 加两个空行
print("content = ", content)
context = {
'author': author,
'content': content,
}
return render(request, 'collection.html', context)
# 作品内容(所有行)都在 context.content 中,传给 render 函数
3. 模板 collection.html
自动显示 xxx 作品集,然后把前面从 statics/works/熊猫酒仙/路径下所有文档中读取的内容显示在一个页面上。
<title>{{author}}</title> <!-- 网页抬头 -->
<body bgcolor="#E0FFFF"></body> <!-- 背景色:浅靛蓝色 -->
<center style="font-family:verdana;font-size:150%;color:green;center">
{{author}}作品集 <!-- 使用 author 参数,网页上显示大标题:xx作品集 -->
</center> <!-- 居中 -->
</br> <!-- 空行 -->
<div align="center"> <!-- 居中 -->
</br>
{% for i in content %} <!-- 遍历文本内容 -->
{{ i }}</br> <!-- 把(从前文中从 txt 中读取的)作品内容都印在网页上-->
{% endfor %}
</br>
</div>
4. 效果图
5. 总结与展望
- 现在可以搭建很简单的个人文集网页,每次更新只需要向相应文件夹补充作品txt,网页就会自动更新。
- 展望:目前网页还非常简陋,没有经过精心的排版、渲染、字体等调节。未来可能借鉴别人的html页面,修改我们的 html 模板。