Ember.js CherryPy收到来自emberjs RESTAdapter的空帖子
我正在探索使用CherryPy作为后端,使用emberjs作为前端,用于管理书籍列表的简单web应用程序。Cherrypy只是在请求索引时提供一个把手模板:Ember.js CherryPy收到来自emberjs RESTAdapter的空帖子,ember.js,cherrypy,Ember.js,Cherrypy,我正在探索使用CherryPy作为后端,使用emberjs作为前端,用于管理书籍列表的简单web应用程序。Cherrypy只是在请求索引时提供一个把手模板: import os import cherrypy from google.appengine.api import users from google.appengine.ext import ndb class Root: def __init__(self): # book REST API
import os
import cherrypy
from google.appengine.api import users
from google.appengine.ext import ndb
class Root:
def __init__(self):
# book REST API
self.books = BookAPI()
@cherrypy.expose
def index(self):
return open(os.path.join(template_env, 'index.hbs'))
我使用BooksAPI和Books类作为RESTfull API,使用Google数据存储来存储图书对象(我现在只存储isbn)
对于emberjs客户端,我使用RestaAdapter:
window.Books = Ember.Application.create();
Books.ApplicationAdapter = DS.RESTAdapter.extend();
我的书本模型定义如下:
Books.Book = DS.Model.extend({
isbn: DS.attr('string'),
});
我添加了以下书籍控制器:
Books.BookController = Ember.ObjectController.extend({
actions: {
removeBook: function() {
var book = this.get('model');
book.deleteRecord();
book.save();
}
}
});
Books.BooksController = Ember.ArrayController.extend({
actions: {
createBook: function() {
// get book isbn
var isbn = this.get('newIsbn');
if(!isbn.trim()) { return; }
// create new book model
var book = this.store.createRecord('book', {
isbn: isbn,
});
// clear the 'new book' text field
this.set('newIsbn', '');
// Save model
book.save();
}
}
});
最后是以下路线:
Books.Router.map(function () {
this.resource('books', { path: '/' });
});
Books.BooksRoute = Ember.Route.extend({
model: function() {
return this.store.find('book');
}
});
使用FixedAdapter添加和删除书籍有效,然后我切换到RESTAdapter
这个方法奏效了。Emberjs自动调用GET方法并成功获取index.hbs模板中显示的JSON格式的书籍列表
然而,emberjs以我意想不到的方式调用POST方法。似乎余烬发送了一篇空帖子,没有添加isbn作为帖子数据。因为当我从cherrypy POST函数中删除isbn关键字参数时,函数确实会被调用。我需要isbn来创建book对象
我可能忘记了一些显而易见的事情,但我不知道是什么。有人知道我忘记了什么或做错了什么吗?谢谢
Bastiaan为了保存新记录,Ember发送一个保存在帖子正文中的对象的json表示 就你的情况而言,我很高兴
book:{isbn:[the isbn value]}
因此,没有isbn参数
你能在你的post函数上测试这个吗
def POST(self):
# get the current user
user = users.get_current_user()
cl = cherrypy.request.headers['Content-Length']
rawbody = cherrypy.request.body.read(int(cl))
body = simplejson.loads(rawbody)
bookFromPost = body.book
# create book and save in data storage
parent_key = ndb.Key('Library', user.user_id())
book = Book(parent=parent_key, isbn=bookFromPost.isbn)
book.put()
您应该返回一个201创建的HTTP代码,其中包含指定id的书籍的json表示
book:{id:[the new id],isbn:[the isbn value]}
您在ember中的模型定义如何?我已经更新了这个问题,添加了ember book模型。这是我定义的唯一一个模型。很好,经过两个小小的修改,它工作了。body和bookFromPost都是字典,因此我需要使用body['book']而不是body.book,bookFromPost['isbn']而不是bookFromPost.isbn。谢谢,这就把事情弄清楚了。很抱歉,我没有要测试的环境,python对我来说不是很熟悉;-)
book:{id:[the new id],isbn:[the isbn value]}