如何在cherrypy应用中通过ajax调用python脚本

2 投票
1 回答
4553 浏览
提问于 2025-04-19 12:04

我正在尝试从一个Python脚本中获取输出,并把它放到我用Cherrypy做的应用的HTML表格里。

这是一个示例应用:

import string, os
import cherrypy

file_path = os.getcwd()

html = """<head>
<meta content="text/html; charset=ISO-8859-1"
http-equiv="content-type">
<title>CCMF</title>
<link rel='shortcut icon' type='image/x-icon' href='img/favicon.ico' />
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>

<script>
    function b1() {
        var request = $.ajax({
            url: "b1.py",
            type: "POST",            
            dataType: "text"
        });
        request.done(function(msg) {
            $("#output").html(msg);          
        });
        request.fail(function(jqXHR, textStatus) {
            alert( "Request failed: " + textStatus );
        });
    }
</script>

</head>
<button onclick="b1()">call b1.py</button>
...
<td id = "output"; style="vertical-align: top; height: 90%; width: 100%;">
<--output goes here -->
</td>
...
</html>
"""
class ccmf(object):

    @cherrypy.expose
    def index(self):
    return html

if __name__ == '__main__':
    cherrypy.server.socket_host = "127.0.0.1"
    cherrypy.server.socket_port = 8084
    config = {
         "/img": {
             "tools.staticdir.on": True,
             "tools.staticdir.dir": os.path.join(file_path, "img"),
         }
    }
    cherrypy.tree.mount(ccmf(), "/", config=config)
    cherrypy.engine.start()
    cherrypy.engine.block()

这是示例的Python脚本b1.py:

def b1():
    op = "ajax b1 pushed"
    print op
    return op

b1()

我调用了ajax,但它返回了失败的提示。我尝试过GET、POST,还有"text"和"html",b1.py也在同一个目录下,但都没有成功。目前所有的操作都是在我的本地机器上进行的。

任何提示都非常感谢!

相关问题:

1 个回答

6

你完全误解了现代路由是怎么工作的,以CherryPy为例。和以前常用的CGI和Apache的mod_*(比如mod_php、mod_python等)那种直接通过URL指向脚本文件的方式不同,现代路由是在应用层进行的。

你的应用会接收所有请求,并根据设定的方法进行处理。在这方面,CherryPy有两种主要的处理方式:内置对象树调度器路由适配器。对于大多数简单和中等复杂度的情况,内置调度器就足够用了。

基本上,它的工作方式可以是这样的。

app.py

#!/usr/bin/env python
# -*- coding: utf-8 -*-


import os

import cherrypy
from cherrypy.lib.static import serve_file


path   = os.path.abspath(os.path.dirname(__file__))
config = {
  'global' : {
    'server.socket_host' : '127.0.0.1',
    'server.socket_port' : 8080,
    'server.thread_pool' : 8
  }
}

class App:

  @cherrypy.expose
  def index(self):
    return serve_file(os.path.join(path, 'index.html')) 

  @cherrypy.expose
  @cherrypy.tools.json_out()
  def getData(self):
    return {
      'foo' : 'bar',
      'baz' : 'another one'
    }


if __name__ == '__main__':
  cherrypy.quickstart(App(), '/', config)

index.html

<!DOCTYPE html>
<html>
<head>
<meta http-equiv='content-type' content='text/html; charset=utf-8'>
<title>CCMF</title>
<script type='text/javascript' src='http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js'></script>
<script type='text/javascript'>
  $(document).ready(function()
  {
    $('button').on('click', function()
    {
      var request = $.ajax({'url': '/getData'});
      request.done(function(response) 
      {
        $('#foo').text(response.foo);
        $('#baz').text(response.baz);
      });
      request.fail(function(jqXHR, textStatus) 
      {
        alert('Request failed: ' + textStatus);
      });
    })
  });
</script>
</head>
<body>
  <button>make ajax call</button>
  <h1>Foo</h1>
  <div id='foo'></div>
  <h1>Baz</h1>
  <div id='baz'></div>
</body>
</html>

撰写回答