Пример #1
0
 def runTest(self):
     uris = ['/items', '/users', '/items/teacup', '/users/bob',
             '/items/teacup/resource', '/users/bob/resource',
             '/items/teacup/users/bob', '/items/teacup/items/kettle',
             '/items/teacup/users/bob/resource', '/items/teacup/items/kettle/resource',
             '/users/bob/users/steve', '/users/bob/items/teacup',
             '/users/bob/users/steve/resource', '/users/bob/items/teacup/resource']
     for uri in uris:
         (root, resp) = treexml.decode(self.conn.get(uri))
         self.assertEqual(root, 'response')
         self.assertEqual(resp['status'][0]['type'][0], 'OKAY')
         self.assertEqual(resp['status'][0]['desc'][0], 'Query completed successfully.')
         sysusage = float(resp['system_usage'][0])
         self.assert_(sysusage > 0.0 and sysusage < 1.0)
     # GET /items
     (root, resp) = treexml.decode(self.conn.get('/items'))
     self.assertEqual(resp['itemlist'][0], '')
     # GET /users
     (root, resp) = treexml.decode(self.conn.get('/users'))
     self.assertEqual(resp['userlist'][0], '')
     # GET /users/bob
     (root, resp) = treexml.decode(self.conn.get('/users/bob'))
     self.assertEqual(resp['user'][0]['id'][0], 'bob')
     # GET /items/teacup
     (root, resp) = treexml.decode(self.conn.get('/items/teacup'))
     self.assertEqual(resp['item'][0]['id'][0], 'teacup')
Пример #2
0
 def runTest(self):
     req = {}
     treexml.insert_node(req, 'value', '5.0')
     reqxml = treexml.encode('request', req)
     (root, resp) = treexml.decode(self.conn.post('/users/bob/items/teacup/rating', reqxml))
     self.assertEqual(resp['status'][0]['type'][0], 'OKAY')
     (root, resp) = treexml.decode(self.conn.post('/users/bob/items/teacup/rating', '3'))
     self.assertEqual(resp['status'][0]['type'][0], 'OKAY')
     (root, resp) = treexml.decode(self.conn.post('/users/sally/items/teacup/rating', '2'))
     self.assertEqual(resp['status'][0]['type'][0], 'OKAY')
     (root, resp) = treexml.decode(self.conn.post('/users/john/items/teacup/rating', '4'))
     self.assertEqual(resp['status'][0]['type'][0], 'OKAY')
     (root, resp) = treexml.decode(self.conn.get('/users/bob/items/teacup/rating'))
     #self.assertEqual(len(resp['history'][0]['record']), 2)
     #self.assertEqual(resp['history'][0]['record'][0]['value'][0], '3.0')
     #self.assertEqual(resp['history'][0]['record'][1]['value'][0], '5.0')
     #self.assertEqual(resp['prediction'][0]['value'][0], '3.5')
     (root, resp) = treexml.decode(self.conn.get('/users/sally/items/teacup/rating'))
     self.assertEqual(len(resp['history'][0]['record']), 1)
     self.assertEqual(resp['history'][0]['record'][0]['value'][0], '2')
     #self.assertEqual(resp['prediction'][0]['value'][0], '3.5')
     (root, resp) = treexml.decode(self.conn.get('/users/sally/items/nonexist/rating'))
     #self.assertEqual(resp['prediction'][0]['value'][0], '0.0')
     self.assertEqual(resp['history'][0]['num_records'][0], '0')
     (root, resp) = treexml.decode(self.conn.post('/users/john/items/basket/rating', '1'))
     self.assertEqual(resp['status'][0]['type'][0], 'OKAY')
     (root, resp) = treexml.decode(self.conn.get('/users'))
     self.assertEqual(resp['userlist'][0]['id'][0], 'bob')
     self.assertEqual(resp['userlist'][0]['id'][1], 'john')
     self.assertEqual(resp['userlist'][0]['id'][2], 'sally')
     self.assertEqual(len(resp['userlist'][0]['id']), 3)
Пример #3
0
 def run(self):
     if self.resource == 'reserved':
         raise(errors.UnimplementedError)
     if self.method == 'get':
         raw_records = self.site.get_relations(self.type, self.name, 
                                               self.tgt_type, self.tgt_name, self.resource)
         records = [{'timestamp':[xmlext.convert_datetime(record[0])], 
                     'value':[record[1]]} 
                    for record in raw_records]
         treexml.insert_node(self.response, 'history', 
                             {'num_records':[repr(len(records))], 'record':records})
         prediction = self.site.get_naive_pred(self.tgt_type, self.tgt_name, self.resource)
         treexml.insert_node(self.response, 'prediction', {'value':[repr(prediction)]})
     else: # self.method == 'post':
         try:
             (root, doc) = treexml.decode(self.data)
             value = doc['value'][0]
         except treexml.DecodeError:
             try:
                 value = float(self.data)
             except ValueError:
                 raise(errors.PostError)
         self.site.insert_relation(self.type, self.name, 
                                   self.tgt_type, self.tgt_name,
                                   self.resource, value)
Пример #4
0
 def runTest(self):
     req = {}
     tags = {'name':'Bob', 'phone':'123-456-7890'}
     treexml.insert_node(req, 'meta', tags)
     reqxml = treexml.encode('request', req)
     (root, resp) = treexml.decode(self.conn.post('/users/bob', reqxml))
     self.assertEqual(resp['status'][0]['type'][0], 'OKAY')
     (root, resp) = treexml.decode(self.conn.get('/users/bob'))
     self.assertEqual(len(resp['user'][0]['meta'][0]), 2)
     self.assertEqual(resp['user'][0]['meta'][0]['phone'][0], '123-456-7890')
     self.assertEqual(resp['user'][0]['meta'][0]['name'][0], 'Bob')
     (root, resp) = treexml.decode(self.conn.post('/users/john/name', 'John'))
     (root, resp) = treexml.decode(self.conn.post('/users/sally/name', 'Sally'))
     (root, resp) = treexml.decode(self.conn.get('/users'))
     self.assertEqual(resp['userlist'][0]['id'][0], 'bob')
     self.assertEqual(resp['userlist'][0]['id'][1], 'john')
     self.assertEqual(resp['userlist'][0]['id'][2], 'sally')
     self.assertEqual(len(resp['userlist'][0]['id']), 3)
Пример #5
0
 def run(self):
     if self.method == 'get':
         meta = self.site.get_meta(self.type, self.name)
         treexml.insert_node(self.response[self.type][0], 'meta', meta)
     else: # self.method == 'post'
         (root, req) = treexml.decode(self.data)
         if 'meta' in req:
             meta = req['meta'][0]
             for tag in meta:
                 self.site.insert_meta(self.type, self.name, tag, meta[tag][0])
Пример #6
0
#!/usr/bin/env python

import treexml

if __name__ == '__main__':
    xml = ('<?xml version="1.0" ?><response><status><type>\nOKAY\n</type>' + 
           '<desc>Everything is just fine.</desc></status><empty/>' +
           '<time>2:08 AM</time><time>5:43 PM</time></response>')
    (root, doc) = treexml.decode(xml)
    print '\'%s\': %s' % (root, doc)
    print doc['status'][0]['desc'][0]
    print 'times: %s' % ', '.join(doc['time'])
    print treexml.encode(root, doc)
    print treexml.encode(root, doc['status'][0])
    
    r = {}
    print r
    msg = treexml.insert_node(r, 'message', {'text':['hello'],'language':['english']})
    print r
    #treexml.insert_node(r['message'], 'language', 'english')
    #print r
    print treexml.encode(root, r)
    
Пример #7
0
 def do_POST(self):
     if 'Content-length' not in self.headers:
         self.send_response(411)
         return;
     self.method = 'POST'
     self.resource = self.path
     contentLength = int(self.headers['Content-length'])
     reqxml = self.rfile.read(contentLength)
     (root, req) = treexml.decode(reqxml)
     data = req['data'][0]
     resp = {}
     startMoney = int(float(data['startMoney'][0]))
     endMoney = int(float(data['endMoney'][0]))
     startScore = int(float(data['startScore'][0]))
     endScore = int(float(data['endScore'][0]))
     startFrame = int(float(data['startFrame'][0]))
     endFrame = int(float(data['endFrame'][0]))
     sessionID = int(float(req['sessionID'][0]))
     gameNum = int(float(req['game'][0]['num'][0]))
     gamediff = int(float(req['game'][0]['diff'][0]))
     userName = req['id'][0]['name'][0]
     userGroup = req['id'][0]['group'][0]
     if userName == '':
         userName = '******'
     if userGroup == '':
         userGroup = 'River People'
     self.connect()
     valid_ipstr = self.conn.getone("SELECT ip FROM session_ip WHERE session_id = %s", (sessionID,))
     if not valid_ipstr:
         self.conn.query("INSERT INTO session_ip SET ip = %s, username = %s, usergroup = %s, session_id = %s", (self.get_client_ip(), userName, userGroup, sessionID))
         sessionID = self.conn.lastid()
         treexml.insert_node(resp, 'sessionID', str(sessionID))
     else:
         self.conn.query("UPDATE session_ip SET username = %s, usergroup = %s WHERE session_id = %s", (userName, userGroup, sessionID))
     #elif self.get_client_ip() != int(valid_ipstr):
     #    self.path = '/bad_session_number'
     #    self.respOK()
     #    #print 'Session IP mismatch, session %s does not belong to %s' % (sessionID, self.get_client_ip())
     #    return
     self.conn.query(("INSERT INTO scores " +
                      "SET session_id = %s, " +
                      "    game_num = %s, " +
                      "    game_type = %s, " +
                      "    score = %s, " +
                      "    score_delta = %s, " +
                      "    max_frame = %s, " +
                      "    start_time = CURRENT_TIMESTAMP " +
                      "ON DUPLICATE KEY UPDATE " +
                      "    score_delta = IF(%s - score > score_delta, %s - score, score_delta), " +
                      "    score = %s, " +
                      "    max_frame = %s"),
                     (sessionID, gameNum, gamediff, endScore, endScore, endFrame, 
                      endScore, endScore, endScore, endFrame)) 
     game_id = self.conn.getone("SELECT id FROM scores WHERE session_id = %s AND game_num = %s", (sessionID, gameNum))
     #print 'game id: %s, session id: %s, game num: %s' % (game_id, sessionID, gameNum)
     myrank = int(self.conn.getone("SELECT COUNT(*) FROM scores WHERE game_type = %s AND score > %s AND score > 100", (gamediff, endScore))) + 1
     numranks = max(1, int(self.conn.getone("SELECT COUNT(*) FROM scores WHERE game_type = %s AND score > 100", (gamediff,))))
     if data.has_key('frame'):
         for frame in data['frame']:
             id = int(frame['id'][0])
             if frame.has_key('buildGun'):
                 for rec in frame['buildGun']:
                     type = int(rec['type'][0])
                     self.conn.query("INSERT INTO guns SET game_id = %s, type = %s, build = 1 " +
                                "ON DUPLICATE KEY UPDATE build = build + 1", (game_id, type))
             if frame.has_key('upGun'):
                 for rec in frame['upGun']:
                     type = int(rec['type'][0])
                     self.conn.query("INSERT INTO guns SET game_id = %s, type = %s, upgrade = 1 " +
                                     "ON DUPLICATE KEY UPDATE upgrade = upgrade + 1", (game_id, type)) 
             if frame.has_key('sellGun'):
                 for rec in frame['sellGun']:
                     type = int(rec['type'][0])
                     self.conn.query("INSERT INTO guns SET game_id = %s, type = %s, sell = 1 " +
                                     "ON DUPLICATE KEY UPDATE sell = sell + 1", (game_id, type))
     self.conn.query("INSERT INTO replay SET game_id = %s, start_frame = %s, xml = %s", (game_id, startFrame, treexml.encode('data', data, None)))
     treexml.insert_node(resp, 'rank', str(myrank))
     percentile = max(1, min(99, 100.0 * (numranks - myrank) / numranks))
     treexml.insert_node(resp, 'percentile', '%.0f' % percentile)
     treexml.insert_node(resp, 'numplayers', str(self.get_num_online()))
     treexml.insert_node(resp, 'numspectators', '0')
     self.respOK()
     self.wfile.write(treexml.encode('rdresp', resp))
     self.conn.close()
Пример #8
0
 def render_POST(self, request):
     self.startreq(request, 'POST')
     if 'content-length' not in self.headers:
         return '';
     contentLength = int(self.headers['content-length'])
     request.content.seek(0, 0)
     reqxml = request.content.read(contentLength)
     (root, req) = treexml.decode(reqxml)
     data = req['data'][0]
     resp = {}
     startMoney = int(float(data['startMoney'][0]))
     endMoney = int(float(data['endMoney'][0]))
     startScore = int(float(data['startScore'][0]))
     endScore = int(float(data['endScore'][0]))
     startFrame = int(float(data['startFrame'][0]))
     endFrame = int(float(data['endFrame'][0]))
     sessionID = int(float(req['sessionID'][0]))
     gameNum = int(float(req['game'][0]['num'][0]))
     gamediff = int(float(req['game'][0]['diff'][0]))
     userName = req['id'][0]['name'][0]
     userGroup = req['id'][0]['group'][0]
     if userName == '':
         userName = '******'
     if userGroup == '':
         userGroup = 'River People'
     valid_ipstr = self.conn.getone("SELECT ip FROM session_ip WHERE session_id = %s", (sessionID,))
     if not valid_ipstr:
         self.conn.cquery("INSERT INTO session_ip SET ip = %s, username = %s, usergroup = %s, session_id = %s", (self.get_client_ip(), userName, userGroup, sessionID))
         sessionID = self.conn.lastid()
         treexml.insert_node(resp, 'sessionID', str(sessionID))
     else:
         row = self.conn.getrow("SELECT username, usergroup FROM session_ip WHERE session_id = %s", (sessionID,))
         if row['username'] != userName or row['usergroup'] != userGroup:
             self.conn.cquery("UPDATE session_ip SET username = %s, usergroup = %s WHERE session_id = %s", (userName, userGroup, sessionID))
     #elif self.get_client_ip() != int(valid_ipstr):
     #    self.path = '/bad_session_number'
     #    self.respOK()
     #    #print 'Session IP mismatch, session %s does not belong to %s' % (sessionID, self.get_client_ip())
     #    return
     row = self.conn.getrow("SELECT id, score, score_delta FROM scores WHERE session_id = %s AND game_num = %s", (sessionID, gameNum))
     if not row:
         self.conn.cquery(("INSERT INTO scores " +
                           "SET session_id = %s, " +
                           "    game_num = %s, " +
                           "    game_type = %s, " +
                           "    score = %s, " +
                           "    score_delta = %s, " +
                           "    max_frame = %s, " +
                           "    start_time = CURRENT_TIMESTAMP "),
                          (sessionID, gameNum, gamediff, endScore, endScore, endFrame))
         game_id = self.conn.lastid()
     else:
         game_id = row['id']
         lastScore = row['score']
         scoreDelta = row['score_delta']
         scoreDelta = max(scoreDelta, endScore - lastScore)
         self.conn.cquery(("UPDATE scores " +
                           "SET score_delta = %s, " +
                           "    score = %s, " +
                           "    max_frame = %s " +
                           "WHERE id = %s"),
                          (scoreDelta, endScore, endFrame, game_id))
     #print 'game id: %s, session id: %s, game num: %s' % (game_id, sessionID, gameNum)
     #myrank = int(self.conn.getone("SELECT COUNT(*) FROM scores WHERE game_type = %s AND score > %s", (gamediff, endScore))) + 1
     #numranks = max(1, int(self.conn.getone("SELECT COUNT(*) FROM scores WHERE game_type = %s", (gamediff,))))
     (myrank, numranks) = getMyRankAndNumRanks(gamediff, endScore)
     if data.has_key('frame'):
         for frame in data['frame']:
             id = int(frame['id'][0])
             if frame.has_key('buildGun'):
                 for rec in frame['buildGun']:
                     type = int(rec['type'][0])
                     self.conn.query("INSERT INTO guns SET game_id = %s, type = %s, build = 1 " +
                                      "ON DUPLICATE KEY UPDATE build = build + 1", (game_id, type))
             if frame.has_key('upGun'):
                 for rec in frame['upGun']:
                     type = int(rec['type'][0])
                     self.conn.query("INSERT INTO guns SET game_id = %s, type = %s, upgrade = 1 " +
                                      "ON DUPLICATE KEY UPDATE upgrade = upgrade + 1", (game_id, type))
             if frame.has_key('sellGun'):
                 for rec in frame['sellGun']:
                     type = int(rec['type'][0])
                     self.conn.query("INSERT INTO guns SET game_id = %s, type = %s, sell = 1 " +
                                      "ON DUPLICATE KEY UPDATE sell = sell + 1", (game_id, type))
         self.conn.commit('guns commit')
     del data['startMoney']
     del data['endMoney']
     del data['startScore']
     del data['endScore']
     self.conn.cquery("INSERT INTO replay SET game_id = %s, start_frame = %s, xml = compress(%s)", (game_id, startFrame, treexml.encode('data', data, None)))
     treexml.insert_node(resp, 'rank', str(myrank))
     percentile = max(1, min(99, 100.0 * (numranks - myrank) / numranks))
     treexml.insert_node(resp, 'percentile', '%.0f' % percentile)
     treexml.insert_node(resp, 'numplayers', str(self.get_num_online()))
     treexml.insert_node(resp, 'numspectators', '0')
     treexml.insert_node(resp, 'gameid', str(game_id))
     self.respOK()
     self.send(treexml.encode('rdresp', resp))
     return self.finishreq()