def _json(self, *args, **kwargs): if self.request.method == 'POST': try: self.req_params = json.decode(self.request.body) except ValueError as e: logging.info(str(e)) error_msg = ErrorReturn(self.response, error_code='') error_msg.handle_400() return elif self.request.method == 'GET': try: self.req_params = self.request.GET.mixed() except Exception as e: logging.info(str(e)) error_msg = ErrorReturn(self.response, error_code='') error_msg.handle_400() return elif self.request.method == 'PUT': try: self.req_params = json.decode(self.request.body) except ValueError as e: logging.info(str(e)) self.req_params = {} return self.response.headers['content-type'] = "application/json" return handler(self, *args, **kwargs)
def test_post(self): # create widget in DB and get its id widget = copy.copy(self.json_widget) ident = model.Widget.put1(widget).key.integer_id() self.assertEqual(1, len(model.Widget.query().fetch(2))) # update widget with the same id through API widget = copy.copy(self.json_widget) widget['email_field'] = '*****@*****.**' response = self.testapp.post( '/rest/Widget/' + str(ident), params=json.encode(widget), expect_errors=True, content_type="application/json; charset=utf-8") self.assertEqual(response.status_int, 200) self.assertEqual(json.decode(response.body)['code'], 200) # get widget with the same id through API and verify that email field is correct response = self.testapp.get('/rest/Widget/' + str(ident), params=self.str_widget, expect_errors=True) self.assertEqual(response.status_int, 200) self.assertEqual(json.decode(response.body)['code'], 200) self.assertEqual( json.decode(response.body)['message']['email_field'], "*****@*****.**")
def get(self): id = self.request.get('id') try: opener = urllib2.build_opener() opener.addheaders = [('App-Token', settings.TRANSPARENCIA_TOKEN), ('Content-Type', 'application/json'), ('Accept', 'application/json')] result = opener.open(settings.uri('candidatos')+"/"+id) profile = json.decode(result.read()) result = opener.open(settings.uri('candidatos')+"/"+id+ "/bens") bens = json.decode(result.read()) profile["bens"] = bens result = opener.open(settings.uri('candidatos')+"/"+id+ "/doadores") doadores = json.decode(result.read()) profile["doadores"] = doadores result = opener.open(settings.uri('candidatos')+"/"+id+ "/candidaturas") candidaturas = json.decode(result.read()) profile["candidaturas"] = candidaturas result = opener.open(settings.uri('candidatos')+"/"+id+ "/estatisticas") estatisticas = json.decode(result.read()) profile["estatisticas"] = estatisticas except urllib2.URLError, e: profile = []
def test_post(self): # create widget in DB and get its id widget = copy.copy(self.json_widget) ident = model.Widget.put(widget).key().id() self.assertEqual(1, len(model.Widget.all().fetch(2))) # update widget with the same id through API widget = copy.copy(self.json_widget) widget['email_field'] = '*****@*****.**' response = self.testapp.post('/rest/Widget/' + str(ident), params = json.encode(widget), expect_errors=True, content_type = "application/json; charset=utf-8") self.assertEqual(response.status_int, 200) self.assertEqual(json.decode(response.body)['code'], 200) # get widget with the same id through API and verify that email field is correct response = self.testapp.get('/rest/Widget/' + str(ident), params = self.str_widget, expect_errors=True) self.assertEqual(response.status_int, 200) self.assertEqual(json.decode(response.body)['code'], 200) self.assertEqual(json.decode(response.body)['message']['email_field'], "*****@*****.**")
def post(self): game_id = self.request.path game_id = game_id.replace('/game/', '') game_id = game_id.replace('/action', '') username = str(self.request.get('player')) player = ndb.gql("SELECT * FROM Player WHERE name = '" + username + "'").fetch() player = player[0] game_status = ndb.gql("SELECT * FROM GameStatus WHERE name = '" + username + "' AND game_id = " + game_id).fetch() game_status = game_status[0] action = str(self.request.get('action')) if action == "bet": value = int(self.request.get('value')) if value > player.tokens: self.response.out.write("Bet more than the number of tokens you have") else: player.tokens -= value game_status.tokens -= value actions_array = json.decode(game_status.your_actions) actions_array.append("play") game_status.your_actions = json.encode(actions_array) player.put() game_status.put() self.response.out.write("ok") elif action == "play": dealer = ndb.gql("SELECT * FROM Dealer WHERE game_id = " + game_id).fetch() dealer = dealer[0] deck = json.decode(dealer.deck) card1 = choice(deck) deck.remove(card1) card2 = choice(deck) deck.remove(card2) player_cards = [card1, card2] game_status.your_cards_visible = json.encode(player_cards) game_status.put() check_games = ndb.gql("SELECT * FROM GameStatus WHERE game_id = " + game_id).fetch() check_num = 1 for game_s in check_games: if len(json.decode(game_s.your_cards_visible)) != 2: check_num = 0 if check_num == 1: d_card1 = choice(deck) deck.remove(d_card1) d_card2 = choice(deck) deck.remove(d_card2) d_visible = json.decode(dealer.dealer_card_v) d_visible.append(d_card1) dealer.dealer_card_v = json.encode(d_visible) dealer.dealer_card_n = d_card2 dealer.deck = json.encode(deck) dealer.put() self.response.out.write("ok") # elif action == "draw": # # elif action == "fold": # # elif action == "doubledown": else: self.response.out.write("error")
def test_get(self): # create widget in DB and get its id widget = copy.copy(self.json_widget) ident = model.Widget.put(widget).key().id() self.assertEqual(1, len(model.Widget.all().fetch(2))) # get widget with the same id through API and verify that email field is correct response = self.testapp.get('/rest/Widget/' + str(ident), params = self.str_widget, expect_errors=True) self.assertEqual(response.status_int, 200) self.assertEqual(json.decode(response.body)['code'], 200) self.assertEqual(json.decode(response.body)['response']['email_field'], "*****@*****.**")
def test_get(self): # create widget in DB and get its id widget = copy.copy(self.json_widget) ident = model.Widget.put(widget).key().id() self.assertEqual(1, len(model.Widget.all().fetch(2))) # get widget with the same id through API and verify that email field is correct response = self.testapp.get('/rest/Widget/' + str(ident), params = self.str_widget, expect_errors=True) self.assertEqual(response.status_int, 200) self.assertEqual(json.decode(response.body)['code'], 200) self.assertEqual(json.decode(response.body)['message']['email_field'], "*****@*****.**")
def test_json_start_post(self): request = webapp2.Request.blank("/") request.method = "POST" request.headers["Content-Type"] = "application/json" request.body = json.encode({ 'update': 1, 'message': { u'date': 1450696897, u'text': u'/start', u'from': { u'username': u'm_messiah', u'first_name': u'Maxim', u'last_name': u'Muzafarov', u'id': 1 }, u'message_id': 1, u'chat': { u'type': u'group', u'id': -1, u'title': u'КС' } } }) response = request.get_response(app) self.assertEqual(response.status_int, 200) self.assertIn("application/json", response.headers['Content-Type']) self.assertDictEqual( json.decode(response.body), { 'method': 'sendMessage', 'text': u"Внимательно слушаю!", 'chat_id': -1, 'disable_web_page_preview': True, 'reply_to_message_id': 1, })
def send_gps(self, gps): request = webapp2.Request.blank("/") request.method = "POST" request.headers["Content-Type"] = "application/json" request.body = json.encode({ 'update': 1, 'message': { u'date': 1450696897, u'text': u'%s' % gps, u'from': { u'username': u'm_messiah', u'first_name': u'Maxim', u'last_name': u'Muzafarov', u'id': 1 }, u'message_id': 1, u'chat': { u'type': u'user', u'id': 1, u'username': u'm_messiah', u'first_name': u'Maxim', u'last_name': u'Muzafarov', } } }) response = request.get_response(app) self.assertEqual(response.status_int, 200) self.assertIn("application/json", response.headers['Content-Type']) response = json.decode(response.body) self.assertEqual('sendLocation', response['method']) return response['latitude'], response['longitude']
def test_json_text_post(self): request = webapp2.Request.blank("/") request.method = "POST" request.headers["Content-Type"] = "application/json" request.body = json.encode({ 'update': 1, 'message': { u'date': 1450696897, u'text': u'как дела?', u'from': { u'username': u'm_messiah', u'first_name': u'Maxim', u'last_name': u'Muzafarov', u'id': 1 }, u'message_id': 1, u'chat': { u'type': u'group', u'id': -1, u'title': u'КС' } } }) response = request.get_response(app) self.assertEqual(response.status_int, 200) self.assertIn("application/json", response.headers['Content-Type']) self.assertDictEqual(json.decode(response.body), {})
def post(self): nota_json = json.decode(self.request.get('nota')) nota = Nota() if 'id' in nota_json: nota = Nota.get_by_id(long(nota_json['id'])) nota.total = float(nota_json['total']) nota.nombre = nota_json['nombre'] if 'fecha_impresion' in nota_json: nota.fecha_impresion = datetime.datetime.fromtimestamp(float(nota_json['fecha_impresion'])/1000) nota.put() for orden_json in nota_json['ordenes']: orden = Orden() if 'id' in orden_json: orden = Orden.get_by_id(long(orden_json['id'])) orden.cantidad = int(orden_json['cantidad']) orden.producto = Producto.get_by_id(long(orden_json['producto']['id'])) orden.nota = nota orden.put() if 'modificadores_producto' in orden_json: for modificador_producto_json in orden_json['modificadores_producto']: if 'id' in modificador_producto_json: orden_modificador_producto = OrdenModificadorProducto.get_by_id(long(modificador_producto_json['id'])) else: orden_modificador_producto = OrdenModificadorProducto() orden_modificador_producto.orden = orden orden_modificador_producto.modificador_producto = ModificadorProducto.get_by_id(long(modificador_producto_json['modificador_producto']['id'])) orden_modificador_producto.put() self.render_json(nota.to_dict())
def post(self, email): # Http 쏘기 위한 공옹 루틴 self.response.headers.add_header("Access-Control-Allow-Origin", "*") self.response.content_type = "application/json" user = db.UserEntity.get_by_id(email) if user == None: res_data = {"result": False, "reason": "email not exist"} self.response.write(json.encode(res_data)) return # 패스워드 틀림 req_data = json.decode(cgi.escape(self.request.body)) if user.password != req_data["password"]: res_data = {"result": False, "reason": "password not match"} self.response.write(json.encode(res_data)) return # 결과 리턴 token = secret.get_jwt(user.auth_type, user.email, user.name) res_data = { "result": True, "token": token, "isWorking": user.is_working, "totalWorkingSeconds": (datetime.now() - user.work_start_date_time).total_seconds(), } if user.intro_text != None: res_data["introText"] = user.intro_text if user.avatar_photo_blob_key != None: userPhoto = db.BlobEntity.get_by_id(str(user.avatar_photo_blob_key)) if userPhoto != None: res_data["avatarPhotoUrl"] = userPhoto.blob_url self.response.write(json.encode(res_data))
def post(self, email): # Http 쏘기 위한 공옹 루틴 self.response.headers.add_header("Access-Control-Allow-Origin", "*") self.response.content_type = "application/json" user = db.UserEntity.get_by_id(email) if user == None: res_data = {"result": False, "reason": "email not exist"} self.response.write(json.encode(res_data)) return req_data = json.decode(cgi.escape(self.request.body)) photo = db.BlobEntity.get_by_id(req_data["avatarPhotoBlobId"]) if photo == None: res_data = {"result": False, "reason": "photo blob not exist"} self.response.write(json.encode(res_data)) return # 이전 사진은 삭제 prev_photo = db.BlobEntity.get_by_id(str(user.avatar_photo_blob_key)) if prev_photo != None: blobstore.delete(prev_photo.blob_key) prev_photo.key.delete() user.avatar_photo_blob_key = photo.blob_key user.put() res_data = {"result": True, "avatarPhotoUrl": photo.blob_url} self.response.write(json.encode(res_data))
def json_decode(self, *args, **kwargs): try: self.request.json = json.decode(self.request.body) except ValueError: self.abort(400, 'Invalid client json') else: return handler(self, *args, **kwargs)
def post(self): values = json.decode(self.request.body) courseCodeGet = values['code'] dateGet = values['date'] startTimeGet = values['startTime'] endTimeGet = values['endTime'] periodTypeGet = values['type'] rooms = values['rooms'] courseList = Course.query_by_code(courseCodeGet).fetch(1) course = None for c in courseList: course = c period = Period(parent=course.key) # Setup the period period.date = datetime.datetime.strptime(dateGet, '%d.%m.%Y').date() period.startTime = datetime.datetime.strptime(startTimeGet, '%H:%M').time() period.endTime = datetime.datetime.strptime(endTimeGet, '%H:%M').time() period.periodType = periodTypeGet i = 0 for r in rooms: period.rooms.append(rooms[str(i)]) i = i + 1 period.put() course.periodsKeys.append(period.key) course.put()
def post(self): # remote_addr shows up as "::1" when calling from localhost # or is it when using the simulated version of the # GAE environment? not sure. # print("remote ip is %s" % self.request.remote_addr) raw = self.request.body try: obj = json.decode(raw) except ValueError: self.response.out.write("invalid json") return ami_launch = AMILaunch(parent=get_parent()) ami_launch.is_bioc_account = obj['accountId'] == "555219204010" if not ami_launch.is_bioc_account: ami_launch.account_hash = hashlib.md5( obj['accountId'].encode()).hexdigest() ami_launch.ami_id = obj['imageId'] ami_launch.instance_type = obj['instanceType'] ami_launch.region = obj['region'] ami_launch.availability_zone = obj['availabilityZone'] is_aws_ip("foo") ami_launch.bioc_version = get_bioc_version(obj['imageId']) ami_info = get_ami_info(obj['imageId']) if ami_info is not None: ami_launch.ami_name = ami_info['name'] ami_launch.ami_description = ami_info['description'] ami_launch.put() self.response.out.write("thanx\n")
def post(self): json_form = json.decode(self.request.body) new_todo = Todo(id=json_form["id"], title=json_form["title"], completed=json_form["completed"]) new_todo.put() self.response.headers["Content-Type"] = "application/json" result = {"result": "success"} self.response.write(json.encode(result))
def AddWordnikDefinition(self): entity = self word = self.word if entity.partsOfSpeech and entity.definitions: raise ndb.Return(True) url = "http://api.wordnik.com:80/v4/word.json/{}/definitions?limit=200&includeRelated=false&useCanonical=false&includeTags=false&api_key={}".format( word, _WORDNIK_API_KEY) context = ndb.get_context() result = yield context.urlfetch(url, deadline=1, follow_redirects=False) if result.status_code != 200: raise ndb.Return(False) items = json.decode(result.content) if not items: raise ndb.Return(False) partsOfSpeech = set() definitions = [] for item in items: if "partOfSpeech" in item: partsOfSpeech.add(item["partOfSpeech"]) if "text" in item: definitions.append(item["text"]) entity.partsOfSpeech = list( set(entity.partsOfSpeech).union(partsOfSpeech)) entity.definitions = list(set(entity.definitions).union(definitions)) yield entity.put_async() raise ndb.Return(True)
def post(self): email_notification = EmailNotification() logging.debug(self.request.body) body = json.decode(self.request.body) email_notification.recipient_email = body["recipient_email"] logging.debug("recipient_email: %s", email_notification.recipient_email) email_notification.sender_name = body["sender_name"] logging.debug("sender_name: %s", email_notification.sender_name) email_notification.put() resp = { "recipient_email": email_notification.recipient_email, "sender_name": email_notification.sender_name } if not mail.is_email_valid(email_notification.recipient_email): self.response.write('Bad Email') else: sender = "%s <*****@*****.**>" % email_notification.sender_name subject, body, html = randMessage(email_notification.sender_name) logging.debug('Sending Email') sendEmailWithSendGrid(sender, email_notification.recipient_email, subject, body, html) # sendEmailWithGAEMailAPI(sender, email_notification.recipient_email, subject, body, html) logging.debug('Sending Response') self.response.write(json.encode(resp))
def create(user_key, name=""): #Find the user to add the key to user = User.find_by_key(user_key) if (user == None): raise Exception("Invalid key") if (name == ""): name = "Untilted" # Set the list to empty usernames = [user.username] pending_usernames = [] # Add the new item list to the database group = Group(name=name, usernames=JSON.encode(usernames), pending_usernames=JSON.encode(pending_usernames), version=0,photo="",photo_version=0) group_key = (group.put()).urlsafe() user_groups = JSON.decode(user.groups) user_groups.append(group_key) user.groups = JSON.encode(user_groups) user.increment_version() user.put() return group_key
def get(self): logging.info("<<<<<<<< GET, in TestHandler >>>>>>>>") url = os.environ['FIREBASE_DB'] + "/email.json" result = urlfetch.fetch(url) # logging.info("ZZqqZZZ 3 " + result.content) emailDict = json.decode(result.content) emailKeys = emailDict.keys() for a in emailKeys: if emailDict[a]['pending'] == True: logging.info("hello yo 3, " + emailDict[a]['type']) yotype = emailDict[a]['type'] yoarbmonthid = emailDict[a]['arbMonthID'] yoarbuid = emailDict[a]['arbuid'] yostamp = emailDict[a]['stamp'] yoparams = { 'arbMonthID': yoarbmonthid, 'arbuid': yoarbuid, 'stamp': yostamp, 'type': yotype } taskurl = "/writemail" taskqueue.add(url=taskurl, params=yoparams) params = '{"pending": false}' url2 = os.environ['FIREBASE_DB'] + "/email/" + a + "/.json" result = urlfetch.fetch(url=url2, payload=params, method=urlfetch.PATCH) logging.info("post result 2 = " + str(result.status_code)) else: logging.info("not a pending email")
def validate(self): request = webapp2.get_request() data = json.decode(request.body) if not isinstance(data, dict): webapp2.abort(403, detail='not a dict') for f in self.fields: if not f.id in self.validations: continue try: value = data[f.id].strip() except KeyError: value = '' self.field_values[f.id] = value for val in self.validations[f.id]: val.input = f.id if not val.validate(self): webapp2.abort(403, detail='validation error, id: %s name: %s value: %s' % (f.id, f.name, value)) return self.field_values
def _get_result(self, URL, MAX_RETRIES=5): result = None retries = 0 while not result and retries <= MAX_RETRIES: result = _try_to_get_result(URL, self.token) retries += 1 return json.decode(result)
def _apicall(self, url, params=(), cr="GET", ch=None): """ Call an API endpoint. url: The URL of the entity to post to. params: a tuple of (name, value) tuples of parameters cr: The request type to be made. If parameters are passed, this will be ignored and treated as POST Returns a dictionary object populated with the json returned. """ pars = urllib.urlencode(dict(params)) if params is not () and cr != "DELETE" and cr != "PUT": cr = "POST" if (ch): ch.update(self.auth_header) r = urlfetch.fetch(url, method=cr, payload=pars, headers=ch, deadline=60, validate_certificate=False) else: r = urlfetch.fetch(url, method=cr, payload=pars, headers=self.auth_header, deadline=60, validate_certificate=False) if ch is not None: return r.content return json.decode(r.content)
def post(self): # remote_addr shows up as "::1" when calling from localhost # or is it when using the simulated version of the # GAE environment? not sure. # print("remote ip is %s" % self.request.remote_addr) raw = self.request.body try: obj = json.decode(raw) except ValueError: self.response.out.write("invalid json") return ami_launch = AMILaunch(parent=get_parent()) ami_launch.is_bioc_account = obj['accountId'] == "555219204010" if not ami_launch.is_bioc_account: ami_launch.account_hash = hashlib.md5(obj['accountId'].encode()).hexdigest() ami_launch.ami_id = obj['imageId'] ami_launch.instance_type = obj['instanceType'] ami_launch.region = obj['region'] ami_launch.availability_zone = obj['availabilityZone'] is_aws_ip("foo") ami_launch.bioc_version = get_bioc_version(obj['imageId']) ami_info = get_ami_info(obj['imageId']) if ami_info is not None: ami_launch.ami_name = ami_info['name'] ami_launch.ami_description = ami_info['description'] ami_launch.put() self.response.out.write("thanx\n")
def test(self): request = webapp2.Request.blank('/locations') request.body = '{"latitude": 40.689068, "longitude": 74.044625, "message": u"Hollå!", "age": 1 }' request.method = 'POST' response = request.get_response(app) assert response.status_int == 200 assert json.decode(response.body) == {}
def test_config_replacement(self): d = 25000 memcache.set('already_clicked', d * 1000) memcache.set('clicks_total', d * 1000 + 333333) memcache.set('already_donated', d) memcache.set('eur_goal', 50000) memcache.set('eur_increment', EUR_INCREMENT) self._create_config( '{"firstvisit":"center","secondvisit":"top","default_locale":"en","strings":{' + '"en":{"heading":"Thanks!","subheading":"Every click is worth %increment%","about":"More about the <strong>dotHIV</strong> initiative","activated":"Already %donated% contributed:","money":"%unlocked%","clickcount":"%clicks% clicks"},' + '"de":{"heading":"Danke!","subheading":"Jeder Klick hilft mit %increment%","about":"Mehr über die <strong>dotHIV</strong> Initiative","activated":"Bereits %donated% gespendet:","money":"%unlocked%","clickcount":"%clicks% Klicks"}}}' ) uri = '/c?domain=' + self.domain + '&from=inside' request = Request.blank(uri, headers=[('Accept-Language', 'de,en-US;q=0.5,en;q=0.6')]) request.method = 'POST' response = request.get_response(application) config = json.decode(response.body) self.assertEqual("Bereits 25.000 € gespendet:", str(config['activated'])) if EUR_INCREMENT < 0.01: # 0.001 self.assertEqual("25.333,33 €", str(config['money'])) self.assertEqual("Jeder Klick hilft mit 0,1 ct", str(config['subheading'])) self.assertEqual(round(25333.33 / 50000, 3), round(config['percent'], 3)) else: # 0.01 self.assertEqual("28.333,33 €", str(config['money'])) self.assertEqual("Jeder Klick hilft mit 1 ct", str(config['subheading'])) self.assertEqual(round(28333.33 / 50000, 3), round(config['percent'], 3)) self.assertEqual("25.333.333 Klicks", str(config['clickcount']))
def _put_candidate(candidato): try: opener = urllib2.build_opener() opener.addheaders = [('App-Token', settings.TRANSPARENCIA_TOKEN), ('Content-Type', 'application/json'), ('Accept', 'application/json')] uri = settings.uri('candidato_stats').format( candidato_id=candidato['id']) result = opener.open(uri) candidato_stats = json.decode(result.read()) if candidato_stats: candidato_stats = candidato_stats[0] else: candidato_stats = {} Candidato(candidato_id=int(candidato['id']), instrucao=candidato['instrucao'], reeleicao=candidato['reeleicao'], cargo=candidato['cargo'], estado=candidato['estado'], nome=candidato['nome'], foto=candidato['foto'], faltas_plenario=float(candidato_stats.get('faltas_plen', 0)), faltas_comissoes=float(candidato_stats.get('faltas_com', 0))).put() except urllib2.URLError, e: print '>>>>>>>>>>>>>>>>>>>> %s' % str(e) pass
def test_json_start_post(self): request = webapp2.Request.blank("/") request.method = "POST" request.headers["Content-Type"] = "application/json" request.body = json.encode({ 'update': 1, 'message': { u'date': 1450696897, u'text': u'/start', u'from': { u'username': u'm_messiah', u'first_name': u'Maxim', u'last_name': u'Muzafarov', u'id': 3798371 }, u'message_id': 1, u'chat': { u'type': u'group', u'id': -11812986, u'title': u'КС' } } }) response = request.get_response(app) self.assertEqual(response.status_int, 200) self.assertIn("application/json", response.headers['Content-Type']) self.assertDictEqual( json.decode(response.body), { 'method': 'sendMessage', 'text': u"Привет! Я буду исправлять твои ошибки в режиме inline (в любое время можно ввести `@spell_bot сообщение`, и я предложу исправления)", 'chat_id': -11812986, } )
def expand_bitly_url(bitly_hash): import urllib2 url = 'http://bit.ly/' + bitly_hash expander_params = { "login": "******", "apiKey": "R_3a5d98588cb05423c22de21292cd98d6", "shortUrl": url, "format": "json" } form_data = urllib.urlencode(expander_params) post_url = 'http://api.bitly.com/v3/expand?' + form_data # result = urlfetch.fetch(url=post_url, method=urlfetch.GET) result = urllib2.urlopen(post_url).read() decoded_result = json.decode(result) if 'expand' not in decoded_result[ 'data'] or 'long_url' not in decoded_result['data']['expand'][0]: return None return cgi.parse_qs( decoded_result['data']['expand'][0]['long_url'].split('?')[1])
def get_bitly_url(str_query): import urllib2 url = url_for('frontend/link/share', _full=True) + '?' + str_query if get_app().debug: url = "http://puertogeo.appspot.com" + url_for( 'frontend/link/share') + '?' + str_query shortener_params = { "login": "******", "apiKey": "R_3a5d98588cb05423c22de21292cd98d6", "longurl": url, "format": "json" } form_data = urllib.urlencode(shortener_params) post_url = 'http://api.bitly.com/v3/shorten?' + form_data result = urllib2.urlopen(post_url).read() bitlydata = json.decode(result) bitly_hash = "" if 'url' in bitlydata['data']: bitly_hash = bitlydata['data']['hash'] return url_for('frontend/link/map', _full=True, bitly_hash=bitly_hash)
def _make_request(url, method, body=None): http = httplib2.Http(timeout=_TIMEOUT) attempt = 0 while attempt < _RETRIES: attempt += 1 url = _api_url_base + url logging.debug('%s: %s', method, url) response, content = http.request(url, method=method, headers=_headers, body=body) # This is pretty dirty. But PUT entry-creation reqs give a status # of 201, and basically all 20x statuses are successes, so... if not response['status'].startswith('20'): # Fail. Retry. logging.debug(response) logging.debug(content) continue return json.decode(content) # If we got to here, then the request failed repeatedly. # Hack: For certain email addresses (such as those with "spam" in the name # part), MailChimp will return an error like: # `"status":400, "detail":" is already a list member. Use PATCH to update existing members."` # That condition will be permanent and unrecoverable if we treat it as an # error (or if we try to PATCH). So we're going to take the dirty route # and just proceed as if the request succeeded. This will result in the # spreadsheet getting updated for this member, allowing us to skip it in # the future. error_info = json.decode(content) if error_info.get('status') == 400 and error_info.get( 'detail', '').find('is already a list member') > 0: logging.warning( '_make_request: got 400 "is already a member" error: %s : %s : %s', method, url, body) # Pretend success return webapp2.abort(int(response['status']), detail=content)
def parse_json(content, info_key): result = json.decode(content) if result['ok'] != 1: raise Exception('JSON Not "OK" (%s)' % (content)) if info_key: return result[info_key] else: return result
def post(self): p = self.request.body logging.info('Set list: ' + p) data = json.decode(p) uid = data['uid'] name = data['name'] songs = data['songs'] self.set_list(uid, name, songs)
def test_put_unauth(self): response = self.testapp.put('/rest/Widgets', params = self.str_widget, expect_errors=True, content_type = "application/json; charset=utf-8") self.assertEqual(response.status_int, 401) self.assertEqual(json.decode(response.body)['code'], 401)
def post(self): self.set_response_data() user = self.get_user() try: location = convert.location(**json.decode(self.request.body)) except Exception, e: print str(e) self.abort(400)
def post(self): """ angularjs sends data as a json string in the body of the post this turns that string in to a dict""" request_body_dict = json.decode(self.request.body) """ load up the variables, missing a key will cause an error""" queryString = request_body_dict.get('queryString') offset = request_body_dict.get('offset') limit = request_body_dict.get('limit') # offset = 0 options = search.QueryOptions(limit=limit, offset=offset, returned_fields=[ 'doctype', 'boardtype', 'boardnumber', 'awardnumber', 'arbitrator', 'carriers', 'unions', 'parties', 'crafts', 'link', 'docdate' ], snippeted_fields=['doctext']) query = search.Query(queryString, options) ksresults = search.Index(name=_INDEX_NAME).search(query) # ksresults = search.Index(name=_INDEX_NAME).search(queryString) result_set = [] for doc in ksresults.results: temp_dict = {} for stuff in doc.fields: temp_dict[stuff.name] = stuff.value for morestuff in doc.expressions: temp_dict[morestuff.name] = morestuff.value result_set.append(temp_dict) num_of_matches = ksresults.number_found # alpha = ksresults.results.pop().doc_id # alpha = ksresults.results.pop().fields.pop().name # alpha = ksresults.results.pop().fields # alpha = str(ksresults.results) rspObj = { 'rsp': 'OK', 'msg': 'I love you Dean', 'ksresults': result_set, 'num_of_matches': num_of_matches, 'bucket': _BUCKET_NAME # 'alpha' : alpha # 'ksresults' : [{'awardnumber':'12345','carriers':'Delta, Virgin'}, 'reject'] } """ assemble and send the response """ self.response.content_type = 'application/json' self.response.write(json.encode(rspObj))
class ModelTestCase(unittest2.TestCase): fixture_widget = json.decode( '{"int_field":1,"email_field":"*****@*****.**","boolean_field":true,"date_field":"2012-02-12","text_field":"daf","id":2,"string_field":"dfa","link_field":"http://i.co"}' ) def setUp(self): # First, create an instance of the Testbed class. self.testbed = testbed.Testbed() # Then activate the testbed, which prepares the service stubs for use. self.testbed.activate() # Next, declare which service stubs you want to use. self.testbed.init_datastore_v3_stub() self.testbed.init_memcache_stub() def tearDown(self): self.testbed.deactivate() def test_create(self): widget = copy.copy(self.fixture_widget) model.Widget.put1(widget) self.assertEqual(1, len(model.Widget.query().fetch(2))) def test_read(self): widget = copy.copy(self.fixture_widget) widget['int_field'] = 123 entity = model.Widget.put1(widget) self.assertNotEqual(None, entity) entity = model.Widget.get(entity.key.integer_id()) self.assertEqual(entity.int_field, 123) def test_update(self): widget = copy.copy(self.fixture_widget) identifier = model.Widget.put1(widget).key.integer_id() widget = copy.copy(self.fixture_widget) widget['int_field'] = 234 widget['email_field'] = '*****@*****.**' widget['boolean_field'] = False entity = model.Widget.post(identifier, widget) self.assertEqual(entity.int_field, 234) self.assertEqual(entity.email_field, '*****@*****.**') self.assertEqual(entity.boolean_field, False) def test_delete(self): widget = copy.copy(self.fixture_widget) identifier = model.Widget.put1(widget).key.integer_id() self.assertEqual(model.Widget.delete1(identifier), True) self.assertEqual(0, len(model.Widget.query().fetch(2)))
def test_incorrect_text(self): request = webapp2.Request.blank("/") request.method = "POST" request.headers["Content-Type"] = "application/json" request.body = json.encode({ 'update': 1, 'inline_query': { u'query': u'стртанный, ткест', u'from': { u'username': u'm_messiah', u'first_name': u'Maxim', u'last_name': u'Muzafarov', u'id': 3798371 }, u'id': "1", u'offset': 0, } }) response = request.get_response(app) self.assertEqual(response.status_int, 200) self.assertIn("application/json", response.headers['Content-Type']) self.assertItemsEqual( json.decode(json.decode(response.body)['results']), [{ u"message_text": u"\u0441\u0442\u0440\u0442\u0430\u043d\u043d\u044b\u0439, \u0442\u043a\u0435\u0441\u0442", u"type": u"article", u"id": u"0", u"title": u"spell", u"description": u"\u0441\u0442\u0440\u0442\u0430\u043d\u043d\u044b\u0439, \u0442\u043a\u0435\u0441\u0442" }, { u'message_text': u'cnhnfyysq? nrtcn', u'title': u'qwerty', u'type': u'article', u'description': u'cnhnfyysq? nrtcn', u'id': u'1' }, { u'message_text': u'cnhnfyysq^ nrtcn', u'title': u'mac', u'type': u'article', u'description': u'cnhnfyysq^ nrtcn', u'id': u'2' }] )
class RPCTest(unittest2.TestCase): str_widget = '{"int_field":1,"email_field":"*****@*****.**","boolean_field":true,"date_field":"12-02-2012","text_field":"daf","id":2,"string_field":"dfa","link_field":"http://i.co"}' json_widget = json.decode(str_widget) faux_db_user = {'email' : '*****@*****.**', 'password_raw' : 'blah', 'pic' : 'http://www.gravatar.com/avatar/759e5b31901d7d20a106f7f8f60a9383?d=http%3A//green-algae.appspot.com/img/algae.png', 'profile' : 'mailto:[email protected]', 'username' : 'ilya' } user = None def signin_faux_user(self): ok, self.user = users.User.create_user('own:[email protected]', **self.faux_db_user) response = self.testapp.get('/email-signin?action=signin_email&email=%s&password=%s' % (self.faux_db_user['email'], self.faux_db_user['password_raw'])) self.assertEqual(response.status_int, 200) self.assertEqual(response.content_type, 'application/json') def setUp(self): # Create a WSGI application. application = webapp2.WSGIApplication(app.routes, debug = True, config = settings.app_config) application.error_handlers[404] = handlers.common.handle_404 application.error_handlers[500] = handlers.common.handle_500 # Wrap the app with WebTest's TestApp. self.testapp = webtest.TestApp(application) # First, create an instance of the Testbed class. self.testbed = testbed.Testbed() # Then activate the testbed, which prepares the service stubs for use. self.testbed.activate() # Next, declare which service stubs you want to use. self.testbed.init_datastore_v3_stub() self.testbed.init_memcache_stub() def test_mailing_list(self): response = self.testapp.get('/rpc/signup_mailing_list?email_mailinglist=%s' % urllib.quote('*****@*****.**')) self.assertEqual(response.status_int, 200) self.assertEqual(response.content_type, 'application/json') self.assertNotEqual(None, db.Query(model.EmailAddr).filter('email =', '*****@*****.**').get()) def test_update_email_noauth(self): response = self.testapp.get('/rpc/change_email_addr?email_change=%s' % urllib.quote('*****@*****.**'), expect_errors=True) self.assertEqual(response.status_int, 401) self.assertEqual(response.content_type, 'application/json') def test_update_email_auth(self): self.signin_faux_user() response = self.testapp.get('/rpc/change_email_addr?email_change=%s' % urllib.quote('*****@*****.**')) self.assertEqual(response.status_int, 200) self.assertEqual(response.content_type, 'application/json') self.assertEqual(self.user.email, '*****@*****.**')
def post(self): json_form = json.decode(self.request.body) id = json_form["id"] q = Todo.query() q = q.filter(Todo.id == id) q.fetch(1)[0].key.delete() self.response.headers["Content-Type"] = "application/json" result = {"result": "success"} self.response.write(json.encode(result))
def post(self, obj_t, identifier, *args): kvs = json.decode(self.request.body) # find model class cls = getattr(sys.modules['core.model'], obj_t) obj = utils.to_dict(cls.post(int(identifier), kvs)) return self.prep_json_response(200, message=obj)
def test_get(self): request = webapp2.Request.blank("/") response = request.get_response(app) self.assertEqual(response.status_int, 200) self.assertIn("application/json", response.headers['Content-Type']) self.assertDictEqual( json.decode(response.body), {"name": "I am Spell bot (https://telegram.me/spell_bot)", "result": "Info"})
def post(self, obj_t, identifier, *args): kvs = json.decode(self.request.body) # find model class cls = getattr(sys.modules['core.model'], obj_t) obj = utils.to_dict(cls.post(int(identifier), kvs)) return self.prep_json_response(200, message = obj)
def wrapper(self,*args,**kwargs): data = {} try: data = json.decode(self.request.body) except Exception as e: log.info(e) resp = callback(self.request,data,**kwargs) self.response.content_type = "application/json" return self.response.write(json.encode(resp))
def test_get(self): request = webapp2.Request.blank("/") response = request.get_response(app) self.assertEqual(response.status_int, 200) self.assertIn("application/json", response.headers['Content-Type']) self.assertDictEqual( json.decode(response.body), {"name": 'Hello World! I am XyE_bot (https://telegram.me/xye_bot)', "result": "Info"})
def getMovesArrayFrom(self, movesFrom, playerNum): moves = [] for strMove in self.moveData[movesFrom:] : move = json.decode(strMove) if (move["state"] == DIST_1 or move["state"] == DIST_2): move["params"] = getattr(self, "cards" + str(playerNum)) moves.append(move) return moves
def login_gplus(self): gplus = json.decode(self.request.get('gplus_object')) try: auth_user = self.auth.get_user_by_password(gplus['email'], gplus['id'], remember=True) except (InvalidAuthIdError, InvalidPasswordError): self._create_new_user(gplus['email'], gplus['email'], gplus['id'], name=gplus['first_name'], last_name=gplus['last_name'], gplus_url=gplus['url'], login_type=UserProfile.GOOGLE_USER, gplus_user=gplus['id']) self.render_json({'redirect_to': uri_for('dashboard')})
def put(self, obj_t, *args): kvs = json.decode(self.request.body) # find model class cls = getattr(sys.modules['core.model'], obj_t) # dispatch put to that model class. all model classes need to a subclass model.RESTModel obj = utils.to_dict(cls.put1(kvs)) return self.prep_json_response(200, message=obj)
def put(self, obj_t, *args): kvs = json.decode(self.request.body) # find model class cls = getattr(sys.modules['core.model'], obj_t) # dispatch put to that model class. all model classes need to a subclass model.RESTModel obj = utils.to_dict(cls.put1(kvs)) return self.prep_json_response(200, message = obj)
def post(self): self.set_response_data() params = json.decode(self.request.body) facebook_access_token = params.get('facebook_access_token') if not facebook_access_token: self.abort(code=400) facebook_user = facebook.get_user(facebook_access_token) user = queries.get_or_create_user(**facebook_user) token = queries.create_token(facebook_access_token=facebook_access_token, **facebook_user) self.response.write(json.encode(convert.user(token, user)))
def test_show_error(self): request = webapp2.Request.blank("/") response = request.get_response(app) self.assertEqual(response.status_int, 200) self.assertIn("application/json", response.headers['Content-Type']) self.assertDictEqual( json.decode(response.body), { "name": "I am DR bot (https://telegram.me/DzzzzR_bot)", "result": "Info" })
def login_facebook(self): fb_object = json.decode(self.request.get('fb_object')) try: auth_user = self.auth.get_user_by_password(fb_object['username'], fb_object['id'], remember=True) except (InvalidAuthIdError, InvalidPasswordError): self._create_new_user(fb_object['username'], fb_object['email'], fb_object['id'], name=fb_object['first_name'], last_name=fb_object['last_name'], fcbk_url=fb_object['link'], login_type=UserProfile.FACEBOOK_USER, fcbk_user=fb_object['id']) self.render_json({'redirect_to': uri_for('dashboard')})
def getpacks(self): if self.packs is None: self.packs = [] q = Pack.all() q.order('-date') for p in q.run(limit=10): idxbytes = blobstore.BlobReader(p.idx).read() idx = json.decode(zlib.decompress(idxbytes)) self.packs.append((idx, p.blob)) logging.info("getpacks, len(packs) = " + ` len(self.packs) `) return self.packs
def test_delete_unauth(self): # create widget in DB and get its id widget = copy.copy(self.json_widget) ident = model.Widget.put1(widget).key.integer_id() self.assertEqual(1, len(model.Widget.query().fetch(2))) response = self.testapp.delete('/rest/Widget/' + str(ident), expect_errors=True) self.assertEqual(response.status_int, 401) self.assertEqual(json.decode(response.body)['code'], 401)
def get_groups(user_key, versions): """Get the groups the user is included in Keyword arguments: user_key - the key of the user Returns: The groups the user has access to in a json array """ user = User.find_by_key(user_key) if (user == None): raise Exception("Invalid key") response = {"user_version" : user.version, "groups" : []} if (user_key not in versions) or (versions[user_key] < user.version): user_groups = JSON.decode(user.groups) for group_key in user_groups: group = Group.find_by_key(group_key) if (group_key not in versions) or (versions[group_key] < group.version): response["groups"].append( { "group_key" : group_key, "group_name" : group.name, "group_usernames" : JSON.decode(group.usernames), "group_pending_usernames" : JSON.decode(group.pending_usernames), "group_version" : group.version, "group_lists" : JSON.decode(group.get_item_lists(versions)), "group_photo" : group.photo if ((group_key+"_photo" not in versions) or (versions[group_key+"_photo"] < group.photo_version)) else "", "group_photo_version" : group.photo_version }) return str(json.dumps(response)).replace("\\\"","\"")
def post(self): workflow = Workflow(**json.decode(self.request.body)) versions = Workflow.query(Workflow.name == workflow.name).order(-Workflow.version).fetch(1) if any(versions): # bump version to one greater that last known one workflow.version = versions[0].version + 1 new_key = workflow.put() logging.info("Create/update: %s", new_key.id()) if any(versions): # replace earlier with this version in relevant agent workflow sets old_id = versions[0].key.id() for agent in Agent.query(Agent.trackVersion == True, Agent.workflows == old_id): agent.workflows.remove(old_id) agent.workflows.append(new_key.id()) self.redirect('/workflows')
def add_users(group_key, usernames): #Find the user to add the key to group = Group.find_by_key(group_key) if (group == None): raise Exception("Invalid group key") #Get the pending usernames and current usernames group_usernames = JSON.decode(group.usernames) group_pending_usernames = JSON.decode(group.pending_usernames) usernames = JSON.unquote(usernames) for username in usernames: #Find the user to add the key to user = User.find_by_username(username) if (user != None): if (user.username not in group_pending_usernames) and (user.username not in group_usernames): #Add the username to the list of pending users group_pending_usernames.append(user.username) #Add the group to the list of user groups user_groups = JSON.decode(user.groups) user_groups.append(group_key) user.groups = JSON.encode(user_groups) user.increment_version() user.put() group.pending_usernames = JSON.encode(group_pending_usernames) group.increment_version() group.put() #Return the currently pending users return str(json.dumps(group_pending_usernames)).replace("\\\"","\"")