python + django 搭建網頁(嘗試4):自動顯示txt檔案
阿新 • • 發佈:2022-01-17
我想實現:
程式自動從一個資料夾中讀取文件,然後呈現在一個網頁上。
1. urls.py 設定
urls.py 中:
urlpatterns = [
...
path('loveread/pandawarrior/', views.collection, {'author': "熊貓酒仙"}),
...
]
這樣,訪問到 .../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)
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}}作品集 </center> </br> <div align="center"> </br> {% for i in content %} {{ i |safe }}</br> {% endfor %} </br> </div>
4. 效果圖
5. 總結與展望
- 現在可以搭建很簡單的個人文集網頁,每次更新只需要向相應資料夾補充作品txt,網頁就會自動更新。
- 展望:目前網頁還非常簡陋,沒有經過精心的排版、渲染、字型等調節。未來可能借鑑別人的html頁面,修改我們的 html 模板。