python web框架cherrypy小demo

今天接觸到一個精簡到比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 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



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章