1. 程式人生 > >網站搭建筆記精簡版---廖雪峰WebApp實戰-Day7:編寫MVC筆記

網站搭建筆記精簡版---廖雪峰WebApp實戰-Day7:編寫MVC筆記

網站搭建筆記精簡版-廖雪峰教程學習@[三川水祭]
僅作學習交流使用,將來的你會感謝現在拼命努力的自己!!!

在前幾天的課程中,已經編寫完了ORM資料庫處理封裝框架、web框架和配置檔案。接下來將處理MVC,進行程式碼的啟動。即對上一節中編寫的handlers.py檔案進行重新編寫,即當遇到不同型別的請求時候函式應該具體如何處理。

handlers.py的程式碼

#!/usr/bin/env python3
# -*- coding: utf-8 -*-

__author__ = 'Michael Liao'

' url handlers '

import re, time, json, logging, hashlib, base64, asyncio
from coroweb import get, post
from models import User, Comment, Blog, next_id

# 裝飾器,即當遇到連結語言為'/'的GET語句時候,進行呼叫index函式。
@get('/')
async def index(request):
    # orm檔案中封裝的findAll函式,models.py檔案中User整合自Model
    users = await User.findAll()
    return {
    	# __template__指定的模板檔案是'test.html',users為html檔案的引數
        '__template__': 'test.html',
        'users': users
}

test.html程式碼

handlers中呼叫test.html網頁作為模板,使用後面的users引數動態生成新的網頁。test.html存放在根目錄下的templates資料夾中,根據app.py中init_jinja2()函式定義的動態網頁模板目錄。

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <title>Test users - Awesome Python Webapp</title>
</head>
<body>
    <h1>All users</h1>
    # 通過handlers.py中的users引數動態輸出user.name與user.email
    {% for u in users %}
    <p>{{ u.name }} / {{ u.email }}</p>
    {% endfor %}
</body>
</html>

網頁測試

資料庫awesome中user表填充

# 進入資料庫
mysql -u 'root' -p
# 檢視所有資料庫
show databases;
# 進入awesome資料庫,本部落格Day5筆記最下面詳述進行了該資料庫建立
use awesome;
# 檢視awesome資料庫中具有哪些表格
show tables;
# 檢視users表中具體的資料
select * from users;
# 如果沒有,自行插入內容
# 首先檢視索引是什麼
show colunms from users;
# 根據屬性插入內容,注意上一行命令出現的各個屬性的型別
insert into users (id, email, passwd, admin, name, image) values (‘111’,'
[email protected]
',1,'root','zht','222'); # 檢視插入的內容 select * from users; # 之後重複插入幾個user物件即可

啟動webapp框架

在命令列輸入:python app.py,之後在瀏覽器輸入localhost:9000即可。

參考部落格
廖雪峰的官方網站