python web框架cherrypy小demo

来源:互联网 发布:怎么上传源码到空间 编辑:程序博客网 时间:2024/06/06 07:31

今天接触到一个精简到比django还XX的框架,cherrypy。

缺点是国内外关于cherrypy的资料比较少,远远没有django多好吗。


介绍两篇入门级blog:

CherryPy 入门

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 cherrypyimport webbrowserimport osimport jsonimport sysMEDIA_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.pymedia(文件夹)bootstrap.min.cssbootstrap.min.jsindex.htmljquery-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



1 0