【问题标题】:How to call a python script with ajax in cherrypy app如何在cherrypy应用程序中使用ajax调用python脚本
【发布时间】:2014-09-03 00:56:24
【问题描述】:

我正在尝试从 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 被调用但返回失败警报。我试过GET、POST、“text”、“html”,b1.py在同一个目录下,不喜勿喷。所有当前都在我的本地机器上运行。

非常感谢任何提示!

【问题讨论】:

  • 我认为你的设计有缺陷。尝试使 b1 成为返回 HTTPResponse 的函数。
  • 这也可能是真的,但它似乎也是一个路径问题。如果我在单击按钮时查看 Firefox 中的工具>Web 开发人员>Netwok,我会得到 404。我尝试添加一个 cgi-bin 目录并将 b1.py 放在那里,并添加了“/cgi-bin”:{ "tools.staticdir.on": True, "tools.staticdir.dir": os.path.join(file_path, "cgi-bin") 到配置,但它仍然认为 cwd/cgi-bin/b1.py 没有'不存在。
  • 好的,我放弃了cherrypy,正在从apache提供html文件。现在,当我单击按钮时,我得到 b1.py 的内容,而不是运行它并返回正确的输出。一次一步,哈哈。
  • 将 apache 配置为运行脚本并返回到我之前的位置 - 404 未找到,尽管它在那里并且所有权限都正确。 :(

标签: python ajax cherrypy


【解决方案1】:

您完全误解了现代(例如 CherryPy 的路由)的工作原理。与 CGI 和 Apache 的 mod_*(mod_php、mod_python 等)通常使用的过时方法不同,在这些方法中,您直接指向包含带有 URL 的脚本的文件,现代路由是应用程序级别的活动。

您的应用程序接收所有请求并根据已建立的方法分派它们。从这个意义上说,CherryPy 有两种主要方法:built-in object tree dispatcherRoutes adapter。对于大多数简单和中级的情况,内置调度程序就足够了。

基本上可以是这样的。

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>

【讨论】:

  • 该链接是否应该返回一个 1GB 的文件?
  • 不,runnable.com 是服务器端可运行代码 sn-ps 的服务(基本上只需单击几下,您就可以从 asnwer 运行 sn-ps)。据我记得,它是不久前被收购和关闭的。现在做curl -v code.runnable.com 我看到301 Moved Premanentlyhttps://www.wowrack.com/1GB.file。看起来很可疑。删除了链接。感谢您的提醒。
猜你喜欢
  • 1970-01-01
  • 2019-03-04
  • 2023-03-29
  • 2014-06-28
  • 2019-10-15
  • 1970-01-01
  • 1970-01-01
  • 2023-03-21
  • 2016-05-06
相关资源
最近更新 更多