def get_roles(user_id): try: user_role_repository = UserRoleRepository() user_roles = user_role_repository.get(**{"user_id": user_id}) return Response(response=json.dumps(user_roles), status=HTTPStatus.OK, mimetype='application/json') except Exception as err: if 'message' not in err.__dict__: err.message = repr(err) print(err.__dict__, '\n\n') return Response(response=json.dumps({"errors": err.message}), status=HTTPStatus.BAD_REQUEST.value, mimetype='application/json')
def list_resources(app_id): try: resource_repository = ResourceRepository() resources = resource_repository.list(app_id) return Response(response=json.dumps(resources), status=HTTPStatus.OK, mimetype='application/json') except Exception as err: if 'message' not in err.__dict__: err.message = repr(err) print(err.__dict__, '\n\n') return Response(response=json.dumps({"errors": err.message}), status=HTTPStatus.BAD_REQUEST.value, mimetype='application/json')
def get_permission_data(app_id, role_id): try: role_repository = RoleRepository() permissions = role_repository.get_permissions(app_id, role_id) return Response(response=json.dumps(permissions), status=HTTPStatus.OK.value, mimetype='application/json') except Exception as err: if 'message' not in err.__dict__: err.message = repr(err) print(err.__dict__, '\n\n') return Response(response=json.dumps({"errors": err.message}), status=HTTPStatus.NOT_FOUND.value, mimetype='application/json')
def handle_json(self, artwork): '''send the complete details as json object''' artwork = json.dumps(artwork) cherrypy.response.headers['Content-Type'] = 'application/json' cherrypy.response.headers['Content-Length'] = len(artwork) if cherrypy.request.method.upper() == 'GET': return artwork
def get_permissions(app_id, role_id): try: role_permission_repository = RolePermissionRepository() role_permission = role_permission_repository.get( **{"role_id": role_id}) return Response(response=json.dumps(role_permission), status=HTTPStatus.OK.value, mimetype='application/json') except Exception as err: if 'message' not in err.__dict__: err.message = repr(err) print(err.__dict__, '\n\n') return Response(response=json.dumps({"errors": err.message}), status=HTTPStatus.BAD_REQUEST.value, mimetype='application/json')
def send_message(self, message): assert type(message) == LinkedInMessage, 'LinkedInInvitation required' url = '%s/~/mailbox' % ENDPOINTS.PEOPLE response = self.make_request('POST', url, data=json.dumps(message.json)) raise_for_error(response) return True
def test_json(): pt.initialize() res = [pt.lcut(s) for s in sentences] j = json.dumps(res, cls=PairJSONEncoder) print(j) k = json.loads(j, cls=PairJSONDecoder) print(k)
def submit_company_share(self, company_id, comment=None, title=None, description=None, submitted_url=None, submitted_image_url=None, visibility_code='anyone'): post = { 'visibility': { 'code': visibility_code, }, } if comment is not None: post['comment'] = comment if title is not None and submitted_url is not None: post['content'] = { 'title': title, 'submitted-url': submitted_url, 'description': description, } if submitted_image_url: post['content']['submitted-image-url'] = submitted_image_url url = '%s/%s/shares' % (ENDPOINTS.COMPANIES, company_id) response = self.make_request('POST', url, data=json.dumps(post)) raise_for_error(response) return response.json()
def add_permission(app_id, role_id): try: role_permission_repository = RolePermissionRepository() data = request.get_json() data['role_id'] = role_id role_permission = role_permission_repository.create(app_id, **data) return Response(response=json.dumps(role_permission), status=HTTPStatus.OK.value, mimetype='application/json') except Exception as err: if 'message' not in err.__dict__: err.message = repr(err) print(err.__dict__, '\n\n') return Response(response=json.dumps({"errors": err.message}), status=HTTPStatus.BAD_REQUEST.value, mimetype='application/json')
def like_post(self, post_id, action): url = '%s/%s/relation-to-viewer/is-liked' % (ENDPOINTS.POSTS, str(post_id)) try: self.make_request('PUT', url, data=json.dumps(action)) except (requests.ConnectionError, requests.HTTPError) as error: raise LinkedInError(error.message) else: return True
def get_json(jsonmethod, sort=None, filters=None, fields=None, limits=None, returntype=None, optparam=None, filtertype=None): '''method to get details from the kodi json api''' kodi_json = {} kodi_json["jsonrpc"] = "2.0" kodi_json["method"] = jsonmethod kodi_json["params"] = {} if optparam: if isinstance(optparam, list): for param in optparam: kodi_json["params"][param[0]] = param[1] else: kodi_json["params"][optparam[0]] = optparam[1] kodi_json["id"] = 1 if sort: kodi_json["params"]["sort"] = sort if filters: if not filtertype: filtertype = "and" if len(filters) > 1: kodi_json["params"]["filter"] = {filtertype: filters} else: kodi_json["params"]["filter"] = filters[0] if fields: kodi_json["params"]["properties"] = fields if limits: kodi_json["params"]["limits"] = { "start": limits[0], "end": limits[1] } json_response = xbmc.executeJSONRPC(try_encode(json.dumps(kodi_json))) json_object = json.loads(json_response.decode('utf-8', 'replace')) # set the default returntype to prevent errors if "details" in jsonmethod.lower(): result = {} else: result = [] if 'result' in json_object: if returntype and returntype in json_object['result']: # returntype specified, return immediately result = json_object['result'][returntype] else: # no returntype specified, we'll have to look for it for key, value in json_object['result'].iteritems(): if not key == "limits" and (isinstance(value, list) or isinstance(value, dict)): result = value else: log_msg(json_response) log_msg(kodi_json) return result
def set_json(jsonmethod, params): '''method to set info in the kodi json api''' kodi_json = {} kodi_json["jsonrpc"] = "2.0" kodi_json["method"] = jsonmethod kodi_json["params"] = params kodi_json["id"] = 1 json_response = xbmc.executeJSONRPC(try_encode(json.dumps(kodi_json))) return json.loads(json_response.decode('utf-8', 'replace'))
def dumps(lst, root_pid=ROOT_OBJECT_ID, add_root=True): l = refactor(lst, root_pid) root = [] if add_root: r = Tree(ROOT_OBJECT_ID, '', 'root') r.children = l root.append(r) else: root = l return json.dumps({'status':1, 'data':root}, default=encode_tree)
def comment_post(self, post_id, comment): post = { 'text': comment } url = '%s/%s/comments' % (ENDPOINTS.POSTS, str(post_id)) try: self.make_request('POST', url, data=json.dumps(post)) except (requests.ConnectionError, requests.HTTPError) as error: raise LinkedInError(error.message) else: return True
def set(self, url, post_data, data, headers): if post_data: url_hash = hashlib.sha1(url + '?' + post_data).hexdigest() else: url_hash = hashlib.sha1(url).hexdigest() domain = ".".join(urlparse.urlparse(url)[1].split('.')[-2:]) conn = self.connect() c = conn.cursor() # Insert a row of data if not post_data: post_data="" only_headers = 0 if data == -1: only_headers = 1 data = "" created = time.mktime(time.localtime()) content_type = headers.get('content-type', '').split(';')[0].strip() if content_type in COMPRESS_TYPES: compressed = 1 data = zlib.compress(data) else: compressed = 0 data = sqlite3.Binary(data) #fixme: this looks wrong try: _headers = json.dumps(headers) except: for h in headers: headers[h] = headers[h].decode(detect_encoding(headers[h])) _headers = json.dumps(headers) t = (url_hash, domain, url, post_data, _headers, created, data, only_headers, compressed) c.execute(u"""INSERT OR REPLACE INTO cache values (?, ?, ?, ?, ?, ?, ?, ?, ?)""", t) # Save (commit) the changes and clean up conn.commit() c.close() conn.close()
def set_json(jsonmethod, params): """method to set info in the kodi json api""" kodi_json = {} kodi_json["jsonrpc"] = "2.0" kodi_json["method"] = jsonmethod kodi_json["params"] = params kodi_json["id"] = 1 json_response = xbmc.executeJSONRPC(try_encode(json.dumps(kodi_json))) if sys.version_info.major == 3: return json.loads(json_response) else: return json.loads(json_response.decode('utf-8', 'replace'))
def create_resource(app_id): try: resource_repository = ResourceRepository() data = request.get_json() is_duplicated, error_message = resource_repository.is_duplicated_data( app_id, data) if is_duplicated: return Response(response=json.dumps({"errors": error_message}), status=HTTPStatus.CONFLICT.value, mimetype='application/json') data['app_id'] = app_id resource = resource_repository.create(**data) return Response(response=json.dumps(resource), status=HTTPStatus.CREATED.value, mimetype='application/json') except Exception as err: if 'message' not in err.__dict__: err.message = repr(err) print(err.__dict__, '\n\n') return Response(response=json.dumps({"errors": err.message}), status=HTTPStatus.BAD_REQUEST.value, mimetype='application/json')
def delete_resource(app_id, resource_id): try: resource_repository = ResourceRepository() resource_repository.delete(resource_id, app_id) return Response(response="", status=HTTPStatus.NO_CONTENT, mimetype='application/json') except Exception as err: if 'message' not in err.__dict__: err.message = repr(err) print(err.__dict__, '\n\n') return Response(response=json.dumps({"errors": err.message}), status=HTTPStatus.BAD_REQUEST.value, mimetype='application/json')
def update_role(app_id, role_id): try: role_repository = RoleRepository() data = request.get_json() is_duplicated, error_message = role_repository.is_duplicated_data( app_id, data, role_id) if is_duplicated: return Response(response=json.dumps({"errors": error_message}), status=HTTPStatus.CONFLICT.value, mimetype='application/json') role = role_repository.update(role_id, app_id, **data) return Response(response=json.dumps(role), status=HTTPStatus.ACCEPTED.value, mimetype='application/json') except Exception as err: if 'message' not in err.__dict__: err.message = repr(err) print(err.__dict__, '\n\n') return Response(response=json.dumps({"errors:": err.message}), status=HTTPStatus.BAD_REQUEST.value, mimetype='application/json')
def list_channel(self, channel=None, verbose=False): if channel: try: console_output(str(self[channel].jsonconf)) except KeyError: logger.warning("No such channel '%s'.", channel) else: console_output("") console_output("Current channels:") for cname in self.iterkeys(): c = self[cname].jsonconf console_output(" * %s: %s %s" % (c["channel_name"], c["platform"], c["open"])) if verbose: console_output(" %s" % json.dumps(c)) console_output("")
def add_channel(self, jsonconf): logger.debug(json.dumps(jsonconf)) cname = jsonconf["channel_name"] if cname in self: logger.warning("Duplicate channel_name '%s'. Nothing happens to it. ", cname) return False try: p = getattr(platform, jsonconf["platform"]) self[cname] = p(jsonconf) self.__method_routing(cname, SNSPocket.__default_mapping) except AttributeError: logger.warning("No such platform '%s'. Nothing happens to it. ", jsonconf["platform"]) return True
def list_channel(self, channel=None, verbose=False): if channel: try: console_output(str(self[channel].jsonconf)) except KeyError: logger.warning("No such channel '%s'.", channel) else: console_output("") console_output("Current channels:") for cname in self.iterkeys(): c = self[cname].jsonconf console_output(" * %s: %s %s" % \ (c['channel_name'],c['platform'],c['open'])) if verbose: console_output(" %s" % json.dumps(c)) console_output("")
def submit_group_post(self, group_id, title, summary, submitted_url, submitted_image_url, content_title, description): post = { 'title': title, 'summary': summary, 'content': { 'submitted-url': submitted_url, 'title': content_title, 'description': description } } if submitted_image_url: post['content']['submitted-image-url'] = submitted_image_url url = '%s/%s/posts' % (ENDPOINTS.GROUPS, str(group_id)) response = self.make_request('POST', url, data=json.dumps(post)) raise_for_error(response) return True
def add_channel(self, jsonconf): logger.debug(json.dumps(jsonconf)) cname = jsonconf['channel_name'] if cname in self: logger.warning( "Duplicate channel_name '%s'. Nothing happens to it. ", cname) return False try: p = getattr(platform, jsonconf['platform']) self[cname] = p(jsonconf) self.__method_routing(cname, SNSPocket.__default_mapping) except AttributeError: logger.warning("No such platform '%s'. Nothing happens to it. ", jsonconf['platform']) return True
def jsondumps(obj): return json.dumps(obj, separators=jsonseps)
def send_message_to_contact(self, token, message): payload = {'from': YOUR_TRIAL_NUMBER, 'to': DESTINATION_NUMBER, 'body': message} response = requests.post(MOORSE_URL + API_URL+"/v2/whatsApp/sendMessage", verify=False, data=json.dumps(payload), headers={'content-type': 'application/json', 'Authorization': token}) response = json.to_json(response.text) return response['data']
def __init__(self, response=None): if response is None or isinstance(response, dict): self.response = json.dumps({"data": response, "errcode": 0, "errmsg": ""}) else: self.response = response
def send_message_to_group(self, token, message): payload = {"groupId": GROUPID, "body": message} response = requests.post(MOORSE_URL + API_URL + "/v2/whatsApp/groups/sendMessage", verify=False, data=json.dumps(payload), headers={'content-type': 'application/json', 'Authorization': token}) response = json.to_json(response.text) return response['data']
def value_from_object(self, obj): return json.dumps(super(JSONField, self).value_from_object(obj))
def sync_to_file(self): with open(self.__notes_file, "w", encoding="utf8") as f: data = dsjson.dumps(self._notes, indent=2) f.write(data)
def convert_context_to_json(self, context): "Convert the context dictionary into a JSON object" return json.dumps(context)
def join_group(self, group_id): url = '%s/~/group-memberships/%s' % (ENDPOINTS.PEOPLE, str(group_id)) response = self.make_request('PUT', url, data=json.dumps({'membershipState': {'code': 'member'}})) raise_for_error(response) return True
def cookie_encode(name, pwd): dd = { 'email': name, 'pwd': pwd } ds = json.dumps(dd) return _encode(ds)
def handle_request(self, headers_only=False): '''send headers and reponse''' image = "" try: artwork = {} params = self.get_params() action = params.get("action", "") title = params.get("title", "") preferred_types = params.get("type") if preferred_types: preferred_types = preferred_types.split(",") else: preferred_types = [] fallback = params.get("fallback", "") is_json_request = params.get("json", "") == "true" if fallback.startswith("Default"): fallback = "special://skin/media/" + fallback log_msg("webservice called with params: %s" % params) # search image on google if action == "getthumb": image = self.server.artutils.google.search_image(title) # get pvr image elif "pvrthumb" in action: channel = params.get("channel", "") genre = params.get("genre", "") artwork = self.server.artutils.get_pvr_artwork(title, channel, genre) if action == "getallpvrthumb": is_json_request = True # get video artwork and metadata elif action == "getartwork": if not preferred_types: is_json_request = True year = params.get("year", "") media_type = params.get("mediatype", "") imdb_id = params.get("imdbid", "") if not imdb_id: artwork = self.server.artutils.get_tmdb_details("", "", title, year, media_type) if artwork: imdb_id = artwork.get("imdbnumber") if not media_type: media_type = artwork.get("media_type") if imdb_id: artwork = extend_dict(artwork, self.server.artutils.get_extended_artwork(imdb_id, "", media_type)) # music art elif action == "getmusicart": artist = params.get("artist", "") album = params.get("album", "") track = params.get("track", "") artwork = self.server.artutils.get_music_artwork(artist, album, track) # genre images elif "genreimages" in action and preferred_types: arttype = preferred_types[0].split(".")[0] mediatype = "tvshows" if "tvshow" in action else "movies" randomize = "true" if "random" in action else "false" lib_path = u"plugin://script.skin.helper.service/?action=genrebackground"\ "&genre=%s&arttype=%s&mediatype=%s&random=%s" % (title, arttype, mediatype, randomize) for count, item in enumerate(self.server.artutils.kodidb.files(lib_path, limits=(0, 5))): artwork["%s.%s" % (arttype, count)] = item["file"] # image from variable elif "getvarimage" in action: title = title.replace("{", "[").replace("}", "]") image = xbmc.getInfoLabel(title) if not xbmcvfs.exists(image): if "resource.images" in image: log_msg( "Texture packed resource addons are not supported by the webservice! - %s" % image, xbmc.LOGWARNING) image = "" if not is_json_request: if artwork and artwork.get("art"): artwork = artwork["art"] if preferred_types: for pref_type in preferred_types: if not image: image = artwork.get(pref_type, "") elif not image and artwork.get("landscape"): image = artwork["landscape"] elif not image and artwork.get("fanart"): image = artwork["fanart"] elif not image and artwork.get("poster"): image = artwork["poster"] elif not image and artwork.get("thumb"): image = artwork["thumb"] # set fallback image if nothing else worked if not image: image = fallback log_msg("webservice image: %s - fallback: %s - artwork: %s - title: %s" % (image, fallback, artwork, title)) if is_json_request and artwork: # send json reponse artwork = json.dumps(artwork) self.send_response(200) self.send_header('Content-type', 'application/json') self.send_header('Content-Length', len(artwork)) self.end_headers() if not headers_only: self.wfile.write(artwork) elif image: # send single image self.send_response(200) if ".jpg" in image: self.send_header('Content-type', 'image/jpg') elif image.lower().endswith(".gif"): self.send_header('Content-type', 'image/gif') else: self.send_header('Content-type', 'image/png') modified = xbmcvfs.Stat(image).st_mtime() self.send_header('Last-Modified', "%s" % modified) image = xbmcvfs.File(image) size = image.size() self.send_header('Content-Length', str(size)) self.end_headers() if not headers_only: log_msg("sending image for request %s" % (self.path)) self.wfile.write(image.readBytes()) image.close() else: self.send_error(404, 'No image was found') except Exception as exc: log_exception(__name__, exc) self.send_error(500, 'Exception occurred: %s' % exc) finally: return
def like_update(self, update_key, is_liked=True): url = '%s/~/network/updates/key=%s/is-liked' % (ENDPOINTS.PEOPLE, update_key) response = self.make_request('PUT', url, data=json.dumps(is_liked)) raise_for_error(response) return True
def comment_on_update(self, update_key, comment): comment = {'comment': comment} url = '%s/~/network/updates/key=%s/update-comments' % (ENDPOINTS.PEOPLE, update_key) response = self.make_request('POST', url, data=json.dumps(comment)) raise_for_error(response) return True
def get_db_prep_value(self, value, connection, prepared=False): """Convert JSON object to a string""" if isinstance(value, basestring): return value return json.dumps(value, **self.dump_kwargs)
def follow_company(self, company_id): url = '%s/~/following/companies' % ENDPOINTS.PEOPLE post = {'id': company_id} response = self.make_request('POST', url, data=json.dumps(post)) raise_for_error(response) return True