今天接触到一个精简到比django还XX的框架,cherrypy。
缺点是国内外关于cherrypy的资料比较少,远远没有django多好吗。
介绍两篇入门级blog:
Simple Ajax with cherrypy and jQuery
介绍下API:
http://docs.cherrypy.org/en/latest/basics.html
我先post下我的小demo截图:
点击BiuBiuBiu~后:
首先是HTML:
<html>
<head>
<title>时光机</title>
<link href="/media/bootstrap.min.css" rel="stylesheet">
<script type="text/javascript" src="/media/jquery-1.9.1.js"></script>
<script src="/media/bootstrap.min.js"></script>
<script type="text/javascript">
$(function() {
$("#form").submit(function() { //ajax构造submit
var postdata = {wish: $("#wish").val()} ;
$.post('/submit', postdata, function(data) {
$("#post-wish").html("<h1>你刚刚说:"+data['wish']+"</h1>") ;
});
return false ; //拦截submit
});
});
</script>
</head>
<body>
<div class="container">
<div class="row">
<div class="col-md-12">
<div class="jumbotron">
<h1 id="title">时光机,发射?!</h1>
<form id="form" action="#" method="post">
<p>
<label for="wish">你的愿望是:</label>
<input type="text" id="wish" />
<input type="submit" value="BiuBiuBiu~" />
</p>
</form>
<span id = "post-wish"></span>
</div>
</div>
</div>
</div>
</body>
</html>
然后是ajax_app.py:
#-*-coding:utf-8 -*-
import cherrypy
import webbrowser
import os
import json
import sys
MEDIA_DIR = os.path.join(os.path.abspath("."), u"media")
class AjaxApp(object):
@cherrypy.expose #暴露此函数才能被url get到
def index(self):
return open(os.path.join(MEDIA_DIR, u'index.html'))
@cherrypy.expose
def submit(self, wish):
cherrypy.response.headers['Content-Type'] = 'application/json'
return json.dumps(dict(wish="%s" % wish))
#配置文件
config = {'/media':
{'tools.staticdir.on': True,
'tools.staticdir.dir': MEDIA_DIR,
}
}
#方便测试,不用每次都打开浏览器写入http://127.0.0.1:8080/
#这个帮我们打开了
def open_page():
webbrowser.open("http://127.0.0.1:8080/")
cherrypy.engine.subscribe('start', open_page) #告诉cherrypy线程开始时就调用这个open_page函数
cherrypy.tree.mount(AjaxApp(), '/', config=config) #配置config,挂载AjaxApp到 /
cherrypy.engine.start() #开始
整个目录结构是:
cherrypy-demo(文件夹):
ajax_app.py
media(文件夹)
bootstrap.min.css
bootstrap.min.js
index.html
jquery-1.9.1.js
稍微解释下有趣的code:
cherrypy.engine.subscribe('start', function1)
API这么说的,我就不翻译了吧:Use cherrypy.engine.subscribe to tell CherryPy to call a function when each thread starts
当然我们也可以: cherrypy.engine.subscribe('stop', function2)
cherrypy.tree.mount() 至少带1个参数,第2个参数是该类要挂载的路径,第3个参数是config。
这框架,funny....
本文code出自第二篇入门blog:
The GITS Blog