# coding: utf-8
import re
import time
from functools import wraps
def default(environ, start_response):
# print('#' * 100)
# print(environ)
# print('#' * 100)
status = '404 Not Found'
response_headers = [('Content-Type', 'text/html')]
start_response(status, response_headers)
return [('==404 from a simple WSGI application!--->%s\n' % time.ctime()).encode('utf-8')]
class Kanado:
def __init__(self, import_name):
self.import_name = import_name
self.uri_map = {}
self.uri_regex_map = {}
self.uri_map = {
'404': default
}
def __call__(self, *args):
environ, start_response = args
url = environ['PATH_INFO']
if url in self.uri_map:
app = self.uri_map.get(url)
dic = {}
return app(environ, start_response, **dic)
for k, v in self.uri_map.items():
if k in self.uri_regex_map:
m = self.uri_regex_map[k].match(url)
if m:
app = self.uri_map.get(k)
return app(environ, start_response, **m.groupdict())
else:
app = self.uri_map.get('404')
return app(environ, start_response)
def route(self, path):
print('path', path)
pattern = path
pattern = pattern.replace('<', '(?P<')
pattern = pattern.replace('>', '>\w+)')
def wrapper(func):
if pattern.find('<') >= 0 and pattern.find('>') >= 0:
self.uri_regex_map[path] = re.compile(pattern)
@wraps(func)
def _wrap(environ, start_response,*args, **param):
res = func(*args, **param)
start_response('200 OK', [('Content-Type', 'text/html')])
return [res.encode('utf-8')]
self.uri_map.update({
path: _wrap,
})
return _wrap
return wrapper
from kanado import Kanado, render_template
app = Kanado(__name__)
class Blog:
def __init__(self, id, title, text):
self.id = id
self.title = title
self.text = text
blogs = []
b1 = Blog(1,'hello1','zhangsan')
b2 = Blog(2,'hello2','lisi')
blogs.append(b1)
blogs.append(b2)
@app.route('/')
def home():
'''
主页
'''
# 渲染首页HTML模板文件
return render_template('home.html')
@app.route('/blogs')
def list_notes():
'''
查询博文列表
'''
# 渲染博文列表页面目标文件,传入blogs参数
return render_template('list_blogs.html',blogs = blogs)
@app.route('/blog/<id>')
def query_note(id):
'''
查询博文详情、删除博文
'''
blog = None
# 到数据库查询博文详情
for blg in blogs:
if blg.id == int(id):
blog = blg
# 渲染博文详情页面
return render_template('query_blog.html',blog = blog)