我正在尝试从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在同一目录中,没有任何乐趣。当前所有正在我的本地机器上运行。
任何提示都非常感谢!
您完全误解了CherryPy路由的现代程度。与CGI和Apache的mod _ *(mod_php,mod_python等)通常采用的过时方法不同,在这种方法中,您直接指向包含带有URL的脚本的文件,而现代路由则是应用程序级的活动。
您的应用程序将接收所有请求,并根据已建立的方法将其分派。从这个意义上讲,CherryPy有两种主要方法:built-in object tree dispatcher和Routes 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>