def executor(queue,task, out): """ the background process """ logging.debug(' task started') class LogOutput(object): """Facility to log output at intervals""" def __init__(self, out_queue): self.out_queue = out_queue self.stdout = sys.stdout sys.stdout = self self.istr = "" def __del__(self): sys.stdout = self.stdout def write(self,data): self.out_queue.put(data) self.istr += data def getvalue(self): return self.istr #stdout, sys.stdout = sys.stdout, cStringIO.StringIO() stdout = LogOutput(out) try: if task.app: os.chdir(os.environ['WEB2PY_PATH']) from gluon.shell import env, parse_path_info from gluon.dal import BaseAdapter from gluon import current level = logging.getLogger().getEffectiveLevel() logging.getLogger().setLevel(logging.WARN) # Get controller-specific subdirectory if task.app is of # form 'app/controller' (a,c,f) = parse_path_info(task.app) _env = env(a=a,c=c,import_models=True) logging.getLogger().setLevel(level) scheduler = current._scheduler f = task.function functions = current._scheduler.tasks if not functions: #look into env _function = _env.get(f) else: _function = functions.get(f) if not isinstance(_function, CALLABLETYPES): raise NameError("name '%s' not found in scheduler's environment" % f) globals().update(_env) args = loads(task.args) vars = loads(task.vars, object_hook=_decode_dict) result = dumps(_function(*args,**vars)) else: ### for testing purpose only result = eval(task.function)( *loads(task.args, object_hook=_decode_dict), **loads(task.vars, object_hook=_decode_dict)) #stdout, sys.stdout = sys.stdout, stdout sys.stdout = stdout.stdout queue.put(TaskReport(COMPLETED, result,stdout.getvalue())) except BaseException,e: sys.stdout = stdout.stdout tb = traceback.format_exc() queue.put(TaskReport(FAILED,tb=tb, output=stdout.getvalue()))
def executor(queue, task, out): """ the background process """ logger.debug(" task started") class LogOutput(object): """Facility to log output at intervals""" def __init__(self, out_queue): self.out_queue = out_queue self.stdout = sys.stdout sys.stdout = self def __del__(self): sys.stdout = self.stdout def flush(self): pass def write(self, data): self.out_queue.put(data) W2P_TASK = Storage({"id": task.task_id, "uuid": task.uuid}) stdout = LogOutput(out) try: if task.app: os.chdir(os.environ["WEB2PY_PATH"]) from gluon.shell import env, parse_path_info from gluon import current level = logging.getLogger().getEffectiveLevel() logging.getLogger().setLevel(logging.WARN) # Get controller-specific subdirectory if task.app is of # form 'app/controller' (a, c, f) = parse_path_info(task.app) _env = env(a=a, c=c, import_models=True) logging.getLogger().setLevel(level) f = task.function functions = current._scheduler.tasks if not functions: # look into env _function = _env.get(f) else: _function = functions.get(f) if not isinstance(_function, CALLABLETYPES): raise NameError("name '%s' not found in scheduler's environment" % f) # Inject W2P_TASK into environment _env.update({"W2P_TASK": W2P_TASK}) globals().update(_env) args = loads(task.args) vars = loads(task.vars, object_hook=_decode_dict) result = dumps(_function(*args, **vars)) else: ### for testing purpose only result = eval(task.function)( *loads(task.args, object_hook=_decode_dict), **loads(task.vars, object_hook=_decode_dict) ) queue.put(TaskReport(COMPLETED, result=result)) except BaseException, e: tb = traceback.format_exc() queue.put(TaskReport(FAILED, tb=tb))
def choose_condition(): soft_assert(request.assid!='ASSIGNMENT_ID_NOT_AVAILABLE', "Can't call choose condition on preview.") # if this assignment exists, return its condition action = db.actions(assid=request.assid) if action: request.condition = sj.loads(action.condition.json) request.phase = action.phase log('Choosing existing assignment condition') return # Compute the phase of study request.phase = (int((now - request.study.launch_date).total_seconds() / options.phase_change_time) if options.phase_change_time else None) # If workerid already has a condition for this phase, return it c = db.condition_choices(workerid=request.workerid, study=request.study, phase=request.phase) if c: log('Choosing existing phase condition') request.condition = sj.loads(c.condition.json) return # Else, let's make a new one. # First we'll choose the stuff we want in the condition. for probability, condition in options[request.task]['special_conditions'] or []: # First, give special conditions a shot random.seed() if random.random() < probability: request.condition = condition.copy() break else: # If none of them match, grab the next condition possible in round-robin fashion. next_index = db((db.condition_choices.phase==request.phase) &(db.condition_choices.study==request.study)).count() request.condition = condition_by_index(experimental_vars_vals(request.study), next_index) # Now add the non-experimental variables back into the condition... for k, v in sj.loads(request.study.conditions).items(): if not isinstance(v, list): request.condition[k] = v # Insert this choice into the database log('Choosing a new available condition') db.condition_choices.insert(study=request.study, phase=request.phase, condition=get_condition(request.condition), workerid=request.workerid, time_assigned=now) # If this is a CHANGE of condition for the worker (because they # were working in a prior phase), let's set a flag so that the # view can tell the worker to pay attention to the difference if db((db.condition_choices.phase < request.phase) & (db.condition_choices.study == request.study) & (db.condition_choices.workerid == request.workerid)).count() > 0: request.new_phase = True
def get_workers(self, only_ticker=False): """ Returns a dict holding worker_name : {**columns} representing all "registered" workers only_ticker returns only the worker running as a TICKER, if there is any """ r_server = self.r_server status_keyset = self._nkey('worker_statuses') registered_workers = r_server.smembers(status_keyset) all_workers = {} for worker in registered_workers: w = r_server.hgetall(worker) w = Storage(w) if not w: continue all_workers[w.worker_name] = Storage( status=w.status, first_heartbeat=self.str2date(w.first_heartbeat), last_heartbeat=self.str2date(w.last_heartbeat), group_names=loads(w.group_names, object_hook=_decode_dict), is_ticker=w.is_ticker == 'True' and True or False, worker_stats=loads(w.worker_stats, object_hook=_decode_dict) ) if only_ticker: for k, v in all_workers.iteritems(): if v['is_ticker']: return {k: v} return {} return all_workers
def save(): try: q = db(db.json.name == request.vars.name) if len(q.select()): _id = q.update( name = request.vars.name, data = request.vars.data ) return response.json({ 'status' : 1, 'message' : 'update done', 'result' : simplejson.loads(q.select()[0].data) }) else: _id = db.json.insert( name = request.vars.name, data = request.vars.data ) return response.json({ 'status' : 1, 'message' : 'insert done', 'result' : simplejson.loads(q.select()[0].data) }) except Exception, ex: return response.json({ 'status' : 0, 'message' : 'error', 'result' : str(ex) })
def on_accept(form): from gluon.contrib import simplejson global sampling_time_old global execonsuccess #update time of cutT, nodiffT, dropT and evenT when sampling time is changed + subintervals definition if float(form.vars.sampling_time)>0: sfactor = float(form.vars.sampling_time) / sampling_time_old else: sfactor = 1 #do nothing if sfactor != 1: dropT = [[x * sfactor for x in y] for y in simplejson.loads(db.flise_file[form.vars.id].dropT)] if (db.flise_file[form.vars.id].dropT != None) else [] db.flise_file[form.vars.id].update_record(dropT=simplejson.dumps(dropT)) cutT = [x * sfactor for x in simplejson.loads(db.flise_file[form.vars.id].cutT)] if (db.flise_file[form.vars.id].cutT != None) else [] db.flise_file[form.vars.id].update_record(cutT=simplejson.dumps(cutT)) nodiffT = [[x * sfactor for x in y] for y in simplejson.loads(db.flise_file[form.vars.id].nodiffT)] if (db.flise_file[form.vars.id].nodiffT != None) else [] db.flise_file[form.vars.id].update_record(nodiffT=simplejson.dumps(nodiffT)) eventT = [x * sfactor for x in simplejson.loads(db.flise_file[form.vars.id].eventT)] if (db.flise_file[form.vars.id].eventT != None) else [] db.flise_file[form.vars.id].update_record(eventT=simplejson.dumps(eventT)) for record in db(db.event.flise_file_id == form.vars.id).select(): time = record.time * sfactor record.update_record(time=time) for record in db(db.subintervals.flise_file_id == form.vars.id).select(): extract_time = record.extract_time str_time = extract_time.split(':') intStart = float(str_time[0]) * sfactor intEnd = float(str_time[1]) * sfactor extract_time = '%g:%g' % (intStart, intEnd) record.update_record(extract_time=extract_time) execonsuccess = 'updateGraph("%s");' % form.vars.name else: execonsuccess = 'web2py_ajax_page("GET","%s","","my_records"); $(".current_record").html("%s"); cur_id=%s; ' % (URL(r=request, f='files'), form.vars.name, form.vars.id)
def executor(queue,task): """ the background process """ logging.debug(' task started') stdout, sys.stdout = sys.stdout, cStringIO.StringIO() try: if task.app: os.chdir(os.environ['WEB2PY_PATH']) from gluon.shell import env from gluon.dal import BaseAdapter from gluon import current level = logging.getLogger().getEffectiveLevel() logging.getLogger().setLevel(logging.WARN) _env = env(task.app,import_models=True) logging.getLogger().setLevel(level) scheduler = current._scheduler scheduler_tasks = current._scheduler.tasks _function = scheduler_tasks[task.function] globals().update(_env) args = loads(task.args) vars = loads(task.vars, object_hook=_decode_dict) result = dumps(_function(*args,**vars)) else: ### for testing purpose only result = eval(task.function)( *loads(task.args, object_hook=_decode_dict), **loads(task.vars, object_hook=_decode_dict)) stdout, sys.stdout = sys.stdout, stdout queue.put(TaskReport(COMPLETED, result,stdout.getvalue())) except BaseException,e: sys.stdout = stdout tb = traceback.format_exc() queue.put(TaskReport(FAILED,tb=tb))
def set_graph_data(map_id, hash, nodes, edges, origin): ''' Set the graph data based on the incoming node and edge strings. ''' if not can_update(map_id, auth.user.id, hash): return dict(success=False) # Delete old nodes and edges db(db.Node.id_map == map_id).delete() db(db.Connection.id_map == map_id).delete() # Parse the input data nodes_to_add = json.loads(nodes) edges_to_add = json.loads(edges) origin = json.loads(origin) node_ids = {} edge_ids = {} for token, node in nodes_to_add.items(): dim = node['dim'] node_id = db.Node.insert(id_map = map_id, valence = node['valence'], x = dim['x'], y = dim['y'], width = dim['width'], height = dim['height'], name = node['text'], special = node['special']) node_ids[token] = node_id for token, edge in edges_to_add.items(): start = node_ids[edge['from']] end = node_ids[edge['to']] points = json.dumps(edge['innerPoints']) connection_id = db.Connection.insert(id_first_node = start, id_second_node = end, valence = edge['valence'], inner_points = points, id_map = map_id) edge_ids[token] = connection_id db.Map[map_id] = dict(originX = origin['x'], originY = origin['y']) db.Map[map_id] = dict(date_modified = datetime.utcnow(), modified_by = auth.user.email) return dict(success=True, node_ids=node_ids, edge_ids=edge_ids)
def get_missing(self, seriesid, seasonnumber): db = current.w2p_tvseries.database fname = 'get_missing' ss_tb = db.seasons_settings se_tb = db.series gs = w2p_tvseries_settings().global_settings() path_format = gs.path_format or '%(seasonnumber).2d' season = db( (ss_tb.series_id == seriesid) & (ss_tb.seasonnumber == seasonnumber) & (se_tb.id == ss_tb.series_id) ).select().first() bpath = season and season.series.basepath or '' if bpath == '': return dict(err='No basepath found') path = os.path.join(bpath, path_format % dict(seasonnumber = season.seasons_settings.seasonnumber)) tracking = season and season.seasons_settings.subtitle_tracking or None sub_settings = season and season.seasons_settings.subtitle_settings or None quality = simplejson.loads(sub_settings).get('quality', 'Normal') language = simplejson.loads(sub_settings).get('language', 'eng') name = season and season.series.name or None id = season and season.seasons_settings.id or None if tracking and name and id: data = simplejson.loads(season.seasons_settings.season_status) missingsubs = data.get('missingsubs', []) if len(missingsubs) == 0: message="No missing subs for %s, season %s, type %s, in path %s" % (name, seasonnumber, quality, path) self.log(fname, message) return dict(message=message) errs = '' subtitles_list, errs = self.search_subtitles(id, name, seasonnumber, missingsubs, quality, language) if errs <> '': return dict(err=errs) else: res = self.download_subtitles(subtitles_list, path) found = [a['number'] for a in subtitles_list] not_found = [] for a in missingsubs: if a not in found: not_found.append(a) data['missingsubs'] = not_found data = simplejson.dumps(data) db(ss_tb.id == season.seasons_settings.id).update(season_status=data) db.commit() message="Searching subs for %s, season %s, type %s, in path %s, were %s, are %s" % (name, seasonnumber, quality, path, missingsubs, not_found) self.log(fname, message) return dict(message=message) else: err = 'settings deny to download subtitles' self.error('fetch_subtitles', err) return dict(err=err)
def step1(): from gluon.contrib.simplejson import loads import urllib if not session.themes: url = LAYOUTS_APP + '/default/layouts.json' try: data = urllib.urlopen(url).read() session.themes = ['Default'] + loads(data)['layouts'] except: session.themes = ['Default'] themes = session.themes if not session.plugins: url = PLUGINS_APP + '/default/plugins.json' try: data = urllib.urlopen(url).read() session.plugins = loads(data)['plugins'] except: session.plugins = [] plugins = [x.split('.')[2] for x in session.plugins] response.view = 'wizard/step.html' params = dict(session.app['params']) form = SQLFORM.factory( Field('title', default=params.get('title', None), requires=IS_NOT_EMPTY()), Field('subtitle', default=params.get('subtitle', None)), Field('author', default=params.get('author', None)), Field( 'author_email', default=params.get('author_email', None)), Field('keywords', default=params.get('keywords', None)), Field('description', 'text', default=params.get('description', None)), Field('layout_theme', requires=IS_IN_SET(themes), default=params.get('layout_theme', themes[0])), Field( 'database_uri', default=params.get('database_uri', None)), Field( 'security_key', default=params.get('security_key', None)), Field( 'email_server', default=params.get('email_server', None)), Field( 'email_sender', default=params.get('email_sender', None)), Field('email_login', default=params.get('email_login', None)), Field('login_method', requires=IS_IN_SET(('local', 'janrain')), default=params.get('login_method', 'local')), Field( 'login_config', default=params.get('login_config', None)), Field('plugins', 'list:string', requires=IS_IN_SET(plugins, multiple=True)), _class='span7 well well-small') if form.accepts(request.vars): session.app['params'] = [(key, form.vars.get(key, None)) for key, value in session.app['params']] redirect(URL('step2') + '/#xwizard_form') return dict(step='1: Setting Parameters', form=form)
def get_savgol(): response.generic_patterns = ['json'] import savgol from gluon.contrib import simplejson data2derive = simplejson.loads(request.vars.data) deriv = simplejson.loads(request.vars.deriv) result = [] for iD in range(len(deriv)): result.append([]) myinstance = savgol.Savgol(int(request.vars.w), int(request.vars.w), int(request.vars.order), deriv[iD]) for iI in range(len(data2derive)): result[iD].append([]) for iS in range(len(data2derive[iI])): result[iD][iI].append(myinstance.filterTS(data2derive[iI][iS])) return dict(result=result)
def call_py (m): connection = deployment_settings.postgis.connection () #file_id = str (uuid4 ().int) mod = get_module (m['filename']) attr = {} #attr['file'] = open ('applications/' + request.application + '/tool/results/' + file_id, 'w') for t in m['args']: key = t[0] label = t[1] ttype = t[2] val = request.vars.get (key) if ttype == 'poly_map': # Fix this later. Send only id in request ob = json.loads (val) map_data = dm.get ('maps', ob['id']) mapname = map_data.prefix + ':' + map_data.filename #json.loads (val)['filename'] attr[key] = loadMap (mapname, enum.POLYGON, enum.GEOSERVER, location = map_data.src) elif ttype == 'point_map': # Fix this later. Send only id in request ob = json.loads (val) map_data = dm.get ('maps', ob['id']) mapname = map_data.prefix + ':' + map_data.filename #json.loads (val)['filename'] attr[key] = loadMap (mapname, enum.POINT, enum.GEOSERVER, location = map_data.src) elif ttype == 'agg': attr[key] = recursiveJSON (val) elif ttype == 'text': if len (val) > 0: attr[key] = val else: attr[key] = None else: attr[key] = val buffers = [] def request_new_buffer (name = None): b_id = uuid4 ().hex if name is None: name = b_id buffers.append ({'id': b_id, 'name': name}) return TempBuffer (name, b_id) mod.request_new_buffer = request_new_buffer mod.mime = mime try: r_type = mod.ctool (**attr) except Exception as ex: return attr_dict (err = str (ex)) return attr_dict (file_ids = buffers)
def testExportOptionsAllOptsJSON(self): """ Test export options, JSON, all options """ assertEqual = self.assertEqual assertTrue = self.assertTrue options = dict(self.records) # Request options resource = current.s3db.resource("fotest_table") result = resource.export_options(fields=["lookup"], as_json=True) fo = json.loads(result) # Inspect result has_empty = False assertTrue(isinstance(fo, dict)) assertTrue("option" in fo) assertTrue(isinstance(fo["option"], list)) assertEqual(len(fo["option"]), len(options) + 1) for opt in fo["option"]: value = opt["@value"] if value == "": has_empty = True self.assertFalse("$" in opt) continue else: value = int(value) assertTrue(value in options) assertEqual(opt["$"], options[value]["name"]) assertTrue(has_empty, msg="Empty-option missing")
def _climate_chart(content_type): """ """ kwargs = dict(request.vars) import gluon.contrib.simplejson as json specs = json.loads(kwargs.pop("spec")) def list_of(converter): def convert_list(choices): return map(converter, choices) return convert_list checked_specs = [] for label, spec in specs.iteritems(): arguments = {} errors = [] for name, converter in dict( query_expression = str, place_ids = list_of(int) ).iteritems(): try: value = spec.pop(name) except KeyError: errors.append("%s missing" % name) else: try: arguments[name] = converter(value) except TypeError: errors.append("%s is wrong type" % name) except AssertionError, assertion_error: errors.append("%s: %s" % (name, assertion_error)) if spec: errors.append("Unexpected arguments: %s" % spec.keys()) checked_specs.append((label, arguments))
def testExportOptionsLastOptJSON(self): """ Test export of last option, JSON """ assertEqual = self.assertEqual assertTrue = self.assertTrue options = dict(self.records) # Get the last record db = current.db table = db.fotest_lookup_table last = db(table.id>0).select(limitby=(0, 1), orderby=~table.id).first() self.assertNotEqual(last, None) # Request last option resource = current.s3db.resource("fotest_table") result = resource.export_options(fields=["lookup"], only_last=True, as_json=True) fo = json.loads(result) # Inspect result assertTrue(isinstance(fo, dict)) assertTrue("option" in fo) assertTrue(isinstance(fo["option"], list)) assertEqual(len(fo["option"]), 1) opt = fo["option"][0] value = opt["@value"] assertEqual(options[value]["uuid"], last.uuid) assertEqual(opt["$"], options[value]["name"])
def testValidateMainTableError(self): """ Test error in main table validation """ request = self.request crud = self.resource.crud jsonstr = """{"name":"", "acronym":"TO"}""" request.body = StringIO(jsonstr) output = crud.validate(request) self.assertTrue(isinstance(output, basestring)) from gluon.contrib import simplejson as json data = json.loads(output) self.assertTrue(isinstance(data, dict)) self.assertEqual(len(data), 2) self.assertTrue("name" in data) name = data["name"] self.assertTrue(isinstance(name, dict)) self.assertTrue("value" in name) self.assertFalse("text" in name) self.assertTrue("_error" in name) acronym = data["acronym"] self.assertTrue(isinstance(acronym, dict)) self.assertTrue("value" in acronym) self.assertTrue("text" in acronym) self.assertTrue(isinstance(acronym["text"], basestring)) self.assertFalse("_error" in acronym)
def testTypeConversionFeature(self): """ Check that values get converted into the field type during validation """ s3db = current.s3db # Create a fake request resource = s3db.resource("project_organisation") request = Storage(prefix="project", name="organisation", resource=resource, table=resource.table, tablename=resource.tablename, method="validate", get_vars=Storage(), representation="json", http="GET") crud = resource.crud jsonstr = """{"organisation_id":"1", "role":"1"}""" request.body = StringIO(jsonstr) output = crud.validate(request) self.assertTrue(isinstance(output, basestring)) from gluon.contrib import simplejson as json data = json.loads(output) self.assertTrue(isinstance(data, dict)) self.assertEqual(len(data), 2) self.assertTrue("role" in data) role = data["role"] self.assertTrue(isinstance(role, dict)) self.assertTrue("value" in role) self.assertTrue(isinstance(role["value"], int))
def check_season(): session.forget(response) series_id, seasonnumber = request.args(0), request.args(1) if not (series_id and seasonnumber): return json({}) status = db( (db.seasons_settings.series_id == series_id) & (db.seasons_settings.seasonnumber == seasonnumber) ).select(db.seasons_settings.season_status, db.seasons_settings.updated_on).first() if not status.updated_on: status.updated_on = request.now episodes = db( (db.series.id == series_id) & (db.episodes.seriesid == db.series.seriesid) & (db.episodes.seasonnumber == seasonnumber) & (db.episodes.inserted_on > status.updated_on) ).select(db.episodes.epnumber) rtn = status.season_status if len(episodes) > 0: st_ = sj.loads(status.season_status) missing = st_.get('missing', []) for ep in episodes: missing.append(ep.epnumber) st_['missing'] = missing rtn = sj.dumps(st_) return rtn
def twitter(): session.forget() session._unlock(response) import urllib import gluon.contrib.simplejson as sj try: if TWITTER_HASH: # tweets = urllib.urlopen('http://twitter.com/%s?format=json' % TWITTER_HASH).read() try: tweets = cache.disk(request.env.path_info + ".tweets", lambda: urllib.urlopen("http://search.twitter.com/search.json?q=%s" % TWITTER_HASH).read(), time_expire=60*15) except: import os # manually clean cache (TODO: check why it can get corrupt!) path = os.path.join(request.folder,'cache') for f in os.listdir(path): try: if f[:1]!='.': os.unlink(os.path.join(path,f)) except IOError: r = False # try to reload redirect(URL("twitter")) data = sj.loads(tweets, encoding="utf-8") the_tweets = dict() for obj in data["results"]: the_tweets[obj["id"]] = (obj["created_at"], obj["from_user"], obj["profile_image_url"], obj["text"]) ret = dict(message = None, tweets = the_tweets) else: ret = dict(tweets = None, message = 'disabled') except Exception, e: ret = dict(tweets = None, message = DIV(T('Unable to download because:'),BR(),str(e)))
def edit_ordering(): """ Edit last ordering.""" # Gets the information on the venue and comparison. venue = db.venue(request.args[0]) or redirect(URL('default', 'index')) last_comparison = db.comparison(request.args[1]) or redirect(URL('default', 'index')) if last_comparison.author != auth.user_id: session.flash = T('Invalid request.') redirect(URL('default', 'index')) # Check that the venue rating deadline is currently open, or that the ranker # is a manager or observer. if ((auth.user.email not in util.get_list(venue.managers)) and (auth.user.email not in util.get_list(venue.observers)) and (datetime.utcnow() < venue.rate_open_date or datetime.utcnow() > venue.rate_close_date)): session.flash = T('The review deadline for this venue is closed.') redirect(URL('venues', 'view_venue', args=[venue.id])) # Ok, the task belongs to the user. # Gets the last reviewing task done for the same venue. if last_comparison == None: last_ordering = [] else: last_ordering = util.get_list(last_comparison.ordering) # Finds the grades that were given for the submissions previously reviewed. if last_comparison == None or last_comparison.grades == None: str_grades = {} else: try: str_grades = simplejson.loads(last_comparison.grades) except Exception, e: str_grades = {} logger.warning("Grades cannot be read: " + str(last_comparison.grades))
def call(self, method, *args): "JSON RPC communication (method invocation)" # build data sent to the service request_id = random.randint(0, sys.maxint) data = {'id': request_id, 'method': method, 'params': args, } if self.version: data['jsonrpc'] = self.version #mandatory key/value for jsonrpc2 validation else err -32600 request = json.dumps(data) # make HTTP request (retry if connection is lost) response = self.__transport.request( self.__host, self.__handler, request, verbose=self.__verbose ) # store plain request and response for further debugging self.json_request = request self.json_response = response # parse json data coming from service # {'version': '1.1', 'id': id, 'result': result, 'error': None} response = json.loads(response) self.error = response.get('error', {}) if self.error and self.exceptions: raise JSONRPCError(self.error.get('code', 0), self.error.get('message', ''), self.error.get('data', None)) if response['id'] != request_id: raise JSONRPCError(0, "JSON Request ID != Response ID") return response.get('result')
def add_crew(room, wefsk, people): people = json.loads(people) id = db.crew.insert(room=room, wefsk=wefsk) for p in people: db(db.person.id==p).update(crew=id) return dict(id=id)
def _climate_chart(content_type): kwargs = dict(request.vars) import gluon.contrib.simplejson as JSON specs = JSON.loads(kwargs.pop("spec")) checked_specs = [] for spec in specs: arguments = {} errors = [] for name, converter in dict( query_expression = str, place_ids = list_of(int) ).iteritems(): try: value = spec.pop(name) except KeyError: errors.append("%s missing" % name) else: try: arguments[name] = converter(value) except TypeError: errors.append("%s is wrong type" % name) except AssertionError, assertion_error: errors.append("%s: %s" % (name, assertion_error)) if spec: errors.append("Unexpected arguments: %s" % spec.keys()) checked_specs.append(arguments)
def call(self, method, *args): "JSON RPC communication (method invocation)" # build data sent to the service request_id = random.randint(0, sys.maxint) data = {"id": request_id, "method": method, "params": args} request = json.dumps(data) # make HTTP request (retry if connection is lost) response = self.__transport.request(self.__host, self.__handler, request, verbose=self.__verbose) # store plain request and response for further debugging self.json_request = request self.json_response = response # parse json data coming from service # {'version': '1.1', 'id': id, 'result': result, 'error': None} response = json.loads(response) if response["id"] != request_id: raise JSONRPCError(0, "JSON Request ID != Response ID") self.error = response.get("error", {}) if self.error and self.exceptions: raise JSONRPCError(self.error.get("code", 0), self.error.get("message", ""), self.error.get("data", None)) return response.get("result")
def get_user(self): request = self.request user = None if request.vars.connection_token: auth_url = "https://%s.api.oneall.com/connections/%s.json" % \ (self.domain, request.vars.connection_token) auth_pw = "%s:%s" % (self.public_key,self.private_key) auth_pw = base64.b64encode(auth_pw) headers = dict(Authorization="Basic %s" % auth_pw) try: auth_info_json = fetch(auth_url,headers=headers) auth_info = json.loads(auth_info_json) data = auth_info['response']['result']['data'] if data['plugin']['key'] == 'social_login': if data['plugin']['data']['status'] == 'success': userdata = data['user'] self.profile = userdata['identity'] source = self.profile['source']['key'] mapping = self.mappings.get(source,self.mappings['default']) user = mapping(self.profile) except (JSONDecodeError, KeyError): pass if user is None and self.on_login_failure: redirect(self.on_login_failure) return user
def ajax_cargar_pedido_mesa(): mmct = db( db.mesa_mozo_caja_turno.mesa == request.get_vars.get('mesa') and\ db.mesa_mozo_caja_turno.caja == Helper.get_caja_abierta().id and\ db.mesa_mozo_caja_turno.turno == Helper.get_current_turno().id).select()[0] pedido = db.pedidos.insert(caja=mmct.caja) for x in sj.loads(request.get_vars.get('productos')): linea_pedido = db.linea_pedido.insert( pedido=pedido.id, producto=x['id_producto'], cantidad=x['cantidad'] ) pedidos_mesas = db.pedidos_mesas.insert( pedido = pedido, mesa = mmct.mesa, mozo = mmct.mozo, turno = mmct.turno, caja = mmct.caja ) return pedido.id
def cargar_pedido_ajax(): pedido = db.pedidos.insert(caja=Helper.get_caja_abierta()) for x in sj.loads(request.vars['productos']): linea_pedido = db.linea_pedido.insert( pedido=pedido.id, producto=x['id_producto'], cantidad=x['cantidad']) return redirect( URL( 'single_pedido_template_'+request.vars['tipo_pedido'], vars=dict( id_pedido=pedido.id, nombre=request.vars['nombre'], direccion=request.vars['direccion'], mesa=request.vars['mesa'], kilometraje = request.vars['kilometraje'], precio = request.vars['precio'], tipo_factura=request.vars["tipo_factura"] ) ) )
def add_to_targetgroup(self, target_id, group_id=None, group_name=None): """ Adds the target with id target_id to the targetgroup with id group_id. Returns True if the operation was successful """ if group_name: group_id = self.get_group_id(group_name) target_row = self._db(self._db.target.id==target_id).select().first() group_row = self._db(self._db.targetgroup.id==group_id ).select().first() result = False if target_row is not None and group_row is not None: targets_j = group_row.targets if not targets_j: # Dumps the json to the group table targets_j = json.dumps([target_id]) else: tmp_j = json.loads(targets_j) tmp_j.append(target_id) targets_j = json.dumps(tmp_j) result = self._db(self._db.targetgroup.id==group_id ).update(targets=targets_j) self._db.commit() return result
def decode_order(form): logger.debug("request.vars.order: " + request.vars.order) logger.debug("request.vars.grades: " + request.vars.grades) if request.vars.order == None or request.vars.grades == None: form.errors.comments = T('Error in the received ranking') session.flash = T('Error in the received ranking') return # Verifies the order. try: decoded_order = [int(x) for x in request.vars.order.split()] for i in decoded_order: if i != subm_id: # This must correspond to a previously done task. mt = db((db.task.submission_id == i) & (db.task.user_id == auth.user_id)).select().first() if mt == None or mt.completed_date > datetime.utcnow(): form.errors.comments = T('Corruputed data received') session.flash = T('Corrupted data received') break form.vars.order = decoded_order except ValueError: form.errors.comments = T('Error in the received ranking') session.flash = T('Error in the received ranking') return # Verifies the grades. try: decoded_grades = simplejson.loads(request.vars.grades) grade_subm = [(float(g), long(s)) for (s, g) in decoded_grades.iteritems()] # Check that all grades are between 0 and 10. for (g, s) in grade_subm: if g < 0.0 or g > 10.0: form.errors.comments = T('Grades should be in the interval [0..10]') session.flash = T('Errors in the received grades') return # Sorts the grades in decreasing order. grade_subm.sort() grade_subm.reverse() # Checks that there are no duplicate grades. if len(grade_subm) == 0: form.errors.comments = T('No grades specified') session.flash = T('Errors in the received grades') return (prev, _) = grade_subm[0] for (g, s) in grade_subm[1:]: if g == prev: form.errors.comments = T('There is a repeated grade: grades need to be unique.') session.flash = T('Errors in the received grades') return # Checks that the order of the grades matches the one of the submissions. subm_order = [s for (g, s) in grade_subm] if subm_order != form.vars.order: form.errors.comments = T('The ranking of the submissions does not reflect the grades.') session.flash = T('Errors in the received grades.') return # Copies the grades in the form variable. form.vars.grades = request.vars.grades except Exception, e: form.errors.comments = T('Error in the received grades') session.flash = T('Error in the received grades') return
def get_targets(self, group_set, target_set=[]): """ If target_set is not a list it returns a rowset with all targets. If target_set is a list of groups it returns a rowset of targets that belong to these groups. """ result_id = [] if not isinstance(group_set, list): for target in self._db(self._db.target).select(): result_id.append(target.id) else: rows = self._db(self._db.targetgroup).select() for row in rows: if row.id in group_set: targets = json.loads(row.targets) for t_id in targets: result_id.append(self._db(self._db.target.id==t_id ).select().first().id) result_id += target_set result = [] for target_id in set(result_id): result.append(self.get_target(target_id)) return result
def twitter(): session.forget() session._unlock(response) import gluon.tools import gluon.contrib.simplejson as sj try: if TWITTER_HASH: page = gluon.tools.fetch('http://twitter.com/%s?format=json' % TWITTER_HASH) return sj.loads(page)['#timeline'] else: return 'disabled' except Exception, e: return DIV(T('Unable to download because:'), BR(), str(e))
def update_names(names): names = json.loads(names) response = [] for name in names: r = db.module_names.update_or_insert(name=name['name'], label=name['value']) response.append(r) errors = list() for i in range(len(response)): if response[i] == 0: errors.append(names[i]) return dict(errors=errors)
def __call__(self, value): from gluon import current try: obj = loads(value) except: return (value, current.T('invalid json')) else: if isinstance(obj, self.myclass): if self.parse: return (obj, None) else: return (value, None) else: return (value, current.T('Not of type: %s') % self.myclass)
def rename(self, seriesid, seasonnumber, mode): db = current.w2p_tvseries.database self.log( 'rename', "Checking for series with id %s and season %s" % (seriesid, seasonnumber)) bit = db.rename_log ss_tb = db.seasons_settings datarec = db((ss_tb.series_id == seriesid) & (ss_tb.seasonnumber == seasonnumber)).select().first() data = datarec and datarec.season_status data = simplejson.loads(data) if not data: return rename = data['rename'] now = datetime.datetime.now() db.commit() existing = [] while True: try: rename_ = rename.pop() except: break source, dest = rename_ self.log( 'rename', "trying to do %s --> %s" % (os.path.basename(source), os.path.basename(dest))) if os.path.exists(dest): existing.append((dest, source)) if os.path.exists(dest) or not os.path.exists(source): continue try: bit.insert(series_id=seriesid, seasonnumber=seasonnumber, file_from=source, file_to=dest) os.rename(source, dest) db.commit() except: db.rollback() data['rename'] = rename if mode == 'video': data['existingvideo'] = existing elif mode == 'subs': data['existingsubs'] = existing datarec.update_record(season_status=simplejson.dumps(data), updated_on=now) db.commit() return datarec
def test_school_classcards_get_json(client, web2py): """ Are the class cards returned correctly? """ populate_api_users(web2py) populate_school_classcards(web2py, 2) url = base_url + '/api/school_classcards_get.json?user=test&key=test' page = urllib.urlopen(url).read() print page json = sj.loads(page) classcard = web2py.db.school_classcards(1) assert json['data'][0]['Name'] == classcard.Name
def lite_wager_end(wager, winned): from gluon.tools import fetch args = '' for w in winned: cond = db.wager_conds[w] if not cond: continue args += '%s/' % cond.bill_id url = LITEcash.url + LITEcash.end_wager % (wager.lite_wager_id, wager.lite_wager_key, args) #print url resp = fetch(url) import gluon.contrib.simplejson as sj res = sj.loads(resp) return res
def process(self, data): data = simplejson.loads(data) id, method, params = data["id"], data["method"], data["params"] if method in self.methods: try: result = self.methods[method](*params) return self.response(id, result) except BaseException: etype, eval, etb = sys.exc_info() return self.error(id, 100, '%s: %s' % (etype.__name__, eval)) except: etype, eval, etb = sys.exc_info() return self.error(id, 100, 'Exception %s: %s' % (etype, eval)) else: return self.error(id, 100, 'method "%s" does not exist' % method)
def test_school_classcards_get_json(client, web2py): """ Are the class cards returned correctly? """ populate_api_users(web2py) populate_school_classcards(web2py, 2) url = base_url + '/api/school_classcards_get.json?user=test&key=test' with urllib.request.urlopen(url) as page: content = page.read().decode('utf-8') json = sj.loads(content) classcard = web2py.db.school_classcards(1) assert json['data'][0]['Name'] == classcard.Name
def test__book_pages_as_json(self): as_json = book_pages_as_json(db, self._book.id) data = loads(as_json) self.assertTrue('files' in data) self.assertEqual(len(data['files']), 2) self.assertEqual(sorted(data['files'][0].keys()), [ 'deleteType', 'deleteUrl', 'name', 'size', 'thumbnailUrl', 'url', ]) self.assertEqual(data['files'][0]['name'], 'file.jpg') self.assertEqual(data['files'][1]['name'], 'file_2.jpg') # Test book_page_ids param. as_json = book_pages_as_json(db, self._book.id, book_page_ids=[self._book_page.id]) data = loads(as_json) self.assertTrue('files' in data) self.assertEqual(len(data['files']), 1) self.assertEqual(data['files'][0]['name'], 'file.jpg')
def represent_ordering(v, r): if v is None: return '' try: id_to_nicks = simplejson.loads(r.submission_nicknames) urls = [ SPAN( A(str(id_to_nicks.get(str(el), '')), _href=URL('feedback', 'view_feedback', args=[el])), ' ') for el in v ] attributes = {} return SPAN(*urls, **attributes) except Exception, e: return '-- data error --'
def testExtendedErrorMessageWithTree(self): """ Test error message with specified error code, text and JSON tree """ json_message = current.xml.json_message msg = json_message(False, 405, message="Test", tree='{"test": "value"}') msg = json.loads(msg) self.assertEqual(len(msg), 4) self.assertEqual(msg["status"], "failed") self.assertEqual(msg["statuscode"], "405") self.assertEqual(msg["message"], "Test") self.assertTrue(isinstance(msg["tree"], dict)) tree = msg["tree"] self.assertEqual(len(tree), 1) self.assertEqual(tree["test"], "value")
def test_school_subscriptions_get_json(client, web2py): """ Are the subscriptions returned correctly? """ populate_api_users(web2py) populate_school_subscriptions(web2py) url = base_url + '/api/school_subscriptions_get.json?user=test&key=test' page = urllib.urlopen(url).read() json = sj.loads(page) subscription = web2py.db.school_subscriptions(1) subscription_price = web2py.db.school_subscriptions_price(1) assert json['data'][0]['Name'] == subscription.Name assert json['data'][0]['Price'] == subscription_price.Price
def login(): data = json.loads(request.body.read()) ssn = db(db.citizen.ssn == data['ssn']).select().first() if ssn: verification_code = id_generator() db.register_codes.insert(verification_code=verification_code, code_date=data['code_date'], citizen_id=ssn['id']) subject = 'Código de inicio de sesión' message = 'El código de inicio de sesión es: \n' message += str(verification_code) message += '\n Ingreselo en la aplicación para acceder al sistema' mail.send(to=ssn['email'], subject=subject, message=message) return dict(status="login_successful") else: return dict(status="error")
def get_user(self): request = self.request if request.vars.token: user = Storage() data = urllib.urlencode(dict(apiKey = self.api_key, token=request.vars.token)) auth_info_json = fetch(self.auth_url+'?'+data) auth_info = json.loads(auth_info_json) if auth_info['stat'] == 'ok': self.profile = auth_info['profile'] provider = re.sub('[^\w\-]','',self.profile['providerName']) user = self.mappings.get(provider,self.mappings.default)(self.profile) return user elif self.on_login_failure: redirect(self.on_login_failure) return None
def get_user(self): request = self.request user = None if request.vars.token: try: auth_url = self.auth_base_url + self.api_secret + "/" + request.vars.token json_data = fetch(auth_url, headers={'User-Agent': "LoginRadius - Python - SDK"}) self.profile = json.loads(json_data) provider = self.profile['Provider'] mapping = self.mappings.get(provider, self.mappings['default']) user = mapping(self.profile) except (JSONDecodeError, KeyError): pass if user is None and self.on_login_failure: redirect(self.on_login_failure) return user
def test_school_teachers_get_json(client, web2py): """ Are the teachers returned correctly? """ from populate_os_tables import populate_auth_user_teachers populate_api_users(web2py) populate_auth_user_teachers(web2py) url = base_url + '/api/school_teachers_get.json?user=test&key=test' page = urllib.urlopen(url).read() json = sj.loads(page) teacher = web2py.db.auth_user(2) assert json['data'][0]['Name'] == teacher.full_name
def message(): from gluon.contrib.websocket_messaging import websocket_send msg = request.body.read() data = json.loads(msg) insert = db.plates.insert( plate=data['results'][0]['plate'], confidence=data['results'][0]['confidence'], total_processing_time=data['processing_time_ms'], plate_processing_time=data['results'][0]['processing_time_ms'], epoch_time=data['epoch_time'], camera_id=data['camera_id'], site_id=data['site_id'], img_width=data['img_width'], img_height=data['img_height'], plate_img_uuid=data['uuid']) websocket_send('http://127.0.0.1:8888', msg, 'mykey', 'live_stream') pass
def test_school_subscriptions_get_json(client, web2py): """ Are the subscriptions returned correctly? """ populate_api_users(web2py) populate_school_subscriptions(web2py) url = base_url + '/api/school_subscriptions_get.json?user=test&key=test' with urllib.request.urlopen(url) as page: content = page.read().decode('utf-8') json = sj.loads(content) subscription = web2py.db.school_subscriptions(1) subscription_price = web2py.db.school_subscriptions_price(1) assert json['data'][0]['Name'] == subscription.Name assert json['data'][0]['Price'] == subscription_price.Price
def test_school_teachers_get_json(client, web2py): """ Are the teachers returned correctly? """ from populate_os_tables import populate_auth_user_teachers populate_api_users(web2py) populate_auth_user_teachers(web2py) url = base_url + '/api/school_teachers_get.json?user=test&key=test' with urllib.request.urlopen(url) as page: content = page.read().decode('utf-8') json = sj.loads(content) teacher = web2py.db.auth_user(2) assert json['data'][0]['Name'] == teacher.full_name
def get_user(self): request = self.request if request.vars.assertion: audience = self.audience issuer = self.issuer assertion = XML(request.vars.assertion, sanitize=True) verify_data = {'assertion': assertion, 'audience': audience} auth_info_json = fetch(self.verify_url, data=verify_data) j = json.loads(auth_info_json) epoch_time = int(time.time() * 1000) # we need 13 digit epoch time if j["status"] == "okay" and j["audience"] == audience and j['issuer'] == issuer and j['expires'] >= epoch_time: return dict(email=j['email']) elif self.on_login_failure: redirect('http://google.com') else: redirect('http://google.com') return None
def in_btc(): man_id = session.man_id if not man_id: return 'session error 1' man_bal_id = request.args(0) if not man_bal_id: return 'empty man_bal_id' man_bal = db.man_bals[man_bal_id] if not man_bal: return 'empty man_bal' if man_bal.man_id != man_id: return 'session error 2' man = db.men[man_bal.man_id] if not man: return 'error man' cash = db.cash[man_bal.cash_id] if not cash: return 'error cash' if cash.system_id != myconf.take('cash.bitcoin_id', cast=int): return T('В разработке') if not man_bal.dep_bill or len(man_bal.dep_bill) < 2: ## make a bill on LITE.cash url = 'http://lite.cash/api_bill/make.json/325?order=%s' % man.ref_key #print url #return url from gluon.tools import fetch resp = fetch(url) #print resp import gluon.contrib.simplejson as sj if not resp[:2].isdigit(): # если тут не число - значит ошибка res = sj.loads(resp) # {'bill': bill_id } err = res.get('error') if err: return dict(err=err) ## bill_id, _, skey = resp.partition('.') man_bal.update_record(dep_bill=resp) redirect('http://lite.cash/bill/show/' + man_bal.dep_bill)
def task_status(self, ref, output=False): """ Shortcut for task status retrieval :param ref: can be - integer --> lookup will be done by scheduler_task.id - string --> lookup will be done by scheduler_task.uuid - query --> lookup as you wish (as in db.scheduler_task.task_name == 'test1') :param output: fetch also the scheduler_run record Returns a single Row object, for the last queued task If output == True, returns also the last scheduler_run record scheduler_run record is fetched by a left join, so it can have all fields == None """ from gluon.dal import Query sr, st = self.db.scheduler_run, self.db.scheduler_task if isinstance(ref, int): q = st.id == ref elif isinstance(ref, str): q = st.uuid == ref elif isinstance(ref, Query): q = ref else: raise SyntaxError( "You can retrieve results only by id, uuid or Query") fields = st.ALL left = False orderby = ~st.id if output: fields = st.ALL, sr.ALL left = sr.on(sr.scheduler_task == st.id) orderby = ~st.id | ~sr.id row = self.db(q).select( *fields, **dict(orderby=orderby, left=left, limitby=(0, 1)) ).first() if output: row.result = row.scheduler_run.run_result and \ loads(row.scheduler_run.run_result, object_hook=_decode_dict) or None return row
def subtitle(): from gluon.contrib import simplejson T.lazy = False if request.args(1) == "create": starts = seconds_to_time(request.vars.starts) ends = seconds_to_time(request.vars.ends) subtitle_id = db.subtitle.insert( subtitulation_id=request.vars.subtitulation_id, starts=starts, ends=ends) subtitle = db.subtitle[subtitle_id] option = SUBTITLE(subtitle) subtitle = subtitle.as_dict() subtitle["starts"] = str(subtitle["starts"]) subtitle["ends"] = str(subtitle["ends"]) subtitle["body"] = "" result = simplejson.dumps(dict(option=option.xml(), subtitle=subtitle)) return result elif request.args(1) == "update": def update_record(sub): del (sub["startEvent"]) del (sub["endEvent"]) subtitulation_id = db.subtitle[sub["id"]].subtitulation_id authorize("subtitulation", subtitulation_id) db.subtitle[sub["id"]].update_record(**sub) payload = simplejson.loads(request.vars.data) if isinstance(payload, dict): update_record(payload) elif isinstance(payload, list): for item in payload: update_record(item) else: raise HTTP(500, "Unexpected data format") return simplejson.dumps("Done!") elif request.args(1) == "delete": subtitulation_id = db.subtitle[request.vars.id].subtitulation_id authorize("subtitulation", subtitulation_id) result = db.subtitle[request.vars.id].delete_record() return simplejson.dumps("ok") else: raise HTTP(501, "Not implemented")
def reassign_ingredient(): jsonData = simplejson.loads(request.body.read()) if request.body else {} layoutName = jsonData.get("layoutName") oldID = jsonData.get("oldID") newID = jsonData.get("newID") removeOld = jsonData.get("removeOld") updated = False if layoutName and oldID and newID: from Embed import Embed embedDao = Embed(db) updated = embedDao.edit_ingredient_mapping(layoutName, oldID, newID) if updated and removeOld: query = db.ingredients.id == oldID db(query).delete() if updated: return api_response(update="success") else: return api_error('Input01', "I'm not angry, just disappointed")
def get_user(self): request = self.request if request.vars.token: user = Storage() data = urllib.urlencode(dict(token = request.vars.token)) auth_info_json = fetch(self.auth_url+'?'+data) #print auth_info_json auth_info = json.loads(auth_info_json) if auth_info["identity"] != None: self.profile = auth_info provider = self.profile["provider"] user = self.mappings.get(provider, self.mappings.default)(self.profile) #user["password"] = ??? #user["avatar"] = ??? return user elif self.on_login_failure: redirect(self.on_login_failure) return None
def count_syllables(str): import urllib import urllib2 from gluon.contrib import simplejson # GET JSONP from RhymeBrain API and parse url = 'http://rhymebrain.com/talk' data = {} data['function'] = 'getWordInfo' data['word'] = str url_values = urllib.urlencode(data) full_url = url + '?' + url_values data = urllib2.urlopen(full_url) result = data.read() parsed_json = simplejson.loads(result) # Return number of syllables cast as int return int(parsed_json['syllables'])
def get_user(self): import string request = self.environment.request if request.vars.token: user = Storage() data = urllib.urlencode( dict(apiKey=self.api_key, token=request.vars.token)) auth_info_json = fetch("?".join([self.auth_url, data])) auth_info = json.loads(auth_info_json) if auth_info['stat'] == 'ok': self.profile = auth_info['profile'] provider = self.profile['providerName'] provider = ''.join(c for c in provider if c in string.ascii_letters) for field in self.auth.settings.table_user.fields: user[field] = self.get_mapping(provider, field) if self.on_mapped and user: user = self.on_mapped(user, provider) if self.allow_local: db = self.db user_table = self.auth.settings.table_user if 'username' in user_table.fields: username = '******' else: username = '******' existing = db( user_table[username] == user[username]).select() if len(existing): dbuser = existing.first() if dbuser[self.auth.settings.password_field] != None: self.environment.session.flash = '%s already in use' % username.capitalize( ) return None if 'registration_key' in user_table.fields: if dbuser['registration_key']: self.environment.session.flash = '%s already in use' % username.capitalize( ) return None return user else: return None #auth_info['err']['msg'] return None
def activation(): data = json.loads(request.body.read()) if data['ssn']: citizen_id = db(db.citizen.ssn == data['ssn']).select().first() code = db((db.register_codes.used == False) & ( db.register_codes.citizen_id == citizen_id['id'])).select().last() if code: if data['verification_code'] == code['verification_code']: code.update_record(used=True, code_date=data['code_date'], citizen_id=citizen_id['id']) citizen_id.update_record(active_user=True, citizen_id=citizen_id['id']) return dict(status="activation_successful", citizen_id=citizen_id['id']) else: return dict(status="activation_error") else: return dict(status="error")
def get_currs(currs): curr_in = 'USD' pars_enc = 'q=select * from yahoo.finance.xchange where pair in (' for code in currs: pars_enc += '"%s%s",' % (curr_in, code) pars_enc = pars_enc[:-1] pars_enc += ')&env=store://datatables.org/alltableswithkeys&format=json' #return None, pars_enc import urllib2 req = urllib2.Request( 'http://query.yahooapis.com/v1/public/yql', pars_enc, #headers, ) #return None, '%s' % req page = urllib2.urlopen(req) res = page.read() #print res import gluon.contrib.simplejson as sj res = sj.loads(res) #print res currs = res.get('query') currs = currs and currs.get('results') currs = currs and currs.get('rate') if not currs: print res return res, None #print currs res = {} # если на входе одна пара то на выходе нет массива if type(currs) != type([]): currs = [currs] for curr in currs: if curr['Name'] == 'N/A': continue code = curr['id'][3:] rate = 1 / float(curr['Rate'] or -1) #rate = 1/ float(curr['Ask'] or -1) dd = curr['Date'] tt = curr['Time'] res[code] = rate return None, res
def add_to_group(group_id, person_id=0, people=None, multiple=False): """Adds a person to the group :param person_id: the id of the person :param group_id: the id of the group :returns: a dictionary with the id of the record for the group """ if multiple and people: people = json.loads(people) response = list() for person_id in people: rec_id = db.group_rec.insert(person_id=person_id, group_id=group_id) response.append(dict(group_rec_id=rec_id)) return dict(response=response) else: rec_id = db.group_rec.insert(person_id=person_id, group_id=group_id) return dict(group_rec_id=rec_id)