简单的Django-swampdragon + AngularJS实时应用

时间:2015-05-10 17:24:53

标签: javascript python django angularjs sockets

我使用django-swampdragon + angularjs创建简单的django应用程序,实时显示网站请求。

所有Django逻辑都没问题,但是当我尝试让它实时响应时系统失败了。我认为问题出在Angular,因为我之前没有使用它。

所以,代码的django-swampdragon部分:

# routers.py 
from swampdragon import route_handler
from swampdragon.route_handler import ModelRouter

from .serializers import HttpRequestSerializer
from .models import HttpRequest


class HttpRequestRouter(ModelRouter):
    serializer_class = HttpRequestSerializer
    model = HttpRequest
    route_name = 'activity-route'

    def get_object(self, **kwargs):
        return self.model.objects.get(pk=kwargs['pk'])

    def get_query_set(self, **kwargs):
        return self.model.all()


route_handler.register(HttpRequestRouter)

代码的Angular.js部分

// controllers.js
var ActivityControllers = angular.module('ActivityControllers', []);

ActivityControllers.controller('ActivityCtrl', ['$scope', '$dragon', function ($scope, $dragon) {
    $scope.channel = 'httprequests';
    $scope.datasource = [];

    // Subscribe to the activity router
    $dragon.onReady(function() {
        $dragon.subscribe('activity-route', $scope.channel, {}).then(function(response) {
            this.dataMapper = new DataMapper(response.data);
        });
        $dragon.getList('activity-route', {}).then(function(response) {
            $scope.datasource = response.data
        });
    });

    $dragon.onChannelMessage(function(channels, new_request) {
        if (indexOf.call(channels, $scope.channel) > -1) {
            $scope.$apply(function() {
                $scope.datasource.unshift(new_request);
            });
        }
    });

}]);

最后,我的模板部分:

<div ng-controller="ActivityCtrl">
    <ul ng-repeat="req in datasource">
        <li>
            <span class="request_date">{$ req.date $} ...</span>
        </li>
    </ul>
</div>

当我运行server.py并在该url / port(http://localhost:9999/)上打开浏览器时出现此错误(在浏览器中):

Traceback (most recent call last):
  File "...lib/python3.4/site-packages/tornado/web.py", line 1323, in _execute
    result = self.prepare()
  File "...lib/python3.4/site-packages/tornado/web.py", line 2014, in prepare
    raise HTTPError(self._status_code)
tornado.web.HTTPError: HTTP 404: Not Found

在控制台上也出现了这个错误:

-------- SwampDragon ------
Running SwampDragon on 127.0.0.1:9999
DRAGON_URL: http://localhost:9999/
Version 0.4.2
Debug: True
Quit the server with ctrl+c
---------------------------
WARNING:tornado.access:404 GET / (127.0.0.1) 206.58ms

当然,我的请求页面也不起作用。

请帮助我找到错误!

1 个答案:

答案 0 :(得分:0)

可以肯定的是,您正在运行django服务器和swmapdragon服务器,对吗?正如你在做两件事:

  • python server.py
  • python manage.py runserver