def update_params(self, d): super(RPC, self).update_params(d) d['js'] = "return ! remoteRequest(self, '%s', '%s', %s, %s)" % ( d.get('action'), d.get('update'), jsonify.encode(d.get('data')), jsonify.encode(self.get_options(d)), )
def test_priority_override(): s = create_session() t = s.query(Test4).get(1) encoded = encode(t) assert encoded == '{"id": 1, "val": "alberto"}' @jsonify.when((Test4,)) def jsonify_test4(obj): return {'val': obj.val} encoded = encode(t) assert encoded == '{"val": "alberto"}'
def test_specific_in_dict(): a = Foo("baz") d = {"a":a} encoded = jsonify.encode(d) print encoded assert encoded == '{"a": "foo-baz"}'
def __init__(self, tabber_options={}, use_cookie=False, hide_on_load=True, *args, **kw): super(Tabber, self).__init__(*args, **kw) js = [] # First some sanity-check if use_cookie and (tabber_options.has_key("onLoad") or tabber_options.has_key("onClick")): warnings.warn( "Cannot use cookies if overriden by " "tabber_options['onClick'] or " "tabber_options['onLoad']. Undefined behavior." ) # Build the js list in it's correct order if use_cookie: js.append(JSLink(static, "tabber/tabber_cookie.js")) if tabber_options: js.append(JSSource("var tabberOptions = %s;" % encode(tabber_options))) if use_cookie: js.append( JSSource( """ try { tabberOptions } catch(e){ tabberOptions = {}; } tabberOptions['onLoad'] = tabber_onload; tabberOptions['onClick'] = tabber_onclick; tabberOptions['cookie'] = 'TGTabber';""" ) ) if hide_on_load: js.append(JSSource("document.write('%s');" % '<style type="text/css">.tabber{display:none;}</style>')) js.append(JSLink(static, "tabber/tabber-minimized.js", location=js_location.bodytop)) self.javascript = js
def jsonify_for_html(obj): json = jsonify.encode(obj) # "</script>" can appear in a JSON string but must not appear inside # a <script> tag with HTML doctype json = json.replace('</', r'\u003c\u002f') # U+2028 and U+2029 are legal in JSON strings but not in JavaScript string # literals: http://timelessrepo.com/json-isnt-a-javascript-subset json = json.replace(u'\u2028', r'\u2028').replace(u'\u2029', r'\u2029') return json
def update_params(self, d): super(TinyMCE, self).update_params(d) d['mce_options'].update(d['new_options']) locale = self._get_locale() if locale: d['mce_options'].setdefault('language', locale) if d['mce_options'].get('mode', 'textareas') == 'exact': d['mce_options']['elements'] = d['field_id'] d['TinyMCEInit'] = "tinyMCE.init(%s);" % encode(d['mce_options'])
def lookup( self ): user = identity.current.user print user.userId print user.emailAddress print user.displayName group = user.groups.pop() print group.groupId print group.displayName permission = user.permissions.pop() print permission.permissionId print permission.groups print group.permissions print group.users print user.groups print user.permissions return [ jsonify.encode( identity.current.user ), jsonify.encode( identity.current.user.groups.pop() ), jsonify.encode( identity.current.user.permissions.pop() ), ]
def __init__(self, tabber_options={}, use_cookie=False, hide_on_load=True, *args, **kw): super(Tabber, self).__init__(*args, **kw) js = [] # First some sanity-check if use_cookie and (tabber_options.has_key('onLoad') or tabber_options.has_key('onClick')): warnings.warn("Cannot use cookies if overriden by " "tabber_options['onClick'] or " "tabber_options['onLoad']. Undefined behavior.") # Build the js list in it's correct order if use_cookie: js.append(JSLink(static, "tabber/tabber_cookie.js")) if tabber_options: js.append( JSSource("var tabberOptions = %s;" % encode(tabber_options))) if use_cookie: js.append( JSSource(""" try { tabberOptions } catch(e){ tabberOptions = {}; } tabberOptions['onLoad'] = tabber_onload; tabberOptions['onClick'] = tabber_onclick; tabberOptions['cookie'] = 'TGTabber';""")) if hide_on_load: js.append( JSSource( "document.write('%s');" % '<style type="text/css">.tabber{display:none;}</style>')) js.append( JSLink(static, "tabber/tabber-minimized.js", location=js_location.bodytop)) self.javascript = js
def update_params(self, d): super(YUITabView, self).update_params(d) d['dynamic'] = jsonify.encode(d['dynamic'])
def update_params(self, d): super(YUITreeView, self).update_params(d) if d['id'] is None: d['id'] = unique_id() d['entries'] = jsonify.encode(d['entries'])
def utilisation_timeseries(self, start=None, end=None, resolution=70, tg_format='json', tg_errors=None, **kwargs): if tg_errors: raise cherrypy.HTTPError(status=400, message=repr(tg_errors)) retval = dict(manual=[], recipe=[], idle_automated=[], idle_manual=[], idle_broken=[], idle_removed=[]) reports_session = create_session(bind=get_reports_engine()) try: systems = self._systems_for_timeseries(reports_session, **kwargs) if not start: start = systems.value(func.min(System.date_added)) or datetime.datetime(2009, 1, 1) if not end: end = datetime.datetime.utcnow().replace(hour=0, minute=0, second=0, microsecond=0) dts = list(dt.replace(microsecond=0) for dt in datetime_range(start, end, step=(end - start) / resolution)) for dt in dts: reserved_query = systems.join('reservations')\ .filter(and_( Reservation.start_time <= dt, or_(Reservation.finish_time >= dt, Reservation.finish_time == None)))\ .group_by(Reservation.type)\ .values(Reservation.type, func.count(System.id)) reserved = dict(reserved_query) for reservation_type in ['recipe', 'manual']: retval[reservation_type].append(reserved.get(reservation_type, 0)) idle_query = systems\ .filter(System.date_added <= dt)\ .filter(not_(System.id.in_(select([Reservation.system_id]).where(and_( Reservation.start_time <= dt, or_(Reservation.finish_time >= dt, Reservation.finish_time == None))))))\ .join('status_durations')\ .filter(and_( SystemStatusDuration.start_time <= dt, or_(SystemStatusDuration.finish_time >= dt, SystemStatusDuration.finish_time == None)))\ .group_by(SystemStatusDuration.status)\ .values(SystemStatusDuration.status, func.count(System.id)) idle = dict(idle_query) for status in SystemStatus: retval['idle_%s' % status.value.lower()].append(idle.get(status, 0)) finally: reports_session.close() if tg_format == 'json': cherrypy.response.headers['Content-Type'] = 'application/json' return jsonify.encode(dict((k, zip((js_datetime(dt) for dt in dts), v)) for k, v in retval.items())) elif tg_format == 'csv': cherrypy.response.headers['Content-Type'] = 'text/csv' stringio = StringIO() csv_writer = csv.writer(stringio) # metadata csv_writer.writerow(['Date generated', str(datetime.datetime.utcnow() .replace(microsecond=0).isoformat()) + 'Z']) csv_writer.writerow(['Generated by', identity.current.user]) csv_writer.writerow(['URL', absolute_url('/reports/utilisation_timeseries?' + cherrypy.request.query_string)]) csv_writer.writerow([]) # header csv_writer.writerow(['timestamp', 'manual', 'recipe', 'idle (automated)', 'idle (manual)', 'idle (broken)']) # data csv_writer.writerows(zip(dts, retval['manual'], retval['recipe'], retval['idle_automated'], retval['idle_manual'], retval['idle_broken'])) return stringio.getvalue() else: raise cherrypy.HTTPError(status=400, message='Unrecognised tg_format %r' % tg_format)
def _jsonify(obj): for k, v in obj.items(): if isinstance(v, dict): obj[k] = _jsonify(v) return jsonify.encode(obj)
def test_specificjson(): a = Foo("baz") encoded = jsonify.encode(a) print encoded assert encoded == '"foo-baz"'
def update_params(self, d): super(RemoteForm, self).update_params(d) d['form_attrs']['onSubmit'] = "return !remoteFormRequest(this, '%s', %s);" % ( d.get("update", ''), jsonify.encode(self.get_options(d)))
def default(self, args=None, **kw): # lang_proxy = rpc.RPCProxy('res.lang') # if(kw.get('lang_code')): # language = kw['lang_code'] # context = rpc.session.context # # context['lang'] = language # lang_id = lang_proxy.search([]) # lang_data = lang_proxy.read(lang_id, [], rpc.session.context) # cherrypy.session['language'] = context['lang'] # cherrypy.session['lang_data'] = lang_data # else: # search_lang = lang_proxy.search([]) # lang_data = lang_proxy.read(search_lang, [], rpc.session.context) # language = 'en_US' # context = rpc.session.context # context['lang'] = language # # if(cherrypy.session.has_key('language')): # cherrypy.session['language'] # cherrypy.session['lang_data'] # else: # cherrypy.session['language'] = context['lang'] # cherrypy.session['lang_data'] = lang_data # selected_items = kw.get('ids', []) selected_items = selected_items and eval(str(selected_items)) if args and not selected_items: pack_proxy = rpc.RPCProxy('evaluation.pack') packs = pack_proxy.search([('name', '=', args)], 0, 0, 0, rpc.session.context) item_ids = pack_proxy.read(packs, ['item_ids'], rpc.session.context) selected_items = item_ids[0].get('item_ids') user_info = cherrypy.session.get('login_info', '') context = rpc.session.context model = 'comparison.factor' proxy = rpc.RPCProxy(model) domain = [('parent_id', '=', False)] ids = proxy.search(domain, 0, 0, 0, context) view = proxy.fields_view_get(False, 'tree', context) fields = proxy.fields_get(False, context) field_parent = view.get("field_parent") or 'child_ids' dom = xml.dom.minidom.parseString(view['arch'].encode('utf-8')) root = dom.childNodes[0] attrs = tools.node_attributes(root) self.head = [] self.parse(root, fields) self.headers = [] add_factor = {} add_factor['name'] = "add_factor" add_factor['type'] = "image" add_factor['string'] = '' add_factor['colspan'] = 2 sh_graph = {} sh_graph['name'] = 'show_graph' sh_graph['type'] = 'image' sh_graph['string'] = '' sh_graph['colspan'] = -1 incr = {} incr['name'] = 'incr' incr['type'] = 'image' incr['string'] = '' incr['colspan'] = -1 decr = {} decr['name'] = 'decr' decr['type'] = 'image' decr['string'] = '' decr['colspan'] = -1 self.headers += [self.head[0]] self.headers += [add_factor] self.headers += [sh_graph] self.headers += [self.head[1]] self.headers += [incr] self.headers += [decr] fields = [] item_model = 'comparison.item' proxy_item = rpc.RPCProxy(item_model) item_ids = proxy_item.search([], 0, 0, 0, context) res = proxy_item.read(item_ids, ['name', 'code', 'load_default']) titles = [] ses_id = [] for r in res: title = {} title['sel'] = False if selected_items: ses_id = selected_items item = {} for s in selected_items: if r['id'] == s: item['id'] = r['id'] item['type'] = 'url' item['string'] = r['name'] item['name'] = r['name'] item['code'] = r['code'] title['sel'] = True title['load'] = r['load_default'] self.headers += [item] elif r['load_default']: item = {} item['id'] = r['id'] item['type'] = 'url' item['string'] = r['name'] item['name'] = r['name'] item['code'] = r['code'] self.headers += [item] ses_id.append(r['id']) cherrypy.session['selected_items'] = ses_id title['name'] = r['name'] title['id'] = r['id'] title['code'] = r['code'] title['load'] = r['load_default'] titles += [title] sel_ids=[] for t in titles: if t['load'] or t['sel']: sel_ids += [t['id']] # cherrypy.response.simple_cookie['selected_items'] = sel_ids for field in self.headers: if field['name'] == 'name' or field['name'] == 'ponderation': fields += [field['name']] fields = jsonify.encode(fields) icon_name = self.headers[0].get('icon') # if kw.has_key('all'): # self.url = '/comparison/data' # self.url_params = dict(model=model, # ids=ids, # fields=ustr(fields), # domain=ustr(domain), ## context=ustr(context), # field_parent=field_parent, # icon_name=icon_name,all = kw.get('all')) # else: self.url = '/comparison/data' self.url_params = dict(model=model, ids=ids, fields=ustr(fields), domain=ustr(domain), context=ustr(context), field_parent=field_parent, icon_name=icon_name) def _jsonify(obj): for k, v in obj.items(): if isinstance(v, dict): obj[k] = _jsonify(v) return jsonify.encode(obj) self.url_params = _jsonify(self.url_params) self.headers = jsonify.encode(self.headers) return dict(headers=self.headers, url_params=self.url_params, url=self.url, titles=titles, selected_items=selected_items)
def test_saobj(): s = create_session() t = s.query(Test1).get(1) encoded = encode(t) assert encoded == '{"id": 1, "val": "bob"}'
def _from_python(self, value, state): return jsonify.encode(value)
def test_explicit_saobj(): s = create_session() t = s.query(Test3).get(1) encoded = encode(t) assert encoded == '{"id": 1, "val": "bob", "customized": true}'
def test_salist(): s = create_session() t = s.query(Test1).get(1) encoded = encode(t.test2s) assert encoded == ('[{"test1id": 1, "id": 1, "val": "fred"},' ' {"test1id": 1, "id": 2, "val": "alice"}]')
def test_select_row(): s = create_session() t = test1.select().execute() encoded = encode(t) assert encoded == '[{"id": 1, "val": "bob"}]'
def test_select_rows(): s = create_session() t = test2.select().execute() encoded = encode(t) assert encoded == ('[{"test1id": 1, "id": 1, "val": "fred"},' ' {"test1id": 1, "id": 2, "val": "alice"}]')
def update_params(self, d): super(AjaxGrid, self).update_params(d) d["defaults"] = jsonify.encode(d["defaults"])
def test_dictionary(): d = {'a':1, 'b':2} encoded = jsonify.encode(d) print encoded assert encoded == '{"a": 1, "b": 2}'