def sendRequest(request, operation, pk=None): friend = User.objects.get(pk=pk) if operation == 'add': Request.sendRequest(request.user, friend) elif operation == 'remove': Request.removeRequest(request.user, friend) return redirect('requests:index')
def __init__(self, method=None, url=None, headers=None, files=None, data=None, params=None, auth=None, cookies=None, hooks=None, json=None, request=None): if isinstance(request, HTTPRequest): request = self._transform_tornado_request(request) elif not isinstance(request, _Request): request = None _Request.__init__(self, method=method or getattr(request, 'method', None), url=url or getattr(request, 'url', None), headers=headers or getattr(request, 'headers', None), files=files or getattr(request, 'files', None), data=data or getattr(request, 'data', None), params=params or getattr(request, 'params', None), auth=auth or getattr(request, 'auth', None), cookies=cookies or getattr(request, 'cookies', None), hooks=hooks or getattr(request, 'hooks', None), json=json or getattr(request, 'json', None))
def application(environ, start_response): # The WSGI server puts content length and type in the environment # even when not provided with the request. Drop them if they are empty. if environ.get('CONTENT_LENGTH') == '': del environ['CONTENT_LENGTH'] if environ.get('CONTENT_TYPE') == '': del environ['CONTENT_TYPE'] wrequest = WerkzeugRequest(environ) data = wrequest.get_data() request = Request( method=wrequest.method, url=wrequest.url, headers=wrequest.headers, data=data, ) prepared = request.prepare() stream = streams.build_output_stream( args, env, prepared, response=None, output_options=args.output_options) streams.write_stream(stream, env.stdout, env.stdout_isatty) # When there is data in the request, give the next one breathing room. if data: print("\n", file=env.stdout) # Make dreams come true. response = Response(headers={'Server': server}) return response(environ, start_response)
def predict_view(request, *args, **kwargs): if request.method == "POST": #GETTING DATA u_img2 = request.FILES['file'] u_mobile = request.POST.get("mobile") u_id = request.POST.get("id_user") u_ip = request.POST.get("ip") fs = FileSystemStorage() filename = fs.save("uploads/" + u_img2.name, u_img2) uploaded_file_url = fs.url(filename) #PREDICTION image = cv2.cvtColor(cv2.imread(uploaded_file_url), cv2.COLOR_BGR2RGB) image = np.array(image) / 127.5 - 1. scaled_img = cv2.resize(image, (224, 224)) scaled_img = np.expand_dims(scaled_img, axis=0) #add batch model = load_model('assets/model_mela.h5') preds = model.predict(scaled_img) #Save Request b = Request(id_request="FX1FFFFF", img=uploaded_file_url, ip=u_ip, mobile=u_mobile, user_id=u_id, preds=preds) b.save() #RETURNS my_context = {"image": uploaded_file_url, "pred": str(preds[0][0])} return JsonResponse(my_context) #return render(request,"predict.html",my_context) else: return HttpResponse("Error 404")
def req(self, request_class, method, url): r = Request() r.method = method r.url = url resp = request_class() resp.request = r return resp
def curl(self, method, endpoint, params=None): url = '{scheme}://{host}{endpoint}'.format(scheme=self.SCHEME, host=self.HOST, endpoint=endpoint) params = params or {} session = Session() request = Request(method, url, params=params) request = request.prepare() request.headers.update({ 'X-Application-Key': self.KEY, }) response = session.send(request) return GforceResponse(response)
def _post(self, resource, headerdict=None, paramdict=None, bodydict=None, rawbody=None): if (bodydict is not None) and (rawbody is not None): raise RequestException( "Not allowed to specify dictionary and raw body at the same time." ) h = {} b = {} p = {} if self.__connectionDetails is None: raise RequestException("Connection detail is None.") h.update(self.__connectionDetails.getHeader()) b.update(self.__connectionDetails.getBody()) p.update(self.__connectionDetails.getParam()) if headerdict is not None: h.update(headerdict) if bodydict is not None: b.update(bodydict) if paramdict is not None: p.update(paramdict) if len(h) is 0: h = None if len(b) is 0: b = None if len(p) is 0: p = None try: if (rawbody is not None): # ignoring template-default body parameters!!! pr = self.session.prepare_request( Request("POST", self.__connectionDetails.formURL() + self._formatResource(resource), headers=h, params=p, data=rawbody, auth=self.__connectionDetails.getAuth())) else: pr = self.session.prepare_request( Request("POST", self.__connectionDetails.formURL() + self._formatResource(resource), headers=h, params=p, json=b, auth=self.__connectionDetails.getAuth())) if self.debug: pprint(vars(pr), indent=2, depth=100) r = self.session.send(pr) if self.debug: pprint(vars(r), indent=2, depth=100) r.raise_for_status() except Exception as e: e.args = e.args[0:] + (e.response.content, ) raise e return r
def do_something(self, request, **kwargs): self.method_check(request, allowed=['get']) data = json.loads(request.raw_post_data) print data["username"], data["comment"], data["longitude"], data["latitude"] user = User.objects.get(username = data["username"]) client = Client.objects.get(user = user) request_new = Request(client = client, comment_user = data["comment"], longitude = data["longitude"], latitude = data["latitude"], rating = 1) request_new.save() providers = Provider.objects.all() for provider in providers: request_provider = RequestXProvider(provider = provider, request = request_new) request_provider.save() return self.create_response(request, {"status": "success"})
def test_send(self, mock_session_cls): request = Request('GET', 'http://example.com/', {}) request = request.prepare() response = mock.MagicMock() response.content = b'{}' session = mock.MagicMock() mock_session_cls.return_value = session session.send.return_value = response response = self.client.send(request) self.assertEqual(type(response), BrandStemResponse) session.send.assert_called_once_with(request)
def request( self, method, url, params=None, data=None, headers=None, cookies=None, files=None, auth=None, timeout=120, # 等待响应,超时时间 allow_redirects=True, proxies=None, hooks=None, stream=None, verify=None, cert=None, json=None) -> Optional[Response]: req = Request( method=method.upper(), url=url, headers=headers, files=files, data=data or {}, json=json, params=params or {}, auth=auth, cookies=cookies, hooks=hooks, ) prep = self.prepare_request(req) proxies = proxies or {} settings = self.merge_environment_settings(prep.url, proxies, stream, verify, cert) send_kwargs = { 'timeout': timeout, 'allow_redirects': allow_redirects, } send_kwargs.update(settings) message = '%s: %s' % (method, prep.url) logger.info(message) for i in range(env.PER_REQUEST_TRY_COUNT + 1): try: r = self.send(prep, **send_kwargs) return r except Timeout: why = 'Timeout' except ConnectionError: why = 'ConnectionError' except ChunkedEncodingError: # 读到的字节数与实际字节数不符 why = 'ChunkedEncodingError' if i != env.PER_REQUEST_TRY_COUNT: logger.warning('%s, retry %d >>> %s' % (why, i + 1, message)) time.sleep(3) logger.error('%s, %s' % (why, message))
def forward_request(self, method, path, data, headers): if method == 'OPTIONS': return 200 req_data = parse_request_data(method, path, data) if req_data: action = req_data.get('Action', [None])[0] if action == 'SetQueueAttributes': queue_url = _queue_url(path, req_data, headers) forward_attrs = _set_queue_attributes(queue_url, req_data) if len(req_data) != len(forward_attrs): # make sure we only forward the supported attributes to the backend return _get_attributes_forward_request(method, path, headers, req_data, forward_attrs) elif action == 'DeleteQueue': QUEUE_ATTRIBUTES.pop(_queue_url(path, req_data, headers), None) elif action == 'ListDeadLetterSourceQueues': queue_url = _queue_url(path, req_data, headers) headers = {'content-type': 'application/xhtml+xml'} content_str = _list_dead_letter_source_queues(QUEUE_ATTRIBUTES, queue_url) return requests_response(content_str, headers=headers) if 'QueueName' in req_data: encoded_data = urlencode(req_data, doseq=True) if method == 'POST' else '' modified_url = None if method == 'GET': base_path = path.partition('?')[0] modified_url = '%s?%s' % (base_path, urlencode(req_data, doseq=True)) return Request(data=encoded_data, url=modified_url, headers=headers, method=method) return True
def session_request(self, method, url, params=None, data=None, headers=None, cookies=None, files=None, auth=None, timeout=conf.timeout if 'timeout' in conf else None, allow_redirects=True, proxies=None, hooks=None, stream=None, verify=False, cert=None, json=None): # Create the Request. merged_cookies = merge_cookies( merge_cookies(RequestsCookieJar(), self.cookies), cookies or conf.cookie if 'cookie' in conf else None) req = Request( method=method.upper(), url=url, headers=merge_setting( headers, conf.http_headers if 'http_headers' in conf else {}), files=files, data=data or {}, json=json, params=params or {}, auth=auth, cookies=merged_cookies, hooks=hooks, ) prep = self.prepare_request(req) proxies = proxies or conf.proxies if 'proxies' in conf else {} settings = self.merge_environment_settings(prep.url, proxies, stream, verify, cert) # Send the request. send_kwargs = { 'timeout': timeout, 'allow_redirects': allow_redirects, } send_kwargs.update(settings) resp = self.send(prep, **send_kwargs) if resp.encoding == 'ISO-8859-1': encodings = get_encodings_from_content(resp.text) if encodings: encoding = encodings[0] else: encoding = resp.apparent_encoding resp.encoding = encoding return resp
def _raw(self, mode, url, headerdict=None, paramdict=None, bodydict=None, rawbody=None): if (bodydict is not None) and (rawbody is not None): raise RequestException( "Not allowed to specify dictionary and raw body at the same time." ) try: pr = self.session.prepare_request( Request(mode, url, headers=headerdict, params=paramdict, data=rawbody, json=bodydict, auth=self.__connectionDetails.getAuth())) if self.debug: pprint(vars(pr), indent=2, depth=100) r = self.session.send(pr) if self.debug: pprint(vars(r), indent=2, depth=100) r.raise_for_status() except requests.RequestException as e: e.args = e.args[0:] + (e.response.content, ) raise e return r
def _del(self, resource, headerdict=None, paramdict=None): # attaching body is highly discouraged, therefore not supported h = {} p = {} if self.__connectionDetails is None: raise RequestException("Connection detail is None.") h.update(self.__connectionDetails.getHeader()) p.update(self.__connectionDetails.getParam()) if headerdict is not None: h.update(headerdict) if paramdict is not None: p.update(paramdict) if len(h) is 0: h = None if len(p) is 0: p = None try: pr = self.session.prepare_request( Request("DELETE", self.__connectionDetails.formURL() + self._formatResource(resource), params=p, headers=h, auth=self.__connectionDetails.getAuth())) if self.debug: pprint(vars(pr), indent=2, depth=100) r = self.session.send(pr) if self.debug: pprint(vars(r), indent=2, depth=100) r.raise_for_status() except Exception as e: e.args = e.args[0:] + (e.response.content, ) raise e return r
def forward_request(self, method, path, data, headers): req_data = None if method == 'POST' and path == '/': req_data = urlparse.parse_qs(data) action = req_data.get('Action')[0] if req_data: if action == 'CreateChangeSet': return create_change_set(req_data) elif action == 'DescribeChangeSet': return describe_change_set(req_data) elif action == 'ExecuteChangeSet': return execute_change_set(req_data) elif action == 'UpdateStack' and req_data.get('TemplateURL'): # Temporary fix until the moto CF backend can handle TemplateURL (currently fails) url = re.sub(r'https?://s3\.amazonaws\.com', aws_stack.get_local_service_url('s3'), req_data.get('TemplateURL')[0]) req_data['TemplateBody'] = requests.get(url).content modified_data = urlparse.urlencode(req_data, doseq=True) return Request(data=modified_data, headers=headers, method=method) elif action == 'ValidateTemplate': return validate_template(req_data) return True
def prepare_request(self, request: Request) -> PreparedRequest: url_netloc: str = urlparse(request.url).netloc if not url_netloc: request.url = urljoin(self.base_url, request.url) prepared_request: PreparedRequest = super().prepare_request( request) # type: ignore[no-untyped-call] return prepared_request
def forward_request(self, method, path, data, headers): if method == 'POST' and path == '/': req_data = urlparse.parse_qs(to_str(data)) if 'QueueName' in req_data: encoded_data = urlencode(req_data, doseq=True) request = Request(data=encoded_data, headers=headers, method=method) return request elif req_data.get('Action', [None])[0] == 'SendMessage': queue_url = req_data.get('QueueUrl', [None])[0] queue_name = queue_url[queue_url.rindex('/') + 1:] message_body = req_data.get('MessageBody', [None])[0] if lambda_api.process_sqs_message(message_body, queue_name): # If an lambda was listening, do not add the message to the queue new_response = Response() new_response._content = SUCCESSFUL_SEND_MESSAGE_XML_TEMPLATE.format( message_attr_hash=md5(data), message_body_hash=md5(message_body), message_id=str(uuid.uuid4()), ) new_response.status_code = 200 return new_response return True
def _prepare_long_request(self, url, api_query): """ Use requests.Request and requests.PreparedRequest to produce the body (and boundary value) of a multipart/form-data; POST request as detailed in https://www.mediawiki.org/wiki/API:Edit#Large_texts """ partlist = [] for k, v in iteritems(api_query): if k in ('title', 'text', 'summary'): # title, text and summary values in the request # should be utf-8 encoded part = (k, (None, v.encode('utf-8'), 'text/plain; charset=UTF-8', {'Content-Transfer-Encoding': '8bit'} ) ) else: part = (k, (None, v)) partlist.append(part) auth1 = OAuth1( self.consumer_token.key, client_secret=self.consumer_token.secret, resource_owner_key=session['mwoauth_access_token']['key'], resource_owner_secret=session['mwoauth_access_token']['secret']) return Request( url=url, files=partlist, auth=auth1, method="post").prepare()
def forward_request(self, method, path, data, headers): if method == 'OPTIONS': return 200 req_data = parse_request_data(method, path, data) if req_data: action = req_data.get('Action', [None])[0] if action == 'SetQueueAttributes': queue_url = _queue_url(path, req_data, headers) forward_attrs = _set_queue_attributes(queue_url, req_data) if len(req_data) != len(forward_attrs): # make sure we only forward the supported attributes to the backend return _get_attributes_forward_request( method, path, headers, req_data, forward_attrs) elif action == 'DeleteQueue': QUEUE_ATTRIBUTES.pop(_queue_url(path, req_data, headers), None) if 'QueueName' in req_data: encoded_data = urlencode( req_data, doseq=True) if method == 'POST' else '' modified_url = None if method == 'GET': base_path = path.partition('?')[0] modified_url = '%s?%s' % (base_path, urlencode(req_data, doseq=True)) return Request(data=encoded_data, url=modified_url, headers=headers, method=method) return True
def forward_request(self, method, path, data, headers): if method == 'OPTIONS': return 200 req_data = self.parse_request_data(method, path, data) if req_data: action = req_data.get('Action', [None])[0] if action == 'SendMessage': new_response = self._send_message(path, data, req_data, headers) if new_response: return new_response elif action == 'SetQueueAttributes': self._set_queue_attributes(path, req_data, headers) if 'QueueName' in req_data: encoded_data = urlencode( req_data, doseq=True) if method == 'POST' else '' modified_url = None if method == 'GET': base_path = path.partition('?')[0] modified_url = '%s?%s' % (base_path, urlencode(req_data, doseq=True)) request = Request(data=encoded_data, url=modified_url, headers=headers, method=method) return request return True
def forward_request(self, method, path, data, headers): if method == 'OPTIONS': return 200 target = headers.get('X-Amz-Target') data_orig = data if method == 'POST' and target: data = json.loads(to_str(data)) if target == ACTION_GET_PARAMS: names = data['Names'] = data.get('Names') or [] for i in range(len(names)): names[i] = normalize_name(names[i]) elif target in [ACTION_PUT_PARAM, ACTION_GET_PARAM]: name = data.get('Name') or '' data['Name'] = normalize_name(name) if target == ACTION_GET_PARAM: details = name.split('/') if len(details) > 4: service = details[3] if service == 'secretsmanager': resource_name = '/'.join(details[4:]) return get_secrets_information(name, resource_name) data = json.dumps(data) if data != data_orig: return Request(data=data, headers=headers, method=method) return True
def session_request(self, method, url, params=None, data=None, headers=None, cookies=None, files=None, auth=None, timeout=None, allow_redirects=True, proxies=None, hooks=None, stream=None, verify=False, cert=None, json=None): conf = CONF.get("requests", {}) if timeout is None and "timeout" in conf: timeout = conf["timeout"] merged_cookies = merge_cookies( merge_cookies(RequestsCookieJar(), self.cookies), cookies or (conf.cookie if "cookie" in conf else None)) req = Request( method=method.upper(), url=url, headers=merge_setting(headers, conf["headers"] if "headers" in conf else {}), files=files, data=data or {}, json=json, params=params or {}, auth=auth, cookies=merged_cookies, hooks=hooks, ) prep = self.prepare_request(req) proxies = proxies or (conf["proxies"] if "proxies" in conf else {}) settings = self.merged_environment_settings(prep.url, proxies, stream, verify, cert) send_kwargs = { "timeout": timeout, "allow_redirects": allow_redirects, } send_kwargs.update(settings) resp = self.send(prep, **send_kwargs) if resp.encoding == "ISO-8859-1": encodings = get_encodings_from_content(resp.text) if encodings: encoding = encodings[0] else: encoding = resp.apparent_encoding resp.encoding = encoding return resp
def forward_request(self, method, path, data, headers): if method == 'OPTIONS': return 200 req_data = None if method == 'POST' and path == '/': req_data = urlparse.parse_qs(to_str(data)) req_data = dict([(k, v[0]) for k, v in req_data.items()]) action = req_data.get('Action') stack_name = req_data.get('StackName') if action == 'CreateStack': event_publisher.fire_event(event_publisher.EVENT_CLOUDFORMATION_CREATE_STACK, payload={'n': event_publisher.get_hash(stack_name)}) if action == 'DeleteStack': client = aws_stack.connect_to_service('cloudformation') stack_resources = client.list_stack_resources(StackName=stack_name)['StackResourceSummaries'] template_deployer.delete_stack(stack_name, stack_resources) if action == 'DescribeStackEvents': # fix an issue where moto cannot handle ARNs as stack names (or missing names) run_fix = not stack_name if stack_name: if stack_name.startswith('arn:aws:cloudformation'): run_fix = True pattern = r'arn:aws:cloudformation:[^:]+:[^:]+:stack/([^/]+)(/.+)?' stack_name = re.sub(pattern, r'\1', stack_name) if run_fix: stack_names = [stack_name] if stack_name else self._list_stack_names() client = aws_stack.connect_to_service('cloudformation') events = [] for stack_name in stack_names: tmp = client.describe_stack_events(StackName=stack_name)['StackEvents'][:1] events.extend(tmp) events = [{'member': e} for e in events] response_content = '<StackEvents>%s</StackEvents>' % obj_to_xml(events) return make_response('DescribeStackEvents', response_content) if req_data: if action == 'ValidateTemplate': return validate_template(req_data) if action in ['CreateStack', 'UpdateStack']: do_replace_url = is_real_s3_url(req_data.get('TemplateURL')) if do_replace_url: req_data['TemplateURL'] = convert_s3_to_local_url(req_data['TemplateURL']) url = req_data.get('TemplateURL', '') is_custom_local_endpoint = is_local_service_url(url) and '://localhost:' not in url modified_template_body = transform_template(req_data) if not modified_template_body and is_custom_local_endpoint: modified_template_body = get_template_body(req_data) if modified_template_body: req_data.pop('TemplateURL', None) req_data['TemplateBody'] = modified_template_body if modified_template_body or do_replace_url: data = urlparse.urlencode(req_data, doseq=True) return Request(data=data, headers=headers, method=method) return True
def forward_request(self, method, path, data, headers): if method == 'POST' and path == '/': if 'nextToken' in to_str(data or ''): data = self._fix_next_token_request(data) headers['content-length'] = str(len(data)) return Request(data=data, headers=headers, method=method) return True
def create_request(method, path, subdomain=None, query_string=''): base_url = '://'.join([schema, server_name]) url = urljoin(base_url, path) params = parse_qs(query_string) headers = { 'Content-Type': 'application/json', } return Request(method, url, params=params, headers=headers)
def test_https_referer(): """Django requires all POST requests via HTTPS to have the Referer header set.""" c = Client() r = c._session.prepare_request(Request('POST', LOGIN_URL)) c._session.get_adapter(LOGIN_URL).add_headers(r) assert r.headers['Referer'] == LOGIN_URL
def forward_request(self, method, path, data, headers): if method == 'OPTIONS': return 200 req_data = parse_request_data(method, path, data) if is_sqs_queue_url(path) and method == 'GET': if not headers.get('Authorization'): headers['Authorization'] = aws_stack.mock_aws_request_headers(service='sqs')['Authorization'] method = 'POST' req_data = {'Action': 'GetQueueUrl', 'Version': API_VERSION, 'QueueName': path.split('/')[-1]} if req_data: action = req_data.get('Action') if action in ('SendMessage', 'SendMessageBatch') and SQS_BACKEND_IMPL == 'moto': # check message contents for key, value in req_data.items(): if not re.match(MSG_CONTENT_REGEX, str(value)): return make_requests_error(code=400, code_string='InvalidMessageContents', message='Message contains invalid characters') elif action == 'SetQueueAttributes': # TODO remove this function if we stop using ElasticMQ entirely queue_url = _queue_url(path, req_data, headers) if SQS_BACKEND_IMPL == 'elasticmq': forward_attrs = _set_queue_attributes(queue_url, req_data) if len(req_data) != len(forward_attrs): # make sure we only forward the supported attributes to the backend return _get_attributes_forward_request(method, path, headers, req_data, forward_attrs) elif action == 'CreateQueue': changed_attrs = _fix_dlq_arn_in_attributes(req_data) if changed_attrs: return _get_attributes_forward_request(method, path, headers, req_data, changed_attrs) elif action == 'DeleteQueue': queue_url = _queue_url(path, req_data, headers) QUEUE_ATTRIBUTES.pop(queue_url, None) sns_listener.unsubscribe_sqs_queue(queue_url) elif action == 'ListDeadLetterSourceQueues': # TODO remove this function if we stop using ElasticMQ entirely queue_url = _queue_url(path, req_data, headers) if SQS_BACKEND_IMPL == 'elasticmq': headers = {'content-type': 'application/xhtml+xml'} content_str = _list_dead_letter_source_queues(QUEUE_ATTRIBUTES, queue_url) return requests_response(content_str, headers=headers) if 'QueueName' in req_data: encoded_data = urlencode(req_data, doseq=True) if method == 'POST' else '' modified_url = None if method == 'GET': base_path = path.partition('?')[0] modified_url = '%s?%s' % (base_path, urlencode(req_data, doseq=True)) return Request(data=encoded_data, url=modified_url, headers=headers, method=method) return True
def test_set_headers(self): auth = ApiKeyAuth(username=self.user.username, api_key=self.api_key.key) req = Request() req = auth.__call__(req) self.assertTrue('Authorization' in req.headers) expected_headers = 'ApiKey %s:%s' % (self.user.username, self.api_key.key) self.assertEquals(req.headers['Authorization'], expected_headers)
def _get_attributes_forward_request(method, path, headers, req_data, forward_attrs): req_data_new = dict([(k, v) for k, v in req_data.items() if not k.startswith('Attribute.')]) i = 1 for k, v in forward_attrs.items(): req_data_new['Attribute.%s.Name' % i] = [k] req_data_new['Attribute.%s.Value' % i] = [v] i += 1 data = urlencode(req_data_new, doseq=True) return Request(data=data, headers=headers, method=method)
def update_s3(method, path, data, headers, response=None, return_forward_info=False): if return_forward_info: modified_data = None # If this request contains streaming v4 authentication signatures, strip them from the message # Related isse: https://github.com/atlassian/localstack/issues/98 # TODO we should evaluate whether to replace moto s3 with scality/S3: # https://github.com/scality/S3/issues/237 if headers.get('x-amz-content-sha256') == 'STREAMING-AWS4-HMAC-SHA256-PAYLOAD': modified_data = strip_chunk_signatures(data) # persist this API call to disk persistence.record('s3', method, path, data, headers) parsed = urlparse.urlparse(path) query = parsed.query path = parsed.path bucket = path.split('/')[1] query_map = urlparse.parse_qs(query) if method == 'PUT' and (query == 'notification' or 'notification' in query_map): tree = ET.fromstring(data) queue_config = tree.find('{%s}QueueConfiguration' % XMLNS_S3) if len(queue_config): S3_NOTIFICATIONS[bucket] = { 'Id': get_xml_text(queue_config, 'Id'), 'Event': get_xml_text(queue_config, 'Event', ns=XMLNS_S3), 'Queue': get_xml_text(queue_config, 'Queue', ns=XMLNS_S3), 'Topic': get_xml_text(queue_config, 'Topic', ns=XMLNS_S3), 'CloudFunction': get_xml_text(queue_config, 'CloudFunction', ns=XMLNS_S3) } if query == 'cors' or 'cors' in query_map: if method == 'GET': return get_cors(bucket) if method == 'PUT': return set_cors(bucket, data) if method == 'DELETE': return delete_cors(bucket) if modified_data: return Request(data=modified_data, headers=headers) return True # get subscribers and send bucket notifications if method in ('PUT', 'DELETE') and '/' in path[1:]: parts = path[1:].split('/', 1) bucket_name = parts[0] object_path = '/%s' % parts[1] send_notifications(method, bucket_name, object_path) # append CORS headers to response if response: parsed = urlparse.urlparse(path) bucket_name = parsed.path.split('/')[0] append_cors_headers(bucket_name, request_method=method, request_headers=headers, response=response)
def forward_request(self, method, path, data, headers): if method == 'OPTIONS': return 200 req_data = None if method == 'POST' and path == '/': req_data = urlparse.parse_qs(to_str(data)) action = req_data.get('Action')[0] if action == 'CreateStack': stack_name = req_data.get('StackName')[0] event_publisher.fire_event( event_publisher.EVENT_CLOUDFORMATION_CREATE_STACK, payload={'n': event_publisher.get_hash(stack_name)}) if action == 'DescribeStackEvents': # fix an issue where moto cannot handle ARNs as stack names (or missing names) stack_name = req_data.get('StackName') run_fix = not stack_name if stack_name: stack_name = stack_name[0] if stack_name.startswith('arn:aws:cloudformation'): run_fix = True stack_name = re.sub( r'arn:aws:cloudformation:[^:]+:[^:]+:stack/([^/]+)(/.+)?', r'\1', stack_name) if run_fix: stack_names = [ stack_name ] if stack_name else self._list_stack_names() client = aws_stack.connect_to_service('cloudformation') events = [] for stack_name in stack_names: tmp = client.describe_stack_events( StackName=stack_name)['StackEvents'][:1] events.extend(tmp) events = [{'member': e} for e in events] response_content = '<StackEvents>%s</StackEvents>' % obj_to_xml( events) return make_response('DescribeStackEvents', response_content) if req_data: if action == 'ValidateTemplate': return validate_template(req_data) if action == 'CreateStack': modified_request = transform_template(req_data) if modified_request: req_data.pop('TemplateURL', None) req_data['TemplateBody'] = json.dumps(modified_request) data = urlparse.urlencode(req_data, doseq=True) return Request(data=data, headers=headers, method=method) return True
def generate_and_decode_token(public_key, config_file): request = get_auth(config_file)(Request()) assert "Authorization" in request.headers (authtype, token) = request.headers["Authorization"].decode("utf-8").split() assert authtype == "Bearer" return jwt.decode(token, public_key, algorithms=["RS256"], audience="webapp")
def forward_request(self, method, path, data, headers): action = headers.get("X-Amz-Target") or "" action = action.split(".")[-1] if action == "PutLogEvents": publish_log_metrics_for_events(data) if method == "POST" and path == "/": if "nextToken" in to_str(data or ""): data = self._fix_next_token_request(data) headers["Content-Length"] = str(len(data)) return Request(data=data, headers=headers, method=method) return True
def forward_request(self, method, path, data, headers): if method == 'POST' and path == '/': req_data = urlparse.parse_qs(to_str(data)) if 'QueueName' in req_data: encoded_data = urlencode(req_data, doseq=True) request = Request(data=encoded_data, headers=headers, method=method) return request return True
def get(self, endpoint, page, page_size, params=None): params = params or {} params.update({ 'page': page, 'page_size': page_size, }) url = '{scheme}://{host}/api/v2{endpoint}'.format(scheme=self.SCHEME, host=self.HOST, endpoint=endpoint) request = Request('GET', url, params=params) request = request.prepare() unix_date = self.get_unix_date() signature = self.compute_signature(request.path_url, unix_date) request.headers.update({ 'X-Brandstem-Date': unix_date, 'X-Brandstem-Access-Id': self.access_id, 'X-Brandstem-Signature': signature, }) return request
def test_serialize_prepared_request(self): r = Request() r.method = "GET" r.url = "http://example.com" r.headers = {"User-Agent": "betamax/test header"} r.data = {"key": "value"} p = r.prepare() serialized = util.serialize_prepared_request(p, False) assert serialized is not None assert serialized != {} assert serialized["method"] == "GET" assert serialized["uri"] == "http://example.com/" assert serialized["headers"] == { "Content-Length": ["9"], "Content-Type": ["application/x-www-form-urlencoded"], "User-Agent": ["betamax/test header"], } assert serialized["body"]["string"] == "key=value"
def test_serialize_prepared_request(self): r = Request() r.method = 'GET' r.url = 'http://example.com' r.headers = {'User-Agent': 'betamax/test header'} r.data = {'key': 'value'} p = r.prepare() serialized = util.serialize_prepared_request(p, False) assert serialized is not None assert serialized != {} assert serialized['method'] == 'GET' assert serialized['uri'] == 'http://example.com/' assert serialized['headers'] == { 'Content-Length': ['9'], 'Content-Type': ['application/x-www-form-urlencoded'], 'User-Agent': ['betamax/test header'], } assert serialized['body']['string'] == 'key=value'
def create_request(user, dep_p_lat, dep_p_long, dep_ran, ar_p_lat, ar_p_long, ar_ran, ar_time, max_del, nb_seats, cancel_margin): r = Request() r.user = user r.departure_point_lat = dep_p_lat r.departure_point_long = dep_p_long r.departure_range = dep_ran r.arrival_point_lat = ar_p_lat r.arrival_point_long = ar_p_long r.arrival_range = ar_ran r.arrival_time = ar_time r.max_delay = max_del r.nb_requested_seats = nb_seats r.cancellation_margin = cancel_margin r.status = 'P' r.save() match_request(r.id)
def process_response(self, request, response): req = Request() req.status_code = response.status_code req.host = request.get_host() req.path = request.path req.user_agent = request.META.get('HTTP_USER_AGENT', '') req.language = request.META.get('HTTP_ACCEPT_LANGUAGE', '') req.timezone = request.META.get('TZ', '') req.remote_address = request.META.get('REMOTE_ADDR', '') req.referer = request.META.get('HTTP_REFERER', '') req.method = request.method req.POST = json.dumps(request.POST) if request.POST else u'{}' req.GET = json.dumps(request.GET) if request.COOKIES else u'{}' req.cookies = json.dumps(request.COOKIES) if request.COOKIES \ else u'{}' req.is_secure = request.is_secure() req.is_ajax = request.is_ajax() if getattr(request, 'user', None): if request.user.__class__ is User \ and request.user.is_authenticated(): req.user = request.user req.save() return response