我尝试使用angularJS使用cherryPy(返回JSON)。
在cherryPY方面我使用example code
import cherrypy
import json
inputs = [
{
'title': 'Lumberjack Song',
'artist': 'Canadian Guard Choir'
},
{
'title': 'Other Song',
'artist': 'artist'
}
]
class Inputs:
exposed = True
def GET(self, id=None):
if id is None:
cherrypy.response.headers['Content-Type'] = "application/json; charset=utf-8"
cherrypy.response.status = 200
print('Retour: %s' % inputs)
return(json.dumps(inputs))
else:
input = inputs[int(id)]
cherrypy.response.headers['Content-Type'] = "application/json; charset=utf-8"
cherrypy.response.status = 200
return(json.dumps(input))
if __name__ == '__main__':
cherrypy.tree.mount(
Inputs(), '/api/inputs',
{'/':
{'request.dispatch': cherrypy.dispatch.MethodDispatcher()}
}
)
cherrypy.engine.start()
cherrypy.engine.block()
当我测试时(使用Chrome REST插件):
http://localhost:8080/api/inputs it return the correct JSON information list of inputs
http://localhost:8080/api/inputs/1 it return the correct JSON input
我制作了一个angularJS服务:
'use strict';
angular.module('RaspBerry.Services', ['ngResource']).factory('Inputs', function ($resource) {
return $resource('http://localhost:port/api/inputs/:id', {"port":":9082"}, {
'query': { method: 'GET', format:'json', isArray: true },
'save': {method:'POST', isArray: false },
'update': {method:'PUT', isArray: false },
'delete': {method:'DELETE', isArray: false}
});
});
// app.factory
控制器代码
'use strict';
angular.module('RaspBerry.Controllers.Input_controller',[]).
controller("EntreeListController", ["$scope", "$location", "Inputs", function($scope, $location, Inputs) {
Inputs.query({},
function (data, status) {
$scope.entrees = data;
},function (data, status) {
}
);
}]
).controller("EntreeDetailController",["$scope", "$window", "$resource", "$routeParams", "$location", "notify", "Inputs", function($scope, $window, $resource, $routeParams, $location, notify, Inputs) {
Inputs.get({id:$routeParams.id},
function (data, status) {
$scope.input = data
},
function (input, status) {
console.log("KO " + status);
}
);
}]);
当我启动我的应用程序时,我的服务始终出错,状态= 0