$post 和 Cherrypy
我现在在做一个项目,之前我们使用的是Django框架。不过,这个框架对我们的需求来说有点太重了,所以我们决定换成cherrypy,因为我们其实只需要处理请求。
我的问题是这样的。我在HTML页面(index.html)上有一个表单,当用户点击提交时,会执行以下的jQuery函数。
$(document).ready(function() {
$("#loginform").submit(function() {
var request_data = {username:$("#username").val(),password:"test"};
$.post('/request',request_data, function(data) {
$("#error").html(data['response']);
});
return false;
});
});
这个功能运行得很好。接下来,应该有一个Cherrypy的方法来处理请求数据,但似乎没有被执行。这里是处理请求的Cherrypy方法。
@cherrypy.expose
def request(self, request_data):
print "Debug"
cherrypy.response.headers['Content-Type'] = 'application/json'
return simplejson.dumps(dict(response ="Invalid username and/or password"))
这个方法只是一个测试,我希望在终端窗口看到“Debug”信息,并且在点击提交按钮后,网页上能显示错误信息。
在终端中,我在请求发出后看到这个消息:
"POST /request HTTP/1.1" 404 1254 "http://127.0.0.1:8080/" "Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10_6_7; en-us) AppleWebKit/533.21.1 (KHTML, like Gecko) Version/5.0.5 Safari/533.21.1"
这表明它找不到请求的方法。我能想到的就是可能和参数有关。
因为我对cherrypy还不太熟悉,我觉得可能是我遗漏了什么简单的东西,如果能给我一些提示就太好了。
附注:以下的代码可以正常工作,但我需要能够传递多个数据给cherrypy。(这里的cherrypy参数改成了username,以便让它能工作)
$(document).ready(function() {
$("#loginform").submit(function() {
$.post('/request',{username:$("#username").val()}, function(data) {
$("#error").html(data['response']);
});
return false;
});
});
感谢你们提前提供的任何帮助或指导。
这是我的完整cherrypy文件。
import cherrypy
import webbrowser
import os
import simplejson
import sys
from backendSystem.database.authentication import SiteAuth
MEDIA_DIR = os.path.join(os.path.abspath("."), u"media")
class LoginPage(object):
@cherrypy.expose
def index(self):
return open(os.path.join(MEDIA_DIR, u'index.html'))
@cherrypy.expose
def request(self, request_data):
print "Debug"
cherrypy.response.headers['Content-Type'] = 'application/json'
return simplejson.dumps(dict(response ="Invalid username and/or password"))
config = {'/media': {'tools.staticdir.on': True, 'tools.staticdir.dir': MEDIA_DIR, }}
root = LoginPage()
# DEVELOPMENT ONLY: Forces the browser to startup, easier for development
def open_page():
webbrowser.open("http://127.0.0.1:8080/")
cherrypy.engine.subscribe('start', open_page)
cherrypy.tree.mount(root, '/', config = config)
cherrypy.engine.start()
1 个回答
6
我找到了这个问题的解决办法。用的是JQuery:
$(document).ready(function() {
$("#loginform").submit(function() {
$.post('/request',{username:$("#username").val(),password:"test"},
function(data) {
$("#error").html(data['response']);
});
return false;
});
});
然后在cherrypy的方法里我这样做:
def request(self, **data):
# Then to access the data do the following
print data['<keyValue'] # In this example I would type print data['username']
其实很简单,就是有时候太专注细节,反而看不到整体。希望这能帮助到其他人。