def post_bot_message(response_bot_params): bot_params = {} bot_params['bot_id'] = vars(response_bot_params)['bot_id'] bot_params['text'] = vars(response_bot_params)['text'] if response_bot_params.picture_url is not None: bot_params['picture_url'] = vars(response_bot_params)['picture_url'] result = requests.post('https://api.groupme.com/v3/bots/post', params=bot_params) if result.status_code == 201: print("EVENT: POST 201 SUCCESSFUL RESPONSE") created_response = result.json()['response']['message'] response = Response(201, created_response['id'], None) return response if result.status_code == 202: print("EVENT: POST 202 SUCCESSFUL RESPONSE") response = Response(202, None, bot_params['text']) return response if result.status_code == 400: print("ERROR: POST 400 BAD REQUEST") write_error_to_logfile("ERROR: POST 400 BAD REQUEST") return False if result.status_code == 401: print("ERROR: POST 401 UNAUTHORIZED") write_error_to_logfile("ERROR: POST 401 UNAUTHORIZED") return False if result.status_code == 409: print("ERROR: POST 409 CONFLICT") write_error_to_logfile("ERROR: POST 409 CONFLICT") return False else: print("ERROR: REQUEST EXCEPTION") raise requests.exceptions.RequestException
async def add_player(self, name, ws): player = Player(name=name, ws=ws) action = "add_player" if len(self._players) > 4: response = Response(action=action, message='"Game is already full"') elif player in self._players: response = Response(action=action, message=f"{player.name} already exists") else: self._players.append(player) player.turn_id = self._players.index(player) player_id = player.turn_id setattr(self.game, f"player_{player_id}", player) response = Response( action=action, message=f'Player added! Player ID: {player_id}', body={ "player_id": player_id, **player.to_dict() }) await self.send_response(response=response, player=player) await self.distribute_game(to_waiting=True)
def join_quiz(quiz_id, user_id=None): ## Get user from request if request: user = User.query.get(request.form['user_id']) else: user = User.query.get(user_id) quiz = Quiz.query.get(quiz_id) if Timer.query.filter(Timer.quiz_id == quiz_id).filter( Timer.user_id == user.id).first() is None: timer = Timer(quiz_id=quiz_id, user_id=user.id, last_answered=datetime.now()) db.session.add(timer) if Response.query.filter(Response.quiz_id == quiz_id).filter( Response.user_id == user.id).first() is None: ## Create responses for user for index in range(0, 10): questions = json.loads(quiz.questions) response = Response(question_id=questions[index], user_id=user.id, quiz_id=quiz_id) db.session.add(response) ## Store responses for user db.session.commit() status_dict = dict() status_dict['status'] = 'JOINED' status_dict['quiz_id'] = quiz_id return jsonify(status_dict)
def test_render_mf2(self): Response(id='abc xyz', source_mf2=json.dumps(self.mf2)).put() resp = app.get_response('/render?source=abc&target=xyz') self.assertEquals(200, resp.status_int) self.assert_multiline_equals(self.html, resp.body.decode('utf-8'), ignore_blanks=True)
def test_render_atom(self): Response(id='abc xyz', source_atom=self.atom).put() resp = self.client.get('/render?source=abc&target=xyz') self.assertEqual(200, resp.status_code) self.assert_multiline_equals(self.html, resp.get_data(as_text=True), ignore_blanks=True)
def add_response(**kwargs): response = Response(**kwargs) try: db.session.add(response) db.session.commit() except SQLAlchemyError as e: print 'ERROR adding response', e
def answer(request, poll_id, user_uuid): poll = get_object_or_404(Poll, pk=poll_id) participant = get_object_or_404(Participant, unique_id=user_uuid) if participant.completed: return redirect(reverse('polls:thanks', args=(poll.id, user_uuid,))) questions = poll.question_set.all() if request.method == 'POST': form = DetailForm(request.POST, questions=questions) if form.is_valid(): to_delete = Response.objects.filter(participant=participant) to_delete.delete() for choice_id in form.answers(): response = Response(participant=participant, choice_id=choice_id) response.save() return HttpResponseRedirect(reverse('polls:sign', args=(poll.id, user_uuid,))) else: form = DetailForm(questions=questions) return render(request, 'polls/detail.html', { 'poll': poll, 'form': form, 'user_uuid': user_uuid, })
def normalize_input(): data = json.loads(request.data) response = Response() response.source = data["deviceId"] response.timestamp = convert_date_string_to_int(data["timestamp"]) response.data = dict() for key in data: if key == "deviceId" or key == "timestamp": continue response_data = Data() try: response_data.string = str(data[key]) except: response_data.string = None try: response_data.numeric = float(data[key]) except: response_data.numeric = None try: response_data.datetime = convert_date_string_to_int(data[key]) except: response_data.datetime = None response.data[key] = response_data return response.toJSON()
def test_render_atom(self): Response(id='abc xyz', source_atom=self.atom).put() resp = application.get_response('/render?source=abc&target=xyz') self.assertEqual(200, resp.status_int) self.assert_multiline_equals(self.html, resp.body.decode(), ignore_blanks=True)
def process_requests(): global account global last_processed_request_id # process request data ubr_list = UBRList() ubr_list.deserialize(request.get_json()) app.logger.debug('Processing received bank requests.') # sort request data sorted_bank_requests = ubr_list.get_sorted() # perform bank requests in order for req in sorted_bank_requests: if last_processed_request_id < req.id: if req.operation == 'CREDIT': account.increase_balance(req.amount) else: account.decrease_balance(req.amount) last_processed_request_id = req.id # response response = Response(code=status.HTTP_200_OK, description='Bankovní operace úspěšně zpracovány.') return make_response(response.serialize(), status.HTTP_200_OK)
def try_salmon(self): """ Returns Flask response (string body or tuple) if we attempted OStatus delivery (whether successful or not), None if we didn't attempt, raises an exception otherwise. """ target = None if self.target_resp: target = self.target_resp.url else: targets = self._targets() if targets: target = targets[0] if not target: logging.warning("No targets or followers. Ignoring.") return status = None try: ret = self._try_salmon(target) if isinstance(ret, str): status = 'complete' return ret except: status = 'error' raise finally: if status: Response(source=self.source_url, target=target, status=status, direction='out', protocol='ostatus', source_mf2=json_dumps(self.source_mf2)).put()
def mockdata(): user = User( username="******", email="*****@*****.**", is_admin=False, ) user.set_password("pass") question_cool = Question(body="Is it cool?") question_neat = Question(body="Is this neat?") token_cool = Token(name="cool") token_neat = Token(name="neat") mod_cool = Modifier(yes_modifier=1, no_modifier=-1, token=token_cool, question=question_cool) mod_neat = Modifier(yes_modifier=1, no_modifier=-1, token=token_neat, question=question_neat) resp_yes_neat = Response(user=user, answer="yes", question=question_neat) resp_no_cool = Response(user=user, answer="no", question=question_cool) data = [ user, question_cool, question_neat, token_cool, token_neat, mod_cool, mod_neat, resp_no_cool, resp_yes_neat ] app.logger.info("Inserting mock data...") for datum in data: db.session.add(datum) try: db.session.commit() except Exception as e: db.session.rollback() app.logger.error("Error inserting mock data: {}".format(e)) finally: db.session.close() app.logger.info("Mock data inserted")
def fetch_arguments(self): """ Fetches arguments. Please call get_all_arguments() to get all arguments. """ url = self.api['arguments_url'] if not self.url else self.url result = requests.get(url).json() response = Response() [setattr(response, key, result[key]) for key in response.keys] return response
def shuffle_requests(): global endpoints # process request data ubr_list = UBRList() ubr_list.deserialize(request.get_json()) valid_json_data = ubr_list.serialize() # init results success = [] fail = [] app.logger.info('Sending data to all endpoints.') # shuffle endpoints shuffle(endpoints) for endpoint in endpoints: # shuffle data shuffle(valid_json_data) # sent data url = "http://{0}:{1}{2}".format(endpoint.host, endpoint.port, endpoint.route) try: status_code = requests.post(url, json=valid_json_data).status_code except requests.exceptions.RequestException: status_code = status.HTTP_408_REQUEST_TIMEOUT # handle response if status_code is status.HTTP_200_OK: success.append({'endpoint': url, 'code': status_code}) else: fail.append({'endpoint': url, 'code': status_code}) app.logger.debug('\n' + json.dumps({'successful': success, 'failed': fail}, indent=4, sort_keys=True)) # response if len(fail) == 0: response = Response( code=status.HTTP_200_OK, description='Bankovní operace úspěšně zpracovány' ) return make_response(response.serialize(), status.HTTP_200_OK) else: response = Response( code=status.HTTP_503_SERVICE_UNAVAILABLE, description='Nepodařilo se zpracovat bankovní oprace' ) return make_response(response.serialize(), status.HTTP_503_SERVICE_UNAVAILABLE)
def send_webmentions(handler, activity, **response_props): """Sends webmentions for an incoming Salmon slap or ActivityPub inbox delivery. Args: handler: RequestHandler activity: dict, AS1 activity response_props: passed through to the newly created Responses """ verb = activity.get('verb') if verb and verb not in SUPPORTED_VERBS: error(handler, '%s activities are not supported yet.' % verb) # extract source and targets source = activity.get('url') or activity.get('id') obj = activity.get('object') obj_url = util.get_url(obj) targets = util.get_list(activity, 'inReplyTo') if isinstance(obj, dict): if not source: source = obj_url or obj.get('id') targets.extend(util.get_list(obj, 'inReplyTo')) if verb in ('like', 'share'): targets.append(obj_url) targets = util.dedupe_urls(util.get_url(t) for t in targets) if not source: error(handler, "Couldn't find original post URL") if not targets: error(handler, "Couldn't find target URLs (inReplyTo or object)") # send webmentions and store Responses errors = [] for target in targets: if not target: continue response = Response(source=source, target=target, direction='in', **response_props) response.put() wm_source = response.proxy_url() if verb in ('like', 'share') else source logging.info('Sending webmention from %s to %s', wm_source, target) wm = send.WebmentionSend(wm_source, target) if wm.send(headers=HEADERS): logging.info('Success: %s', wm.response) response.status = 'complete' else: logging.warning('Failed: %s', wm.error) errors.append(wm.error) response.status = 'error' response.put() if errors: msg = 'Errors:\n' + '\n'.join(json.dumps(e, indent=2) for e in errors) error(handler, msg, status=errors[0].get('http_status'))
def test_basic_response(self): response = Response( status_code=200, reason_phrase='Ok', headers={'Content-Length': 5}, body='Hello', ) response_bytes = serializer.serialize_response(response) assert response_bytes == b'HTTP/1.1 200 Ok\r\nContent-Length: 5\r\n\r\nHello'
def get(self): """ :param key problem id :param oj problem origin :return: """ params = self._get_params() if params is None: self.finish( json.dumps( dict( Response(code=Response.FAIL, data=None, message="key and oj param is required")))) else: params['task_id'] = uuid.uuid1().hex self.storage.save(REDIS_TARGET_TOPIC, json.dumps(params)) logger.info('create crawl problem-{}-{} success'.format( params['oj'], params['key'])) self.finish(json.dumps(dict(Response(data=params))))
def messagePatient(id, query): doc = Doctor.query.get(id) form = FeedbackForm() if form.validate_on_submit(): new = Response(content=form.content.data, doctor_id=doc.id, query_id=query) db.session.add(new) db.session.commit() return redirect(url_for('docMessages', id=doc.id)) return render_template('respond.html', doc=doc, form=form)
def test_oversized_status_code(self): try: response = Response( status_code=2000, reason_phrase='Ok', headers={'Content-Length': 5}, body='Hello', ) serializer.serialize_response(response) self.fail() except ValueError as e: assert str(e) == 'Status code must be < 1000'
def test_negative_status_code(self): try: response = Response( status_code=-200, reason_phrase='Ok', headers={'Content-Length': 5}, body='Hello', ) serializer.serialize_response(response) self.fail() except ValueError as e: assert str(e) == 'Status code cannot be negative'
def fetch_followers(self): """ Fetches your followers. Please call get_all_followers() to get your all followers. """ url = self.api['followers_url'].format( username=self.credentials['username'] ) if not self.url else self.url result = requests.get(url).json() response = Response() [setattr(response, key, result[key]) for key in response.keys] return response
def test_get_or_save_merge_urls(self): self.responses[0].failed = ['http://failed/1'] self.responses[0].put() got = Response( id=self.responses[0].key.id(), unsent=['http://new'], failed=['http://failed/1', 'http://failed/2'], response_json=self.responses[0].response_json, ).get_or_save(self.sources[0]) self.assertEqual(['http://target1/post/url', 'http://new'], got.unsent) self.assertEqual(['http://failed/1', 'http://failed/2'], got.failed)
def calculate_response(answer_word: Word, guess_word: Word): response = Response(guess_word) for i, char in enumerate(guess_word.chars): if char == answer_word.chars[i]: response.colors.append('g') elif char in answer_word.chars: response.colors.append('y') else: response.colors.append('b') return response
async def guess_block(self, player, guess: Guess): from_player = player # type: Player to_player = getattr(self.game, f'player_{guess.to_player_id}') # type: Player success = from_player.guess_block(target_player=to_player, target_block_index=guess.target, guess=guess.guess) await self.distribute_game() if success: response = Response(action=Actions.GUESS_SUCCESS.value, message="Guess Succeeded!", body="") from_player.guessing_more() await self.distribute_response(response=response) await self.distribute_game() next_action_message = await player.ws.recv() request = Request.deserialize(value=next_action_message) if request.action == Actions.MAKE_GUESS.value: guess = Guess(**request.body) await self.guess_block(player, guess) elif request.action == Actions.YIELD_TURN.value: from_player.get_ready() self.game.swap_turn() next_player = getattr(self.game, f'player_{self.game.turn}') next_player.drawing_block() else: raise TypeError('Invalid Action type.') else: response = Response(action=Actions.GUESS_FAIL.value, message="Guess Failed!", body="") await self.distribute_response(response=response) from_player.get_ready() self.game.swap_turn() next_player = getattr(self.game, f'player_{self.game.turn}') next_player.drawing_block() return self.game
def test_render_errors(self): for source, target in ('', ''), ('abc', ''), ('', 'xyz'): resp = app.get_response('/render?source=%s&target=%s' % (source, target)) self.assertEquals(400, resp.status_int, resp.body) # no Response resp = app.get_response('/render?source=abc&target=xyz') self.assertEquals(404, resp.status_int) # no source data Response(id='abc xyz').put() resp = app.get_response('/render?source=abc&target=xyz') self.assertEquals(404, resp.status_int)
def test_render_errors(self): for source, target in ('', ''), ('abc', ''), ('', 'xyz'): resp = self.client.get(f'/render?source={source}&target={target}') self.assertEqual(400, resp.status_code, resp.get_data(as_text=True)) # no Response resp = self.client.get('/render?source=abc&target=xyz') self.assertEqual(404, resp.status_code) # no source data Response(id='abc xyz').put() resp = self.client.get('/render?source=abc&target=xyz') self.assertEqual(404, resp.status_code)
def test_good(self): self.expect_requests_get( 'http://foo.com/', """ <html class="h-feed"> <div class="h-entry"> <a class="u-url" href="http://foo.com/post"></a> <a class="u-syndication" href="https://www.facebook.com/snarfed.org/posts/123"></a> </div> </html>""") self.mox.ReplayAll() self.handler.receive(self.mail) self.assert_equals(200, self.response.status_code) emails = list(FacebookEmail.query()) self.assertEquals(1, len(emails)) self.assert_equals('SMTP-123-xyz', emails[0].key.id()) self.assert_equals(self.fea.key, emails[0].source) self.assert_equals([COMMENT_EMAIL_USERNAME], emails[0].htmls) resp_id = EMAIL_COMMENT_OBJ_USERNAME['id'] self.assert_equals(ndb.Key('Response', resp_id), emails[0].response) expected = Response( id=resp_id, source=self.fea.key, type='comment', response_json=json.dumps(EMAIL_COMMENT_OBJ_USERNAME), activities_json=[ json.dumps({ 'id': '123', 'numeric_id': '123', 'url': 'https://www.facebook.com/212038/posts/123', 'author': { 'id': 'snarfed.org' }, }) ], unsent=['http://foo.com/post']) self.assert_entities_equal([expected], list(Response.query()), ignore=('created', 'updated')) tasks = self.taskqueue_stub.GetTasks('propagate') self.assertEquals(1, len(tasks)) self.assert_equals(expected.key.urlsafe(), testutil.get_task_params(tasks[0])['response_key']) self.assert_equals(EMAIL_COMMENT_OBJ_USERNAME, self.fea.get_comment('123_789'))
def handler(request_data): # request request = Request(request_data.decode('utf-8')) # file path path = config.ROOT_DIR + urlparse(request.url).path if request.url.endswith("/"): path += "index.html" path_is_exist = os.path.exists(path) # response if request.method not in REQUEST_METHODS: response = Response(method=request.method, protocol=request.protocol, status=405) elif "/.." in request.url or (request.url.endswith("/") and not path_is_exist): if mimetypes.guess_type(request.url[:-1])[0] is None: response = Response(method=request.method, protocol=request.protocol, status=403) else: response = Response(method=request.method, protocol=request.protocol, status=404) elif (not request.is_valid) or (not path_is_exist): response = Response(method=request.method, protocol=request.protocol, status=404) else: content_type = mimetypes.guess_type(path)[0] with open(path, 'rb') as stream: data = stream.read() if len(data) == 0: print(path, content_type, data, len(data)) response = Response(method=request.method, protocol=request.protocol, status=200, content_type=content_type, content_length=len(data)) headers = response.get_headers() if request.method == 'GET' and response.status == 200: return [headers, data] else: return [headers]
async def distribute_game(self, to_waiting=False): response = Response(action=Actions.UPDATE_GAME.value, body=self.game.to_dict()) serialized_response = response.serialize() if to_waiting: tasks = [ asyncio.ensure_future(ws.send(serialized_response)) for ws in self._waiting ] else: tasks = [ asyncio.ensure_future(player.ws.send(serialized_response)) for player in self._players ] await asyncio.gather(*tasks)
def respond(request): """ Request handler when someone posts a response 1. Add response content to the database 2. Send push notification to client device 3. Update the credit of the responder """ if request.method == 'POST': json_data = json.loads(request.body) try: thread_id = json_data['thread_id'] response_content = json_data['content'] device_id = json_data['device_id'] except KeyError: print "Error: A posted response did not have a JSON object with the required properties" else: # check that the thread id and the device ids are valid thread = Thread.objects.filter(id=thread_id) device = Device.objects.filter(device_id=device_id) print "Passed parameter validation" print thread.count() print device.count() if thread.exists() and device.exists(): # add response to database response = Response(thread=thread[0], responder_device=device[0], response_content=response_content) response.save() # add update to the other device asker_device = thread[0].asker_device answerer_device = thread[0].answerer_device print "Thread and device actually exist" print device_id print asker_device.device_id print answerer_device.device_id if asker_device.device_id == device_id: ResponseUpdates.add_update(answerer_device, response) print "Adding an update to the answerers queue" elif answerer_device.device_id == device_id: ResponseUpdates.add_update(asker_device, response) print "Adding an update to the askers queue" return HttpResponse(json.dumps({}), content_type="application/json")