def _request(self, path, method='GET', data=None): out = self._conn.request(self.name, path, method, data) # Allow connection to return dict if self._conn.response_type != "dict": out = simplejson.loads(out) return storify(out)
def search_imdb(self, name, imdb_id='', year=''): ''' Search IMDB by either IMDB ID or Name/Year Args: name (str): full name of movie you are searching Kwargs: imdb_id (str): IMDB ID year (str): 4 digit year of video, recommended to include the year whenever possible to maximize correct search results. Returns: DICT of meta data or None if cannot be found. ''' #Set IMDB API URL based on the type of search we need to do if imdb_id: url = self.imdb_api % imdb_id else: name = urllib.quote(name) if year: url = self.imdb_nameyear_api % (name, year) else: url = self.imdb_name_api % name try: addon.log('Requesting IMDB : %s' % url, 0) meta = simplejson.loads(net.http_GET(url).content) addon.log('IMDB Meta: %s' % meta, 0) except Exception, e: addon.log("Error connecting to IMDB: %s " % e, 4) return {}
def handle_error(self, status, error): try: data = simplejson.loads(error) message = data.get('message', '') json = error except: message = error json = None raise ClientException(status, message, json)
def load_things(keys, query): _things = simplejson.loads(store.get_many(keys)) xthings.update(_things) for k, v in query.requested.items(): k = web.lstrips(k, query.prefix) if isinstance(v, Query): keys2 = common.flatten([d.get(k) for d in _things.values() if d.get(k)]) keys2 = [k['key'] for k in keys2] load_things(set(keys2), v)
def _read_input_json(self): try: sent = self._read_input() if sent is not None: content = json.loads(sent) except ValueError: self.log_message('JSON: /invalid, sent=[%s]' % sent) return None self.log_message('JSON: %s', content) return content
def _read_input_json(self): try: sent = self._read_input() if sent is not None: content = json.loads( sent) except ValueError: self.log_message( 'JSON: /invalid, sent=[%s]' % sent) return None self.log_message( 'JSON: %s', content) return content
def load_things(keys, query): _things = simplejson.loads(store.get_many(keys)) xthings.update(_things) for k, v in query.requested.items(): k = web.lstrips(k, query.prefix) if isinstance(v, Query): keys2 = common.flatten( [d.get(k) for d in _things.values() if d.get(k)]) keys2 = [k['key'] for k in keys2] load_things(set(keys2), v)
def save(self, key, data, timestamp=None, comment=None, machine_comment=None, ip=None, author=None, transaction_id=None): timestamp = timestamp or datetime.datetime.utcnow() t = self.db.transaction() metadata = self.get_metadata(key) try: typekey = data['type'] type_id = self._key2id(typekey) if metadata: # already existing object revision = None thing_id = metadata.id olddata = simplejson.loads(self.get(key)) created = metadata.created action = "update" else: revision = 1 thing_id = self.new_thing(key=key, type=type_id, latest_revision=1, last_modified=timestamp, created=timestamp) olddata = {} created = timestamp action = "create" if transaction_id is None: transaction_id = self._add_transaction(action=action, author=author, ip=ip, comment=comment, created=timestamp) revision = self._add_version(thing_id=thing_id, revision=revision, transaction_id=transaction_id, created=timestamp) self._update_tables(thing_id, key, olddata, dict(data)) #@@ why making copy of data? data['created'] = created data['revision'] = revision data['last_modified'] = timestamp data['key'] = key data['id'] = thing_id data['latest_revision'] = revision data = common.format_data(data) self.db.update('thing', where='id=$thing_id', last_modified=timestamp, latest_revision=revision, type=type_id, vars=locals()) self.db.insert('data', seqname=False, thing_id=thing_id, revision=revision, data=simplejson.dumps(data)) except: t.rollback() self.cache.clear(local=True) raise else: t.commit() web.ctx.new_objects[key] = simplejson.dumps(data) return {'key': key, 'revision': revision}
def __call__(self, *args, **kwargs): params = kwargs if len(kwargs) else args if Any.kind(params) == Object and self.__version != '2.0': raise Exception('Unsupport arg type for JSON-RPC 1.0 ' '(the default version for this client, ' 'pass version="2.0" to use keyword arguments)') r = urllib.urlopen( self.__service_url, dumps({ "jsonrpc": self.__version, "method": self.__service_name, 'params': params, 'id': str(uuid.uuid1()) })).read() return loads(r)
def _do_request_all(self, method, values): ''' Request JSON data from TMDB, returns all matches found Args: method (str): Type of TMDB request to make values (str): Value to use in TMDB lookup request Returns: DICT of meta data found on TMDB Returns None when not found or error requesting page ''' url = "%s/%s?language=%s&api_key=%s&%s" % (self.url_prefix, method, self.lang, self.api_key, values) addon.log('Requesting TMDB : %s' % url, 0) try: meta = simplejson.loads(net.http_GET(url,{"Accept":"application/json"}).content) except Exception, e: addon.log("Error connecting to TMDB: %s " % e, 4) return None
def reindex(self, keys): """Remove all entries from index table and add again.""" t = self.db.transaction() try: thing_ids = dict((key, self._key2id(key)) for key in keys) docs = dict((key, simplejson.loads(self.get(key))) for key in keys) deletes = {} for key in keys: type = docs[key]['type']['key'] for table in self.schema.find_tables(type): deletes.setdefault(table, []).append(thing_ids[key]) for table, ids in deletes.items(): self.db.delete(table, where="thing_id IN $ids", vars=locals()) for key in keys: self._update_tables(thing_ids[key], key, {}, docs[key]) except: t.rollback() raise else: t.commit()
def from_json(store, key, data): return Thing.from_dict(store, key, simplejson.loads(data))
def POST(self, sitename): i = input("keys") keys = simplejson.loads(i['keys']) site = get_site(sitename) site.store.reindex(keys) return {"status": "ok"}
def POST_save_many(self, sitename): store = get_site(sitename).get_store() json = get_data() docs = simplejson.loads(json) store.put_many(docs)
def info( address): str_info = get( address, "/state") if str_info is None: return None return json.loads( str_info)
def load_json( s): return json.loads( s)
def load_json(s): return json.loads(s)
def _request(self, path, method='GET', data=None): out = self.conn.request(self.name, "/_seq/" + path, method, data) return simplejson.loads(out)
def pull( address): s = get( address, "/copy") if s is None: return None return json.loads( s)
def valid_json(self, line): try: simplejson.loads(line) return True except ValueError: return False
def assert_valid_json(self, line): try: simplejson.loads(line) except ValueError: raise web.BadRequest()
def PUT(self, sitename, path): store = get_site(sitename).get_store() json = get_data() doc = simplejson.loads(json) store.put(path, doc) return JSON('{"ok": true}')
def _loads(self, line): entry = simplejson.loads(line) entry = web.storage(entry) entry.timestamp = to_timestamp(entry.timestamp) return entry
def get_data(self): if self.json: return simplejson.loads(self.json) else: return {}
def info(address): str_info = get(address, "/state") if str_info is None: return None return json.loads(str_info)
def pull(address): s = get(address, "/copy") if s is None: return None return json.loads(s)
def loads(s, *, cls=None, **kw): """Deserialize ``s`` (a ``str``, ``bytes`` or ``bytearray`` instance containing a JSON document) to a Python object. ``object_hook`` is an optional function that will be called with the result of any object literal decode (a ``dict``). The return value of ``object_hook`` will be used instead of the ``dict``. This feature can be used to implement custom decoders (e.g. JSON-RPC class hinting). ``object_pairs_hook`` is an optional function that will be called with the result of any object literal decoded with an ordered list of pairs. The return value of ``object_pairs_hook`` will be used instead of the ``dict``. This feature can be used to implement custom decoders. If ``object_hook`` is also defined, the ``object_pairs_hook`` takes priority. ``parse_float``, if specified, will be called with the string of every JSON float to be decoded. By default this is equivalent to float(num_str). This can be used to use another datatype or parser for JSON floats (e.g. decimal.Decimal). ``parse_int``, if specified, will be called with the string of every JSON int to be decoded. By default this is equivalent to int(num_str). This can be used to use another datatype or parser for JSON integers (e.g. float). ``parse_constant``, if specified, will be called with one of the following strings: -Infinity, Infinity, NaN. This can be used to raise an exception if invalid JSON numbers are encountered. To use a custom ``JSONDecoder`` subclass, specify it with the ``cls`` kwarg; otherwise ``JSONDecoder`` is used. The ``encoding`` argument is ignored and deprecated since Python 3.1. """ if isinstance(s, str): if s.startswith('\ufeff'): raise JSONDecodeError("Unexpected UTF-8 BOM (decode using utf-8-sig)", s, 0) else: if not isinstance(s, (bytes, bytearray)): raise TypeError(f'the JSON object must be str, bytes or bytearray, ' f'not {s.__class__.__name__}') s = s.decode(detect_encoding(s), 'surrogatepass') if "encoding" in kw: import warnings warnings.warn( "'encoding' is ignored and deprecated. It will be removed in Python 3.9", DeprecationWarning, stacklevel=2 ) del kw['encoding'] if cls is None: # Brython-specific : in the most simple case, use Javascript JSON : this # is much faster. return _json.loads(s, **kw) if object_hook is not None: kw['object_hook'] = object_hook if object_pairs_hook is not None: kw['object_pairs_hook'] = object_pairs_hook if parse_float is not None: kw['parse_float'] = parse_float if parse_int is not None: kw['parse_int'] = parse_int if parse_constant is not None: kw['parse_constant'] = parse_constant return cls(**kw).decode(s)
def _request(self, path, method='GET', data=None): out = self._conn.request(self.name, path, method, data) out = simplejson.loads(out) return storify(out)
def from_json(s): try: return simplejson.loads(s) except ValueError, e: raise common.BadData(message="Bad JSON: " + str(e))
def assert_valid_json(self, line): try: simplejson.loads(line) except ValueError: raise web.BadRequest(message="Invalid json")