def disconnect(): """Revoke current user's token and reset their session.""" # Only disconnect a connected user. credentials = session.get('credentials') if credentials is None: response = make_response(json.dumps('Current user not connected.'), 401) response.headers['Content-Type'] = 'application/json' return response # Execute HTTP GET request to revoke current token. access_token = credentials.access_token url = 'https://accounts.google.com/o/oauth2/revoke?token=%s' % access_token h = httplib2.Http() result = h.request(url, 'GET')[0] if result['status'] == '200': # Reset the user's session. del session['credentials'] response = make_response(json.dumps('Successfully disconnected.'), 200) response.headers['Content-Type'] = 'application/json' return response else: # For whatever reason, the given token was invalid. response = make_response( json.dumps('Failed to revoke token for given user.', 400)) response.headers['Content-Type'] = 'application/json' return response
def _test_get_facebook_pages(self): print "test_get_facebook_pages" from unifide_backend.action.social.facebook.action import get_fb_user, get_fb_page_list user_id = "xaa8LzkwtCCgb6BeP" fbUser = get_fb_user(user_id) page_list = get_fb_page_list(fbUser.fb_id, fbUser.access_token) assert page_list is not None print json.dumps({"status": "ok", "page_list": page_list})
def item_save(): item={} stomp_connection = messaging_helper.getConnection() try: logging_debug(request.form.get('item_name')) item_name = request.form['item_name'] description = request.form['description'] brand = request.form['brand'] price = request.form['price'] category = request.form['category'] image_url_1 = request.form['image_url_1'] image_url_2 = request.form['image_url_2'] image_url_3 = request.form['image_url_3'] owner_id = request.form['owner_id'] owner_name = request.form['owner_name'] gotwish = request.form['gotwish'] item['item_name'] = item_name item['description'] = description item['brand'] = brand item['price'] = price item['category'] = category item['image_url_1'] = image_url_1 item['image_url_2'] = image_url_2 item['image_url_3'] = image_url_3 item['owner_id'] = owner_id item['owner_name'] = owner_name item['gotwish'] = gotwish logging_debug(item) item_id = dao.insert_item(item) worker_item = {} worker_item['owner_id'] = owner_id worker_item['item_id'] = item_id worker_item['work_type'] = "save" worker_item['category'] = category worker_item['gotwish'] = gotwish logging_debug(json.dumps(worker_item)) stomp_connection.send(json.dumps(worker_item), destination='/topic/test') except KeyError, e: logging_debug(KeyError) logging_debug(e)
def debug_info(self): if not json_available or not sqlalchemy_available: return {} queries = get_debug_queries() data = [] for query in queries: is_select = query.statement.strip().lower().startswith('select') _params = '' try: _params = json.dumps(query.parameters) except TypeError: pass # object not JSON serializable hash = hashlib.sha1( current_app.config['SECRET_KEY'] + query.statement + _params).hexdigest() data.append({ 'duration': query.duration, 'sql': format_sql(query.statement, query.parameters), 'raw_sql': query.statement, 'hash': hash, 'params': _params, 'is_select': is_select, 'context_long': query.context, 'context': format_fname(query.context) }) return data
def request(self, host, requests): server = "http://%s/jsonrpc" % host data = [] for req in requests: method, kwargs = req data.append({"method": method, "params": kwargs, "jsonrpc": "2.0", "id": method}) data = json.dumps(data) headers = {"Content-Type": "application/json"} if self.conf("password"): base64string = base64.encodestring("%s:%s" % (self.conf("username"), self.conf("password"))).replace( "\n", "" ) headers["Authorization"] = "Basic %s" % base64string try: log.debug("Sending request to %s: %s", (host, data)) rdata = self.urlopen(server, headers=headers, params=data, multipart=True) response = json.loads(rdata) log.debug("Returned from request %s: %s", (host, response)) return response except: log.error("Failed sending request to XBMC: %s", traceback.format_exc()) return []
def content(self): if not json_available or not sqlalchemy_available: msg = ['Missing required libraries:', '<ul>'] if not json_available: msg.append('<li>simplejson</li>') if not sqlalchemy_available: msg.append('<li>Flask-SQLAlchemy</li>') msg.append('</ul>') return '\n'.join(msg) queries = get_debug_queries() data = [] for query in queries: is_select = query.statement.strip().lower().startswith('select') _params = '' try: _params = json.dumps(query.parameters) except TypeError: pass # object not JSON serializable hash = hashlib.sha1( current_app.config['SECRET_KEY'] + query.statement + _params).hexdigest() data.append({ 'duration': query.duration, 'sql': format_sql(query.statement, query.parameters), 'raw_sql': query.statement, 'hash': hash, 'params': _params, 'is_select': is_select, 'context_long': query.context, 'context': format_fname(query.context) }) return self.render('panels/sqlalchemy.html', {'queries': data})
def content(self): if not json_available or not sqlalchemy_available: msg = ['Missing required libraries:', '<ul>'] if not json_available: msg.append('<li>simplejson</li>') if not sqlalchemy_available: msg.append('<li>Flask-SQLAlchemy</li>') msg.append('</ul>') return '\n'.join(msg) queries = get_debug_queries() data = [] for query in queries: is_select = query.statement.strip().lower().startswith('select') _params = '' try: _params = json.dumps(query.parameters) except TypeError: pass # object not JSON serializable hash = hashlib.sha1(current_app.config['SECRET_KEY'] + query.statement + _params).hexdigest() data.append({ 'duration': query.duration, 'sql': format_sql(query.statement, query.parameters), 'raw_sql': query.statement, 'hash': hash, 'params': _params, 'is_select': is_select, 'context_long': query.context, 'context': format_fname(query.context) }) return self.render('panels/sqlalchemy.html', {'queries': data})
def get(self): self.response.headers["Content-Type"] = "application/json" list_request_ids = [] request_ids = self.request.get("request_ids") if request_ids: list_request_ids = request_ids.split(",") list_request_stats = [] for request_id in list_request_ids: request_stats = RequestStats.get(request_id) if request_stats and not request_stats.disabled: dict_request_stats = {} for property in RequestStats.serialized_properties: dict_request_stats[property] = request_stats.__getattribute__(property) list_request_stats.append(dict_request_stats) # Don't show temporary redirect profiles more than once automatically, as they are # tied to URL params and may be copied around easily. if request_stats.temporary_redirect: request_stats.disabled = True request_stats.store() self.response.out.write(json.dumps(list_request_stats))
def request(self, host, requests): server = 'http://%s/jsonrpc' % host data = [] for req in requests: method, kwargs = req data.append({ 'method': method, 'params': kwargs, 'jsonrpc': '2.0', 'id': method, }) data = json.dumps(data) headers = { 'Content-Type': 'application/json', } if self.conf('password'): base64string = base64.encodestring('%s:%s' % (self.conf('username'), self.conf('password'))).replace('\n', '') headers['Authorization'] = 'Basic %s' % base64string try: log.debug('Sending request to %s: %s', (host, data)) rdata = self.urlopen(server, headers = headers, params = data, multipart = True) response = json.loads(rdata) log.debug('Returned from request %s: %s', (host, response)) return response except: log.error('Failed sending request to XBMC: %s', traceback.format_exc()) return []
def parseMetadata(meta, jsonsafe=True): ''' Return a dict of section headings like 'Video stream' or 'Audio stream'. Each key will have a list of dicts. This supports multiple video/audio/subtitle/whatever streams per stream type. Each element in the list of streams will he a dict with keys like 'Image height' and 'Compression'...anything that hachoir is able to extract. An example output: {'Audio stream': [{u'Channel': u'6', u'Compression': u'A_AC3', u'Sample rate': u'48.0 kHz'}], u'Common': [{u'Creation date': u'2008-03-20 09:09:43', u'Duration': u'1 hour 40 min 6 sec', u'Endianness': u'Big endian', u'MIME type': u'video/x-matroska', u'Producer': u'libebml v0.7.7 + libmatroska v0.8.1'}], 'Video stream': [{u'Compression': u'V_MPEG4/ISO/AVC', u'Image height': u'688 pixels', u'Image width': u'1280 pixels', u'Language': u'English'}]} ''' if not meta: return sections = {} what = [] for line in meta: #if line doesn't start with "- " it is a section heading if line[:2] != "- ": section = line.strip(":").lower() #lets collapse multiple stream headings into one... search = re.search(r'#\d+\Z', section) if search: section = re.sub(search.group(), '', section).strip() if section not in sections: sections[section] = [dict()] else: sections[section].append(dict()) else: #This isn't a section heading, so we put it in the last section heading we found. #meta always starts out with a section heading so 'section' will always be defined i = line.find(":") key = line[2:i].lower() value = _parseValue(section, key, line[i+2:]) if value is None: value = line[i+2:] if jsonsafe: try: v = json.dumps(value) except TypeError: value = str(value) sections[section][-1][key] = value return sections
def error_response(self): """ Return a basic application/json response with status code 422 to inform the consumer of validation errors in the form request. """ errors = dict([(e.field_name, e.reason) for e in self.errors]) # TODO what about multiple errors per field content = json.dumps(dict(message="Validation error", errors=errors)) return make_response(content, 422, _error_response_headers)
def test_addresses_put_not_valid_data(url, client): uid = json.loads(login(client).data)['uid'] address_data = first_address.copy() del address_data['city'] resp = client.put(url, data=json.dumps(address_data), content_type='application/json') assert resp.status_code == 404 logout(client, uid)
def unauthorized_access(error): return Response( response=json.dumps(dict(error="Unauthorized Access", statusCode=error.code)), status=error.code, headers={}, mimetype="application/json", content_type="application/json", )
def page_not_found(error): return Response( response=json.dumps(dict(error="404 Page Not Found", statusCode=error.code)), status=error.code, headers={}, mimetype="application/json", content_type="application/json", )
def get(self): page_num = int(request.args.get('page', 1)) per_page = int(request.args.get('per_page', self.per_page)) per_page = min(per_page, self.per_page) # Upper limit self.page = self.query().paginate(page_num, per_page=per_page) content = json.dumps(dict( _embedded={request.url_rule.endpoint: self.embedded()}, _links=self.links(), **self.json)) return content, 200, {'Content-Type': self.content_type}
def parseMetadata(meta, jsonsafe=True): ''' Return a dict of section headings like 'Video stream' or 'Audio stream'. Each key will have a list of dicts. This supports multiple video/audio/subtitle/whatever streams per stream type. Each element in the list of streams will he a dict with keys like 'Image height' and 'Compression'...anything that hachoir is able to extract. An example output: {'Audio stream': [{u'Channel': u'6', u'Compression': u'A_AC3', u'Sample rate': u'48.0 kHz'}], u'Common': [{u'Creation date': u'2008-03-20 09:09:43', u'Duration': u'1 hour 40 min 6 sec', u'Endianness': u'Big endian', u'MIME type': u'video/x-matroska', u'Producer': u'libebml v0.7.7 + libmatroska v0.8.1'}], 'Video stream': [{u'Compression': u'V_MPEG4/ISO/AVC', u'Image height': u'688 pixels', u'Image width': u'1280 pixels', u'Language': u'English'}]} ''' if not meta: return sections = {} what = [] for line in meta: #if line doesn't start with "- " it is a section heading if line[:2] != "- ": section = line.strip(":").lower() #lets collapse multiple stream headings into one... search = re.search(r'#\d+\Z', section) if search: section = re.sub(search.group(), '', section).strip() if section not in sections: sections[section] = [dict()] else: sections[section].append(dict()) else: #This isn't a section heading, so we put it in the last section heading we found. #meta always starts out with a section heading so 'section' will always be defined i = line.find(":") key = line[2:i].lower() value = _parseValue(section, key, line[i + 2:]) if value is None: value = line[i + 2:] if jsonsafe: try: v = json.dumps(value) except TypeError: value = str(value) sections[section][-1][key] = value return sections
def test_addresses_put_201(url, client): uid = json.loads(login(client).data)['uid'] resp = client.put(url, data=json.dumps(first_address), content_type='application/json') response_data = json.loads(resp.data) assert 'id' in response_data assert response_data['city'] == first_address['city'] assert resp.status_code == 201 logout(client, uid)
def find_one_from_mongodb(collection, criteria): """ Return the result matching the criteria. Note that the objectID is excluded from the result JSON. """ result = collection.find_one(criteria, {'_id': 0}) if result is None: return utility.get_response_for_code(utility.ERROR_NOTFOUND) response = make_response(json.dumps(result)) response.headers['Content-Type'] = 'application/json' return response
def jsonify(*args, **kwargs): status = 200 if __debug__: _assert_have_json() if "status" in kwargs: status = kwargs.pop("status", 200) return current_app.response_class( json.dumps(dict(*args, **kwargs), indent=None if request.is_xhr else 2, cls=CustomEncoder), status=status, mimetype="application/json", )
def response_ok(data=None,message=None,force_modal=False): if message is not None: status=2 else: status=1 return Response(json.dumps({ 'status':status, 'data':data, 'message':message, 'call':True, 'force_modal':force_modal }))
def test_product_create(url, client): data = first_product.copy() login(client) resp = client.post(url, content_type='application/json') assert resp.status_code == 400 resp = client.post(url, data=json.dumps(data), content_type='application/json') assert resp.status_code == 201 assert 'slug' in json.loads(resp.data)
def response_redirect(redirect_to=None,in_modal=False,remember_modal=False,redirect_on_close=None): out_dict={ 'status':5, 'redirect_to':redirect_to, 'call':False, 'in_modal':in_modal, 'remember_modal':remember_modal } if redirect_on_close: out_dict['redirect_on_close']=redirect_on_close return Response(json.dumps(out_dict))
def test_address_creation_failed_no_data(url, client): data = first_address.copy() del data['type'], data['city'], data['street'] uid = json.loads(login(client).data)['uid'] resp = client.post(url, data=json.dumps(data), content_type='application/json') assert 'type' in json.loads(resp.data) assert 'city' in json.loads(resp.data) assert 'street' in json.loads(resp.data) assert resp.status_code == 400 logout(client, uid)
def response_ok(data=None, message=None, force_modal=False): if message is not None: status = 2 else: status = 1 return Response( json.dumps({ 'status': status, 'data': data, 'message': message, 'call': True, 'force_modal': force_modal }))
def method_not_allowed(error): return Response( response=json.dumps( dict( error="405 Method Not Allowed", message="The method {0} is not allowed for the requested URL".format(request.method), statusCode=error.code, ) ), status=error.code, headers={}, mimetype="application/json", content_type="application/json", )
def get_productswithid(): """ Gets the array of product infos with the product ids """ try: product_idlist = json.loads(request.data) except ValueError as e: return utility.get_response_for_code(utility.ERROR_BADINPUT) collection = mongoclient_manager.getdb('joytube_infodb').products resultlist = find_all_from_mongodb(collection, {"product_id": { "$in": product_idlist }}) if len(resultlist) == 0: return utility.get_response_for_code(utility.ERROR_NOTFOUND) response = make_response(json.dumps(resultlist)) response.headers['Content-Type'] = 'application/json' return response
def people(): """Get list of people user has shared with this app.""" credentials = session.get('credentials') # Only fetch a list of people for connected users. if credentials is None: response = make_response(json.dumps('Current user not connected.'), 401) response.headers['Content-Type'] = 'application/json' return response try: # Create a new authorized API client. http = httplib2.Http() http = credentials.authorize(http) # Get a list of people that this user has shared with this app. google_request = SERVICE.people().list(userId='me', collection='visible') result = google_request.execute(http=http) response = make_response(json.dumps(result), 200) response.headers['Content-Type'] = 'application/json' return response except AccessTokenRefreshError: response = make_response(json.dumps('Failed to refresh access token.'), 500) response.headers['Content-Type'] = 'application/json' return response
def response_request_confirmation(message=None,confirmation_url=None,post=None): """ Confirmation is always must be post @param message: @param confirmation_url: @return: """ return Response(json.dumps({ 'status':4, 'message':message, 'confirmation_url':confirmation_url, 'call':False, "post":True }))
def response_redirect(redirect_to=None, in_modal=False, remember_modal=False, redirect_on_close=None): out_dict = { 'status': 5, 'redirect_to': redirect_to, 'call': False, 'in_modal': in_modal, 'remember_modal': remember_modal } if redirect_on_close: out_dict['redirect_on_close'] = redirect_on_close return Response(json.dumps(out_dict))
def response_request_confirmation(message=None, confirmation_url=None, post=None): """ Confirmation is always must be post @param message: @param confirmation_url: @return: """ return Response( json.dumps({ 'status': 4, 'message': message, 'confirmation_url': confirmation_url, 'call': False, "post": True }))
def json_helper(array, name): firstEl = True ret = "" for elQry in array: el = elQry.jsond() if not firstEl: ret = ret + ", " else: firstEl = False ret = ret + str(el["id"]) + " : { 'key_id':" + str(el["id"]) for prop, val in el.items(): if type(val) is str or type(val) is datastore_types.Text: val = reduce(lambda s1, s2: s1 + s2, re.split("\r+", str(val))) val = json.dumps(val) ret = ret + ", '" + str(prop) + "'" + ": " + val pass ret = ret + "}" return "var " + name + " = {" + ret + "};" pass
def json_helper(array, name): firstEl = True ret = '' for elQry in array: el = elQry.jsond() if not firstEl: ret = ret + ', ' else: firstEl = False ret = ret + str(el['id']) + ' : { \'key_id\':' + str(el['id']) for prop, val in el.items(): if type(val) is str or type(val) is datastore_types.Text: val = reduce(lambda s1, s2: s1 + s2, re.split('\r+', str(val))) val = json.dumps(val) ret = ret + ', \'' + str(prop) + '\'' + ': ' + val pass ret = ret + '}' return 'var ' + name + ' = {' + ret + '};' pass
def content(self): if not json_available or not sqlalchemy_available: msg = ["Missing required libraries:", "<ul>"] if not json_available: msg.append("<li>simplejson</li>") if not sqlalchemy_available: msg.append("<li>Flask-SQLAlchemy</li>") msg.append("</ul>") return "\n".join(msg) queries = get_debug_queries() data = [] for query in queries: is_select = query.statement.strip().lower().startswith("select") _params = "" try: _params = json.dumps(query.parameters) except TypeError: pass # object not JSON serializable hash = hashlib.sha1(current_app.config["SECRET_KEY"] + query.statement + _params).hexdigest() bind = "" if hasattr(query, "bind") and query.bind is not None: bind = query.bind data.append( { "duration": query.duration, "sql": format_sql(query.statement, query.parameters), "raw_sql": query.statement, "hash": hash, "params": _params, "is_select": is_select, "context_long": query.context, "context": format_fname(query.context), "bind": bind, } ) return self.render("panels/sqlalchemy.html", {"queries": data})
def request(self, host, requests): server = 'http://%s/jsonrpc' % host data = [] for req in requests: method, kwargs = req data.append({ 'method': method, 'params': kwargs, 'jsonrpc': '2.0', 'id': method, }) data = json.dumps(data) headers = { 'Content-Type': 'application/json', } if self.conf('password'): base64string = base64.encodestring( '%s:%s' % (self.conf('username'), self.conf('password'))).replace( '\n', '') headers['Authorization'] = 'Basic %s' % base64string try: log.debug('Sending request to %s: %s', (host, data)) rdata = self.urlopen(server, headers=headers, params=data, multipart=True) response = json.loads(rdata) log.debug('Returned from request %s: %s', (host, response)) return response except: log.error('Failed sending request to XBMC: %s', traceback.format_exc()) return []
def get_videoinfo(video_id): """ - Gets the combined JSON of the products, and objects (including ROIs) for the associated video. - Then all objects data (from 'objects' collection) associated with those ROIs - Then all products data (from 'products' collection) associated with those ROIs - Combine ROIs + objects + products data, return to client """ rois_data = get_roiswithvideoid(video_id) # Get all object data (description, URL...) appeared in rois_data object_idlist = [x['object_id'] for x in rois_data] collection = mongoclient_manager.getdb('joytube_infodb').objects objects_data = find_all_from_mongodb(collection, {"object_id": { "$in": object_idlist }}) # Collect the array of product IDs associated. product_idlist = [y['product_id'] for y in rois_data] # Test: http://128.199.90.136:4567/info/video/:HaKinn-Bhutan/productobjs collection = mongoclient_manager.getdb('joytube_infodb').products products_data = find_all_from_mongodb(collection, {"product_id": { "$in": product_idlist }}) # In client, need to get use the same name: products_json, objects_json, rois_json res = {'rois_json': rois_data, 'objects_json': objects_data, 'products_json': products_data} response = make_response(json.dumps(res)) response.headers['Content-Type'] = 'application/json' return response
def json_dumps(data): try: return json.dumps(data, indent=2, cls=CustomEncoder) except ValueError as e: current_app.logger.debug("%s: %s", e.message, data) raise e
'pulse code modulation': 'PCM', 'pcm': 'PCM', 'windows media audio': 'WMA', 'windows media video': 'WMV', 's_text/ascii': 'ASCII', 's_text/utf8': 'UTF8', 's_text/ssa': 'SSA', 's_text/ass': 'ASS' } for codec in codecs: if codec in value.lower(): return codecs[codec] def _parseBitRate(value): try: bitrate = float(value.split()[0]) except: return None if 'kbit' in value.lower(): multi = 1000 elif 'mbit' in value.lower(): multi = 1000 * 1000 else: return None return bitrate * multi print json.dumps(parseMetadata(getMetadata(sys.argv[1])))
def response_error(error): return Response(json.dumps({'status': 0, 'message': error, 'call': False}))
'pcm': 'PCM', 'windows media audio': 'WMA', 'windows media video': 'WMV', 's_text/ascii': 'ASCII', 's_text/utf8': 'UTF8', 's_text/ssa': 'SSA', 's_text/ass': 'ASS' } for codec in codecs: if codec in value.lower(): return codecs[codec] def _parseBitRate(value): try: bitrate = float(value.split()[0]) except: return None if 'kbit' in value.lower(): multi = 1000 elif 'mbit' in value.lower(): multi = 1000 * 1000 else: return None return bitrate * multi print json.dumps(parseMetadata(getMetadata(sys.argv[1])))
def padded_jsonify(callback, *args, **kwargs): content = str(callback) + '(' + json.dumps(dict(*args, **kwargs)) + ')' return getattr(current_app, 'response_class')(content, mimetype='text/javascript')
def jsonify(mimetype, *args, **kwargs): content = json.dumps(dict(*args, **kwargs)) return getattr(current_app, 'response_class')(content, mimetype=mimetype)