Using Tornado-JSON
authorBen Doumenc <bdoumenc@parkeon.com>
Sun, 26 Jul 2015 12:18:32 +0000 (14:18 +0200)
committerBen Doumenc <bdoumenc@parkeon.com>
Sun, 26 Jul 2015 12:18:32 +0000 (14:18 +0200)
r15k/engine/game.py
r15k/engine/ids.py [new file with mode: 0644]
r15k/engine/world.py
r15k/server/app/__init__.py [new file with mode: 0644]
r15k/server/app/api.py [new file with mode: 0644]
r15k/server/server.py
r15k/server/user.py [new file with mode: 0644]
r15k/web/js/api.js
r15k/www/app/utils.js

index f213fd3..3c777bf 100644 (file)
@@ -1,8 +1,8 @@
 # -*- coding: utf-8 -*-
 
 import logging
-import uuid
 
+from r15k.engine.ids import new_id
 from r15k.engine.turn import Turn
 
 logger = logging.getLogger('r15k.game')
@@ -13,7 +13,7 @@ class Game:
         self.oldTurns = []
         self.currentTurn = Turn()
         self.isRunning = True
-        self.uid = str(uuid.uuid4())
+        self.uid = new_id()
         self.players = []
 
     def update(self):
@@ -44,7 +44,7 @@ class Game:
 class Player:
     def __init__(self, name):
         self.name = name
-        self.uid = str(uuid.uuid4())
+        self.uid = new_id()
 
     def dump(self):
         data = {}
diff --git a/r15k/engine/ids.py b/r15k/engine/ids.py
new file mode 100644 (file)
index 0000000..4cef9c4
--- /dev/null
@@ -0,0 +1,8 @@
+# -*- coding: utf-8 -*-
+
+import uuid
+
+
+def new_id():
+    return str(uuid.uuid4().hex)
+
index bb3bb39..201fbfb 100644 (file)
@@ -4,8 +4,8 @@ import random
 import itertools
 import networkx as nx
 import logging
-import uuid
 
+from r15k.engine.ids import new_id
 from r15k.atomic.atomic import Atomic
 import r15k.engine.graph as GraphGenerator
 
@@ -40,7 +40,7 @@ class World:
         self.nodes = {}
         self.corps = []
         self.graph = None
-        self.uid = str(uuid.uuid4())
+        self.uid = new_id()
 
     def addNode(self, node):
         self.nodes[node.name] = node
diff --git a/r15k/server/app/__init__.py b/r15k/server/app/__init__.py
new file mode 100644 (file)
index 0000000..e69de29
diff --git a/r15k/server/app/api.py b/r15k/server/app/api.py
new file mode 100644 (file)
index 0000000..a8bf1eb
--- /dev/null
@@ -0,0 +1,34 @@
+# -*- coding: utf-8 -*-
+
+import logging
+import json
+
+from tornado_json.requesthandlers import APIHandler
+from tornado_json import schema
+
+from r15k.engine.world import World
+from r15k.engine.game import Game
+from r15k.server.datastore import Datastore
+
+logger = logging.getLogger('r15k.api')
+
+games = Datastore("/tmp/games")
+
+class GamesHandler(APIHandler):
+    def get(self, id=None):
+        if id:
+            if games.has_key(str(id)):
+                self.write(games.get(str(id)).dump())
+                return
+        self.write({"games": games.keys()})
+
+    def post(self):
+        logger.info("GAMES:Got %s" % (self.request.body))
+        data = json.loads(self.request.body)
+        if (data and data.has_key("size") and data.has_key("seed")):
+            W = World()
+            W.create(data)
+            game = Game(W)
+            games.save(game.uid, game)
+            self.write({"uid": game.uid})
+
index 42522a6..eeb6d69 100644 (file)
@@ -1,3 +1,4 @@
+# -*- coding: utf-8 -*-
 
 import os
 import signal
@@ -5,7 +6,6 @@ import sys
 import logging
 import json
 
-
 # root path
 rootPath = os.path.abspath(os.path.join(os.path.dirname(os.path.realpath(__file__)), ".."))
 sys.path.append(os.path.join(rootPath, ".."))
@@ -13,41 +13,14 @@ sys.path.append(os.path.join(rootPath, ".."))
 import tornado.ioloop as loop
 import tornado.web as web
 
-from r15k.engine.world import World
-from r15k.engine.game import Game
-from r15k.server.datastore import Datastore
-
+from tornado_json.routes import get_routes
+from tornado_json.application import Application
 
 # configuration
 logging.basicConfig(level=logging.DEBUG, format='%(asctime)s %(levelname)-8s %(name)-25s %(message)s')
 logger = logging.getLogger('r15k.server')
 logger.info("Starting with rootPath='%s'" % rootPath)
 
-DEBUG = True
-SECRET_KEY = 'development key'
-
-games = Datastore("/tmp/games")
-
-
-class GamesHandler(web.RequestHandler):
-    def get(self, id=None):
-        if id:
-            if games.has_key(str(id)):
-                self.write(games.get(str(id)).dump())
-                return
-        self.write({"games": games.keys()})
-
-    def post(self):
-        logger.info("GAMES:Got %s" % (self.request.body))
-        data = json.loads(self.request.body)
-        if (data and data.has_key("size") and data.has_key("seed")):
-            W = World()
-            W.create(data)
-            game = Game(W)
-            games.save(game.uid, game)
-            self.write({"uid": game.uid})
-
-
 class NoCacheStaticFileHandler(web.StaticFileHandler):
     def set_extra_headers(self, path):
         # Disable cache
@@ -55,13 +28,16 @@ class NoCacheStaticFileHandler(web.StaticFileHandler):
 
 
 def make_app():
-    return web.Application([
-            (r"/games$", GamesHandler),
-            (r"/games/([\w\d-]+$)", GamesHandler),
-            (r"/(.*)", NoCacheStaticFileHandler, {"path": os.path.join(rootPath, "www/"), "default_filename": "index.html"}),
-        ],
-        debug=True,
+    import app
+    routes = get_routes(app)
+    print("Routes\n======\n\n" + json.dumps(
+        [(url, repr(rh)) for url, rh in routes],
+        indent=2)
     )
+    routes.append((r"/(.*)", NoCacheStaticFileHandler, {"path": os.path.join(rootPath, "www/"), "default_filename": "index.html"}))
+    # Create the application by passing routes and any settings
+    application = Application(routes=routes, settings={"debug":True})
+    return application
 
 
 def on_exit(sig, func=None):
diff --git a/r15k/server/user.py b/r15k/server/user.py
new file mode 100644 (file)
index 0000000..f7a3cca
--- /dev/null
@@ -0,0 +1,7 @@
+# -*- coding: utf-8 -*-
+
+class User:
+    def __init__(self, login):
+        self.login = login
+
+
index 0f814cd..9c2b227 100644 (file)
@@ -22,7 +22,7 @@ module.gameNew = function gameNew(settings) {
     settings = defaultSettings(settings, {size: 30, seed: 1});
     $.ajax({
         type: "POST",
-        url: remoteHost + "/games",
+        url: remoteHost + "/api/games",
         data: JSON.stringify({size: settings.size, seed: settings.seed}),
         contentType: "application/json; charset=utf-8",
         dataType: "json",
@@ -35,7 +35,7 @@ module.gameListGet = function gameGet(settings) {
     settings = defaultSettings(settings);
     $.ajax({
         type: "GET",
-        url: remoteHost + "/games",
+        url: remoteHost + "/api/games",
         success: settings.success,
         failure: settings.failure
     });
@@ -45,7 +45,7 @@ module.gameGet = function gameGet(settings) {
     settings = defaultSettings(settings);
     $.ajax({
         type: "GET",
-        url: remoteHost + "/games/" + settings.uid,
+        url: remoteHost + "/api/games/" + settings.uid,
         success: settings.success,
         failure: settings.failure
     });
index fa80ebe..4a476a6 100644 (file)
@@ -74,7 +74,7 @@ define(['jquery', 'bullet', 'vis'], function($, Bullet, Vis){
         settings = defaultSettings(settings, {size: 30, seed: 1});
         $.ajax({
             type: "POST",
-            url: remoteHost + "/games",
+            url: remoteHost + "/api/games",
             data: JSON.stringify({size: settings.size, seed: settings.seed}),
             contentType: "application/json; charset=utf-8",
             dataType: "json",
@@ -87,7 +87,7 @@ define(['jquery', 'bullet', 'vis'], function($, Bullet, Vis){
         settings = defaultSettings(settings);
         $.ajax({
             type: "GET",
-            url: remoteHost + "/games",
+            url: remoteHost + "/api/games",
             success: settings.success,
             failure: settings.failure
         });
@@ -97,7 +97,7 @@ define(['jquery', 'bullet', 'vis'], function($, Bullet, Vis){
         settings = defaultSettings(settings);
         $.ajax({
             type: "GET",
-            url: remoteHost + "/games/" + settings.uid,
+            url: remoteHost + "/api/games/" + settings.uid,
             success: settings.success,
             failure: settings.failure
         });