def funders(): """ Apart from Sime Darby at the top, the funder information is stored in a JSON file that provides rows of sets of funders. Each row contains a number of image/link pairs, and an overall row height. The code below packages them into bootstrap rows of DIVs with centred, containing, non-repeating background images. The number of links in a row should pack into the bootstrap 12 column grid! """ # load funders from the json data f = os.path.join(request.folder, 'static', 'info', 'funders.json') content = simplejson.load(open(f)) funders = [] for r in content: row_class = 'img-responsive col-sm-' + str(12 / len(r['links'])) links = [ A(DIV( _style='background-image:url(' + URL('static', str(ln['image'])) + ');' + 'background-size:contain;background-repeat: no-repeat;background-position:center;' + 'height:' + r['height'], _class=row_class), _href=ln['url']) for ln in r['links'] ] funders.append(DIV(*links, _class='row', _style='margin:20px 0px;')) return dict(funders=funders)
def logistics(): # load costs from the json data f = os.path.join(request.folder, 'static', 'info', 'costs.json') costs = simplejson.load(open(f)) return dict(costs=costs, frm=get_frm())
def register_score(): """Register a player's accomplishment. The required URL format is /register-score/mode/difficulty, where * mode in {normal, time}, and * difficulty in {easy, normal, hard}. Expects request body in JSON of the form { "player" : <string> , "score" : <number> } Returns with HTTP(200) if no errors happened. """ mode, difficulty = request.args accomplishment = load(request.body) db.scores.insert( mode=mode, difficulty=difficulty, name=accomplishment['player'], score=accomplishment['score'], time_of_acmnt=datetime.now()) raise HTTP(200, 'Accomplishment saved.')
def json2tree(cls, source, format=None): """ Converts JSON into an element tree @param source: the JSON source @param format: name of the XML root element """ try: root_dict = json.load(source) except (ValueError,): e = sys.exc_info()[1] raise HTTP(400, body=cls.json_message(False, 400, e)) native=False if not format: format=cls.TAG.root native=True if root_dict and isinstance(root_dict, dict): root = cls.__obj2element(format, root_dict, native=native) if root: return etree.ElementTree(root) return None
def rpc_request(pars, vars=None, password=None, test=None): if test: vars['test_payment'] = True vars['test_result'] = test if vars: vars = urllib.urlencode(vars) #print 'rpc VARS:', vars rq = urllib2.Request(pars, vars) else: rq = urllib2.Request(pars) ##rq.add_header('Authorization', 'Bearer ' + token) #return rq # платеж в процессе - ожидаем и потом еще раз запросим try: f = urllib2.urlopen(rq) #r = f.read() r = json.load(f) #print 'response - res:', r except Exception as e: from gluon import current # или любая ошибка - повтор запроса - там должно выдать ОК #print 'YmToConfirm while EXEPTION:', e log(current.db, 'rpc ' + pars + ' EXEPTION: %s' % e) return e #time.sleep(1) return r
def json2tree(cls, source, format=None): """ Converts JSON into an element tree @param source: the JSON source @param format: name of the XML root element """ try: root_dict = json.load(source) except (ValueError, ): e = sys.exc_info()[1] raise HTTP(400, body=cls.json_message(False, 400, e)) native = False if not format: format = cls.TAG.root native = True if root_dict and isinstance(root_dict, dict): root = cls.__obj2element(format, root_dict, native=native) if root: return etree.ElementTree(root) return None
def clean_file_cache(user_id): start = datetime.datetime.now() try: path = 'applications/menuet/cache/cache_' + str(user_id) # Remove user cache os.remove(path) except Exception as e: logger.error('We failed to clean user cache with ' + str(e) + " " + str(e.message)) try: master_file = 'applications/menuet/cache/cache_master' # remove user_id and its cache data from master_file # OPen master for read f = open(master_file, 'r+') # read all lines master_cache = simplejson.load(f) master_cache = [x for x in master_cache if x['user_id'] != user_id] # return to start of the file and rewrite whole file # TODO: maybe slow f.close() f = open(master_file, 'w') simplejson.dump(master_cache, f) f.close() except Exception as e: logger.error('We failed to clean master cache with ' + str(e) + " " + str(e.message)) finally: end = datetime.datetime.now() - start logger.warning("we finished clean cache in " + str(end)) pass
def activateBeacon(): uemail=request.vars.uemail password=request.vars.password b_name=request.vars.b_name b_f_id=request.vars.b_f_id valid_usr=authenticate(uemail,password) if valid_usr: usr_role=getuserrole(uemail) if(usr_role=="admin"): import urllib, urllib2, base64 data={"name":b_name,"factory_id":b_f_id} data_json = json.dumps(data) headers = { 'Authorization': 'Token token=f50ccc1aab3314434ae32dada87312cb', 'Content-Type': 'application/json' } req = urllib2.Request( 'https://manager.gimbal.com/api/beacons',data_json, headers) res=json.load(urllib2.urlopen(req)) if(res) : code=200 rows =db (db.beacons.b_factory_id==b_f_id).select() if rows: for row in rows: row.update_record(beacon_status="Active") message="success" return json.dumps(dict(message=message)) else : code=412 message="error" else: code=401 message="user not authorized" else: code=412 message="User not Authenticated" response.headers['Content-Type']='application/json' response.status=int(code) return json.dumps(dict(message=message)) return None
def YmGetBalanse(api_pars, token, acc_name): """ Make an API call - requests account info """ rq = urllib2.Request(api_pars['URI_YM_API'] + '/account-info', '') rq.add_header('Authorization', 'Bearer ' + token) try: f = urllib2.urlopen(rq) except Exception as e: print 'YmGetBalanse ', acc_name, e return {'error': e, 'status': 'unauthorized', 'balance': None} r = json.load(f) #print r.get('balance') return r #.get('balance')
def YmGetPayInfo(api_pars, token, pay_id): """ Make an API call - requests account info """ rq = urllib2.Request(api_pars['URI_YM_API'] + '/operation-details', 'operation_id=%s' % pay_id) rq.add_header('Authorization', 'Bearer ' + token) try: f = urllib2.urlopen(rq) except Exception as e: print 'YmGetPayInfo ', pay_id, e return {'error': e, 'status': 'unauthorized', 'balance': None} r = json.load(f) #print r.get('balance') return r #.get('balance')
def get_history_pars(edlr, edlr_acc, pars): api_pars, acc_pars, name = get_pars(edlr, edlr_acc) token = edlr_acc.skey """ Make an API call - requests account info """ rq = urllib2.Request(api_pars['URI_YM_API'] + '/operation-history', pars) rq.add_header('Authorization', 'Bearer ' + token) try: f = urllib2.urlopen(rq) except Exception as e: print 'get_incoms %s \n PARS: %s' % (e, pars) return {'error': e, 'status': 'unauthorized', 'get_incoms': None} r = json.load(f) #print r.get('balance') return r #.get('balance')
def YmOauthRedirectHandler(api_pars, acc_pars, code): """ Oauth redirect handler. User browser will be redirected here at second step of Oauth. Requests access token in exchange for request token (code) provided be yandex.money as the redirect parameter. """ #print 'CODE', code data = { 'client_id': acc_pars['CLIENT_ID'], 'grant_type': 'authorization_code', 'redirect_uri': acc_pars['YM_REDIRECT_URI'], 'code': code } f = urllib.urlopen(api_pars['URI_YM_TOKEN'], urllib.urlencode(data)) r = json.load(f) return r
def update_gazetteer(): """ This controller reloads the contents of the gazetteer table and the alias table from the files provided in static and then updates the UTM50N geometry field. The geojson file used here is the one provided by the api/locations endpoint, and so this function also clears the ram cache providing the file hash of gazetteer.geojson, so that the next call to versions_index will repopulate it with the new file hash Note that this relies on web2py 2.18.5+, which includes a version of PyDAL that supports st_transform. """ # GAZETTEER - drop the current contents db.gazetteer.truncate() # Refill the tables from the static resource gazetteer_path = os.path.join(request.folder, 'static', 'files', 'gis', 'gazetteer.geojson') with open(gazetteer_path, 'r') as f: gazetteer_json = simplejson.load(f) # Get the features from within the geojson features = gazetteer_json['features'] # Loop over the features, inserting the properties and using shapely to convert # the geojson geometry to WKT, prepending the PostGIS extended WKT statement of # the EPSG code for the geometry for ft in features: fields = ft['properties'] fields['wkt_wgs84'] = "SRID=4326;" + shape(ft['geometry']).wkt db.gazetteer.insert(**fields) # Recalculate the UTM50N geometries - using the extended pydal GIS db(db.gazetteer).update( wkt_utm50n=db.gazetteer.wkt_wgs84.st_transform(32650)) # GAZETTEER ALIASES - drop the current contents db.gazetteer_alias.truncate() # Repopulate from the file. gazetteer_alias_csv = os.path.join(request.folder, 'static', 'files', 'gis', 'location_aliases.csv') db.gazetteer_alias.import_from_csv_file(open(gazetteer_alias_csv, 'r'), null='null') # Clear the ram cache of the outdated version. cache.ram('version_stamps', None)
def YmToConfirm(pars_in, api_pars, token, test=None): pars = { # 'pattern_id': pars_in['pattern_id'], 'request_id': pars_in['request_id'], 'money_source': 'wallet', #'test_payment': True, #'test_result': 'limit_exceeded', } if test: pars['test_payment'] = True pars['test_result'] = test pars = urllib.urlencode(pars) print 'YmToConfirm PARS:', pars rq = urllib2.Request(api_pars['URI_YM_API'] + '/process-payment', pars) rq.add_header('Authorization', 'Bearer ' + token) #return rq while True: # платеж в процессе - ожидаем и потом еще раз запросим try: f = urllib2.urlopen(rq) r = json.load(f) print 'YmToConfirm while status not in_proggress - res:', r if r['status'] != 'in_progress': # платеж не а поцессе - выходим из проверки окончания платежа break except Exception as e: from gluon import current # или любая ошибка - повтор запроса - там должно выдать ОК #print 'YmToConfirm while EXEPTION:', e log(current.db, 'YmToConfirm while EXEPTION: %s' % e) pass time.sleep(20) pass ''' если УСПЕХ! balance : 42.24 invoice_id : 2000106905131 payment_id : 434450183282000006 status : success ''' return r
def research_areas(): """ Loads an image and some blurb from a JSON file for each research area and looks up the number of projects associated with each area """ # get the research areas of the most recent version of approved projects proj_query = db((db.project_id.project_details_id == db.project_details.id) & (db.project_details.admin_status == 'Approved')) research_areas = proj_query.select(db.project_details.research_areas) ra_list = [r.research_areas for r in research_areas] ra_list = [item for sublist in ra_list for item in sublist] ra_table = Counter(ra_list) f = os.path.join(request.folder, 'static', 'info', 'research_areas.json') content = simplejson.load(open(f)) content_formatted = [] for k in list(content.keys()): block = DIV( H3(k), DIV(IMG(_src=URL('static', str(content[k]['image'])), _width=150, _align='left', _style='margin:0px 15px 15px 0px'), _class="media-left"), DIV(P(XML(content[k]['text'])), P( B(ra_table[k], ' projects'), ' are currently tagged with this research area. See them ', A('here', _href=URL( 'projects', 'projects', vars={ 'keywords': 'project_details.research_areas contains "' + k + '"' }))), _class="media-body")) content_formatted.append(block) return dict(content=content_formatted)
def write_to_cache(user_id, weighted_result, query): # add to cache if len(weighted_result) > 0: # Create new cache for the results file = open('applications/menuet/cache/cache_' + str(user_id), 'w') _ = { "user_id": user_id, "items": jsonpickle.dumps(weighted_result, unpicklable=False), "curr_pos": 0, "sorted": None } # dumps this results simplejson.dump(_, file) file.close() import os # do we have master cache? if os.path.isfile('applications/menuet/cache/cache_master'): # create with list if doesnt have master file with open('applications/menuet/cache/cache_master', 'w') as master_file: simplejson.dump([], master_file) # populate master with info about new created cache with open('applications/menuet/cache/cache_master', mode='r+') as feedsjson: feedsjson.seek(0) entry = { "user_id": user_id, "time_created": str(time.time()), "last_query": query } try: feeds = simplejson.load(feedsjson) except Exception as e: logger.error("something broken in cache creation " + str(e) + str(e.message)) feeds = [] feeds.append(entry) feedsjson.seek(0) simplejson.dump(feeds, feedsjson) return True return None
def register_score(): """Register a player's accomplishment. The required URL format is /register-score/mode/difficulty, where * mode in {normal, time}, and * difficulty in {easy, normal, hard}. Expects request body in JSON of the form { "player" : <string> , "score" : <number> } Returns with HTTP(200) if no errors happened. """ mode, difficulty = request.args accomplishment = load(request.body) db.scores.insert(mode=mode, difficulty=difficulty, name=accomplishment['player'], score=accomplishment['score'], time_of_acmnt=datetime.now()) raise HTTP(200, 'Accomplishment saved.')
def load(fp, cls=simplejson.JSONDecoder, object_hook=None, **kwargs): return simplejson.load(fp, cls=cls, object_hook=object_hook, **kwargs)
def addbeacon(): uemail=request.vars.uemail password=request.vars.password beacon_name=request.vars.beacon_name b_factory_id=request.vars.b_factory_id beacon_lat="" beacon_long="" beacon_status="Active" valid_usr=authenticate(uemail,password) if valid_usr: usr_role=getuserrole(uemail) if(usr_role=="admin"): #insert into gimbal server and get place-id , place_lat, place_long import urllib, urllib2, base64 data={"name":beacon_name,"factory_id":b_factory_id} data_json = json.dumps(data) headers = { 'Authorization': 'Token token=f50ccc1aab3314434ae32dada87312cb', 'Content-Type': 'application/json' } req = urllib2.Request( 'https://manager.gimbal.com/api/beacons',data_json, headers) res=json.load(urllib2.urlopen(req)) beacon_id=res["id"] b_battery_lvl=res["battery_level"] #insert into datastore b_id=db.smartapp_beacons.insert(beacon_id=beacon_id,beacon_name=beacon_name,beacon_factory_id=b_factory_id,beacon_lat=beacon_lat,beacon_long=beacon_long,beacon_status=beacon_status,beacon_battery_lvl=b_battery_lvl) if(b_id) : message="success" return json.dumps(dict(message=message)) else : code=412 message="error" else: code=401 message="user not authorized" else: code=412 message="User not Authenticated" response.headers['Content-Type']='application/json' response.status=int(code) return json.dumps(dict(message=message)) return None
def get_from_cache(user_id, count, query, sort): try: master_file = open('applications/menuet/cache/cache_master', 'r+') except IOError: master_file = open('applications/menuet/cache/cache_master', 'wb') master_file.close() master_file = open('applications/menuet/cache/cache_master', 'r+') try: cache_items = simplejson.loads(master_file.read()) except JSONDecodeError: return {'msg': 'none'} except Exception as e: logger.error("we broke cache" + str(e) + str(e.message)) return {'msg': 'none'} cache_items = clean_if_stale(cache_items, user_id) if cache_items is None or len(cache_items) == 0: return {'msg': 'none'} try: for item in cache_items: # find requested data for user by id if item['user_id'] == user_id: # if we found record - do we have data ? path = 'applications/menuet/cache/cache_' + str(user_id) if item.get('last_query') != query: clean_file_cache(user_id) with open(path, 'r+') as f: cached = simplejson.load(f) if sort == 'None' or sort is None: r = simplejson.loads( cached['items'])[int(cached['curr_pos'] ):int(cached['curr_pos']) + count] else: # sorting by user request with unknown initial state if cached['sorted'] is None or cached[ 'sorted'] == 'None' or sort != cached['sorted']: # reset curr_pos to start anew cached['curr_pos'] = 0 # load everything r = simplejson.loads(cached['items']) # sort by user request r = sort_result(r, sort) cached['sorted'] = sort # sore all result inside our cache file cached['items'] = simplejson.dumps(r) elif cached['curr_pos'] >= len( simplejson.loads(cached['items'])): # we dont need our cache file now - close f.close() # remove cache because we showed to user everything os.remove(path) return {'msg': 'no more'} r = simplejson.loads( cached['items'])[int(cached['curr_pos'] ):int(cached['curr_pos']) + count] cached['curr_pos'] += count if len(r) == 0: f.close() # do we need to delete cache ? os.remove(path) return {'msg': 'no more'} else: f.seek(0) simplejson.dump(cached, f) return {'msg': 'ok', 'items': r} except Exception as e: # TODO:re design logger.error('we failed to fetch from cache with ' + str(e.message) + str(e)) return {'msg': 'none'} return {'msg': 'none'}
def addplace(): uemail=request.vars.uemail password=request.vars.password place_desc=request.vars.place_desc place_name=request.vars.place_name place_addr=request.vars.place_addr place_lat="" place_long="" valid_usr=authenticate(uemail,password) if valid_usr: usr_role=getuserrole(uemail) if(usr_role=="admin"): #insert into gimbal server and get place-id , place_lat, place_long import urllib, urllib2, base64 data={"name":place_name} data_json = json.dumps(data) headers = { 'Authorization': 'Token token=f50ccc1aab3314434ae32dada87312cb', 'Content-Type': 'application/json' } req = urllib2.Request( 'https://manager.gimbal.com/api/v2/places',data_json, headers) res=json.load(urllib2.urlopen(req)) place_id=res["id"] #insert into datastore pl_id=db.smartapp_places.insert(pl_id=place_id,pl_desc=place_desc,pl_name=place_name,pl_address1=place_addr,pl_lat=place_lat, pl_long=place_long) if(pl_id) : code=200 message="success" return json.dumps(dict(message=message)) else : code=412 message="error" else: code=401 message="user not authorized" else: code=412 message="User not Authenticated" response.headers['Content-Type']='application/json' response.status=int(code) return json.dumps(dict(message=message))
def YmTo(db, deal, edlr_deal, api_pars, token, acc, amount, acc_name, test=None, log_on=None, pars_in=None): if edlr_deal.scid == 'phone-topup': if False and len(acc) == 11 and acc[0:1] == '7': ph = acc[1:] else: ph = acc #print ph pars = { 'pattern_id': edlr_deal.scid, 'phone-number': ph, # 'PROPERTY1': ph[0:3], # 'PROPERTY2': ph[3:], 'amount': amount, 'comment': u'7Pay to phone: %s' % acc, 'message': u'from 7Pay.in', #'test_result': 'phone_unknown', } elif edlr_deal.scid == 'p2p': #return {'error': 'p2p not support', 'status':'p2p not support'} pars = { 'pattern_id': edlr_deal.scid, 'to': acc, 'amount': amount, 'comment': u'7Pay to wallet: %s' % acc, 'message': u'from 7Pay.in', } elif edlr_deal.p2p: # это подключенный к нам магазин через яндекс кошелек # тут закодируем счет пользователя id_name = u'7Pay: %s' % acc pars = { 'pattern_id': 'p2p', 'to': edlr_deal.scid, 'amount': amount, 'title': id_name, 'label': id_name, 'comment': id_name, 'message': id_name } #pars['label'] = pars['message'] else: # это магазин и там иднтификатор #print type(deal) if type(deal) == type(''): name = deal else: name = deal.name #.decode('utf8') #'cp1251') #print name pars = { 'pattern_id': edlr_deal.scid, 'comment': '7Pay to %s for [%s]' % (name, acc), 'message': u'from 7Pay.in', #current.T('from 7Pay.in'), #'test_result': 'shop_unknown', } # добавим параметры из шаблона магазина if not pars_in: make_pay_pars(deal, edlr_deal, api_pars, acc, amount, pars) pars['label'] = pars['message'] pars['title'] = pars['message'] #print pars #if 'user' not in pars: # return {'error': 'user=None', 'status':'user not setted'} if test: pars['test_payment'] = True pars['test_result'] = test if 'test_result' in pars: pars['test_payment'] = True #print pars_in pars = pars_in or pars # если заданы комисии то сразу их введем fees = pars.get('_calcs_') fees = fees and fees.get('_fees') if fees: amo = float(pars['sum']) # <fee a="0.02" c="30" netAmount="netSum"/> # "_fees": { "a": "0.02", "c": "30", "netAmount": "netSum"} a = float(fees.get('a', 0)) c = float(fees.get('c', 0)) fee = amo * a if fee < c: fee = c pars[fees['netAmount']] = amo - fee # сохраним параметры без примечаний и сообщений для ЛОГа pars_uncomment = pars.copy() for k in ['comment', 'FormComment', 'message', 'title', 'label']: pars_uncomment.pop(k, None) pars = urllib.urlencode(pars) #print 'PARS:',pars #return pars rq = urllib2.Request(api_pars['URI_YM_API'] + '/request-payment', pars) rq.add_header('Authorization', 'Bearer ' + token) #print rq #logging.Logger.debug(rq) try: f = urllib2.urlopen(rq) except Exception as e: print 'ERROR YmTo ', acc_name, e, print 'e.errno, e.strerror:', e.errno, e.strerror ## была такая ошибка а потом нормально заплтило - но pay_ins - в процессе остался TODO - сделать игнорирование такой ошибки - на повтор ## res={'_acc': '79092111110', '_acc_name': 'Yandex:410012071750033', 'error': URLError(error(10054, 'An existing connection was forcibly closed by the remote host'),), 'status': 'Exception'} return { 'error': e, 'status': 'Exception', '_acc_name': acc_name, '_acc': acc } r = json.load(f) ''' данные ан выходе почемуто пишет успех но денег то на счете нету! balance : 49.24 contract : Оплата услуг сотовой связи МТС Реквизиты платежа: Cумма платежа: 12345.00 RUB Телефон: 9169172019 Номер транзакции: 2000106896738 money_source : request_id : 3731303332363133385f623537333864323962616438633061396637383733393965396131323937343639326231373332305f3332333937303939 status : success ============================================== если послать сумму в балансе то выдает: money_source : wallet : allowed : true ================================ при ошибках есть error: ''' # получили вроде полож ответ # но проверим источник выплаты r['_acc_name'] = acc_name r['_acc'] = acc r['_pars'] = pars_uncomment # удалим лишние комменты if log_on != False: log(db, 'pars_uncomment:%s --> res:%s' % (pars_uncomment, r)) if r['status'] != 'success': return r # если в ответе нет источника то уже ошибка r['error'] = 'no money_source' r['status'] = r.get('status') or 'refused' if not 'money_source' in r: return r v = r['money_source'] if not 'wallet' in v: return r v = v['wallet'] if not 'allowed' in v: return r v = v['allowed'] if not v or v == 'false': return r # ошибки нет - то что надо выбрано для выплаты r['error'] = None r['status'] = 'success' if log_on != False: print 'YmTo - success!', acc, amount, '\n' return r
import os import numpy import gluon.contrib.simplejson as json from pprint import pprint from gluon.custom_import import track_changes; track_changes(True) from adeireader.adeireader import ADEIReader import collections f_server = open(os.path.join(request.folder, 'static/config/server.json')) config_server = json.load(f_server) f_server.close() pprint(config_server) def index(): return locals() @request.restful() def api(): response.view = 'generic.'+request.extension if request.env.http_origin: response.headers['Access-Control-Allow-Origin'] = '*' def GET(*args, **kargs): """ Case 1: '/api/server_name/group_name/sensor_mask.json' Case 2: '/api/sensor_file.json' """ # case 1 if len(args) == 3: server, group, sensor = args
def GET(*args, **kargs): """ Case 1: '/api/server_name/group_name/sensor_mask.json' Case 2: '/api/sensor_file.json' """ # case 1 if len(args) == 3: server, group, sensor = args if server not in config_server: return "Error: server setting (%s) not found" %s else: ar = ADEIReader( config_server[server]['host'], config_server[server]['server'], config_server[server]['database']) res = ar.query(group=group, sensor=sensor) return dict(timestamp=res[0][0], value=res[0][1]) # case 2 elif len(args) == 1: if 'w' in kargs: window = int( kargs['w'] ) else: window = 0 if 'r' in kargs: resample = int( kargs['r'] ) else: resample = 10 if ( window / resample > 30 ): resample = window/30 + 1 try: f_sensor = open(os.path.join(request.folder, 'static/config/' + args[0] + '.json')) sensors = json.load(f_sensor) f_sensor.close() except IOError: return "Error: %s.json not found on server" % args[0] for i in range(len(sensors)-1): if sensors[i]['server'] != sensors[i+1]['server']: return "Error: sensors from different SERVER is found in %s.json" % args[0] if sensors[i]['group'] != sensors[i+1]['group']: return "Error: sensors from different GROUP is found in %s.json" % args[0] server = sensors[0]['server'] group = sensors[0]['group'] # initial output output = {} sensor_masks = [] sensor_ids = [] for i, s in enumerate(sensors): output['sensor-'+str(i)] = [] if s['sensor'] >= 0: sensor_masks.append(s['sensor']) sensor_ids.append(i) # query ar = ADEIReader( config_server[server]['host'], config_server[server]['server'], config_server[server]['database']) query_res = ar.query(group=group, sensor=sensor_masks, window=window, resample=resample) query_res = numpy.array( query_res ) timestamp = query_res[ :,0 ].tolist() for i in sensor_ids: output['sensor-'+str(i)] = query_res[:, i+1].tolist() return dict(timestamp=timestamp, value=output)