1. 程式人生 > >Day 7

Day 7

然後,編寫一個jinja2模板test.html,放入templates資料夾中:
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <title>Test users - Awesome Python Webapp</title>
</head>
<body>
    <h1>All users</h1>
    {% for u in users %}
    <p>{{ u.name }} / {{ u.email }}</p>
    {% endfor %}
</body>
</html>
最後,對Day 5中初始化app的函式修改,啟動orm框架
import asyncio, os, json, time, logging
import orm
from config import configs
from datetime import datetime
from aiohttp import web
from jinja2 import Environment, FileSystemLoader
from coroweb import add_route, add_routes, add_static
if __name__ == '__main__':

	async def init(loop):
		await orm.create_pool(loop, **configs['db']) # 新增配置檔案
		app = web.Application(loop = loop, middlewares=[logger_factory, response_factory])
		init_jinja2(app, filters=dict(datetime = datetime_filter))
		add_routes(app, 'test_view')
		add_static(app)
		srv = await loop.create_server(app.make_handler(), 'localhost', 9000)
		logging.info('server started at http://127.0.0.1:9000...')
		return srv

	loop = asyncio.get_event_loop()
	loop.run_until_complete(init(loop))
	loop.run_forever()
在開始執行前,別忘了在MySQL的users表中傳入資料。 然後,執行,訪問localhost:9000。 雖然顯示頁面非常簡陋,但我們已經完成一次MVC聯動了~