zoukankan      html  css  js  c++  java
  • cherry 与sqlite

    Index.html

    <!DOCTYPE html>
    <html>
      <head>
        <link href="/static/css/style.css" rel="stylesheet">
        <script src="http://code.jquery.com/jquery-2.0.3.min.js"></script>
        <script type="text/javascript">
          $(document).ready(function() {
    
    
            $("#generate-string").click(function(e) {
              $.post("/generator", {"length": $("input[name='length']").val()})
               .done(function(string) {
                $("#the-string").show();
                $("#the-string input").val(string);
              });
              e.preventDefault();
            });
    
    
            $("#replace-string").click(function(e) {
              $.ajax({
                type: "PUT",
                url: "/generator",
                data: {"another_string": $("#the-string input").val()}
              })
              .done(function() {
                alert("Replaced!");
              });
              e.preventDefault();
            });
    
    
            $("#delete-string").click(function(e) {
              $.ajax({
                type: "DELETE",
                url: "/generator"
              })
              .done(function() {
                $("#the-string").hide();
              });
              e.preventDefault();
            });
    
    
          });
        </script>
      </head>
      <body>
        <input type="text" value="8" name="length"/>
        <button id="generate-string">Give it now!</button>
        <div id="the-string">
          <input type="text" />
          <button id="replace-string">Replace</button>
          <button id="delete-string">Delete it</button>
        </div>
      </body>
    </html>

    Code

    import os, os.path
    import random
    import sqlite3
    import string
    import time
    import cherrypy
    
    
    DB_STRING = "my.db"
    
    class StringGenerator(object):
        @cherrypy.expose
        def index(self):
            return open('index.html')
    
    
    
    
    @cherrypy.expose
    class StringGeneratorWebService(object):
    
    
        @cherrypy.tools.accept(media='text/plain')
        def GET(self):
            with sqlite3.connect(DB_STRING) as c:
                cherrypy.session['ts'] = time.time()
                r = c.execute("SELECT value FROM user_string WHERE session_id=?",
                              [cherrypy.session.id])
                return r.fetchone()
    
    
        def POST(self, length=8):
            some_string = ''.join(random.sample(string.hexdigits, int(length)))
            with sqlite3.connect(DB_STRING) as c:
                cherrypy.session['ts'] = time.time()
                c.execute("INSERT INTO user_string VALUES (?, ?)",
                          [cherrypy.session.id, some_string])
            return some_string
    
    
        def PUT(self, another_string):
            with sqlite3.connect(DB_STRING) as c:
                cherrypy.session['ts'] = time.time()
                c.execute("UPDATE user_string SET value=? WHERE session_id=?",
                          [another_string, cherrypy.session.id])
    
    
        def DELETE(self):
            cherrypy.session.pop('ts', None)
            with sqlite3.connect(DB_STRING) as c:
                c.execute("DELETE FROM user_string WHERE session_id=?",
                          [cherrypy.session.id])
    
    
    
    
    def setup_database():
        """
        Create the `user_string` table in the database
        on server startup
        """
        with sqlite3.connect(DB_STRING) as con:
            con.execute("CREATE TABLE user_string (session_id, value)")
    
    
    
    
    def cleanup_database():
        """
        Destroy the `user_string` table from the database
        on server shutdown.
        """
        with sqlite3.connect(DB_STRING) as con:
            con.execute("DROP TABLE user_string")
    
    
    
    
    if __name__ == '__main__':
        conf = {
            '/': {
                'tools.sessions.on': True,
                'tools.staticdir.root': os.path.abspath(os.getcwd())
            },
            '/generator': {
                'request.dispatch': cherrypy.dispatch.MethodDispatcher(),
                'tools.response_headers.on': True,
                'tools.response_headers.headers': [('Content-Type', 'text/plain')],
            },
            '/static': {
                'tools.staticdir.on': True,
                'tools.staticdir.dir': './public'
            }
        }
    
    
        cherrypy.engine.subscribe('start', setup_database)
        cherrypy.engine.subscribe('stop', cleanup_database)
    
    
        webapp = StringGenerator()
        webapp.generator = StringGeneratorWebService()
        cherrypy.quickstart(webapp, '/', conf)

  • 相关阅读:
    使用comet架构实现了一个基于网页的视频监控prototype!!!!哇哈哈庆祝一下
    Pixysoft.Framework.Noebe.Datamining 数据挖掘开发实录
    论创业成功!让大家的青春充满着无限美好的回忆
    新年第一篇 数据库备份恢复系统上线的挫折
    .Net FrameWork 4.0中使用EF向数据库插入数据报datatime2类型错误的解决办法
    RoRoWoBlog 开源博客系统介绍
    第一次偶然出现的“System.Data.Entity.dll”类型的异常
    序列化类型 System.Data.Entity.DynamicProxies 的对象时检测到循环引用
    我也来说说Entity Frame Work 4中的数据库优先和代码优先两种方式(2)
    Asp.net MVC 2 + Castle + NHibernate 项目实战(1)
  • 原文地址:https://www.cnblogs.com/sea-stream/p/14179451.html
Copyright © 2011-2022 走看看