def test_http_response(): request = Request() request.headers = { 'Authorization': 'token', 'header1': 'value1', 'header2': 'value2' } request.method = 'GET' request.url = 'http://url.com' request.body = None response = HttpResponse() response.status_code = 400 response.request = request assert response.to_curl(request) == ( "curl -X 'GET' -v -H 'Authorization: <...>' " "-H 'header1: value1' -H 'header2: value2' " "'http://url.com'") assert sorted( response.hide_and_serialize_sensitive_headers( request.headers).split('\n')) == [ '', 'Authorization: <...>', 'header1: value1', 'header2: value2' ] with pytest.raises(ExtendedHTTPError) as exc_info: # ensure error is raised response.raise_for_status() assert exc_info.value.response == response assert exc_info.value.request == request
def _send_request(method, url, headers, body): """发送请求""" s = Session() prepped = Request(method, url).prepare() prepped.headers = headers prepped.body = body r = s.send(prepped) return r.status_code, r.text
def main(): file = None with open(r'E:\MyDesktop\default_avatar_female_50.gif', 'rb') as f: file = f.read() fileMd5 = hashlib.md5(file).hexdigest() date = httpdate_rfc1123() uri = '/image-upyun-9527/3.webp' method = 'PUT' headers = { 'Authorization': sign(key, secret, method, uri, date), 'Date': date, 'Content-Length': str(len(file)), 'x-gmkerl-thumb': '/format/webp/quality/85/progressive/true/strip/true' } print(headers) from requests import Session, Request s = Session() prepped = Request(method, 'http://v0.api.upyun.com' + uri).prepare() prepped.headers = headers prepped.body = file r = s.send(prepped) print(r.status_code, r.text)
def lambda_handler(event, context): pp.pprint(event) aws_sns_topic_arn = event['sns'] url = event['url'] method = event.get('method', 'GET') headers = event.get('headers') body = event.get('body') session = Session() request = Request(method, url).prepare() if headers is not None: request.headers = headers if body is not None: request.body = body response = session.send(request) if response.status_code == 200: content = response.text pp.pprint(content) publish_command_to_sns(aws_sns_topic_arn, content) else: pp.pprint(response)
def main(): file = None with open( r'C:\Users\Steven Fang\Documents\Tencent Files\1075004549\Image\Group\{SS]6F@`F[F6WY~[%{F`C_N.gif', 'rb') as f: file = f.read() fileMd5 = hashlib.md5(file).hexdigest() date = httpdate_rfc1123() uri = '/image-upyun-9527/3.webp' method = 'PUT' headers = { 'Authorization': sign(key, secret, method, uri, date), 'Date': date, 'Content-Length': str(len(file)), 'x-gmkerl-thumb': '/format/webp/quality/85/progressive/true/strip/true' } print(headers) from requests import Session, Request s = Session() prepped = Request(method, 'http://v0.api.upyun.com' + uri).prepare() prepped.headers = headers prepped.body = file r = s.send(prepped) print(r.status_code, r.text)
def test_signature_generation_for_iam(self): """ Test the dictionary returned by AWSProfileAuth which is used in `auth` input to request sent to AWS API Gateway. This dict should contain signature values used by AWS API Gateway Resource Policy to determine access to API from HTTP request. This test just confirms the override functionality we needed to create to support AWS_PROFILE. By default, aws_requests_auth doesn't support this directly. """ # Mock request object, needed for signature generation r = Request('POST', "https://123456780.execute-api.us-west-2.amazonaws.com", json={'key': 'value'}) r.prepare() r.body = "test-text" sig_generation_without_profile = kubectl_hyperkube.AWSProfileAuth( aws_host="https://123456780.execute-api.us-west-2.amazonaws.com", aws_region='us-west-2', aws_service='execute-api', profile=None) sig_without_profile_result = ( sig_generation_without_profile.get_aws_request_headers( r, aws_access_key="fffasdfdfadadsfdkaf101010", aws_secret_access_key="akdsfjasdfwiqer;s123k122", aws_token="testingtokenaklzaner")) assert "Credential=fffasdfdfadadsfdkaf101010" in ( sig_without_profile_result['Authorization']) assert "us-west-2/execute-api/aws4_request" in ( sig_without_profile_result['Authorization']) assert ("SignedHeaders=host;x-amz-date;x-amz-security-token" in (sig_without_profile_result['Authorization'])) assert ( "b18939c1891ba923a4d46ccf146612094490300d22e436bf5a5d6d46d99e4225" in ( # noqa sig_without_profile_result['x-amz-content-sha256'])) assert sig_without_profile_result['X-Amz-Security-Token'] == ( "testingtokenaklzaner") # requires ~/.aws/config to have a `[default]` profile sig_generation_with_profile = kubectl_hyperkube.AWSProfileAuth( aws_host="https://123456780.execute-api.us-west-2.amazonaws.com", aws_region='us-west-2', aws_service='execute-api', profile="default") sig_with_profile_result = ( sig_generation_with_profile.get_aws_request_headers( r, aws_access_key="fffasdfdfadadsfdkaf102381", aws_secret_access_key="akdsfjasdfwiqer;sfkjk213", aws_token="testingtokenakldsfkja;")) assert "Credential=fffasdfdfadadsfdkaf102381" in ( sig_with_profile_result['Authorization']) assert "us-west-2/execute-api/aws4_request" in ( sig_with_profile_result['Authorization']) assert ("SignedHeaders=host;x-amz-date;x-amz-security-token" in (sig_with_profile_result['Authorization'])) assert ( "b18939c1891ba923a4d46ccf146612094490300d22e436bf5a5d6d46d99e4225" in ( # noqa sig_with_profile_result['x-amz-content-sha256'])) assert sig_with_profile_result['X-Amz-Security-Token'] == ( "testingtokenakldsfkja;")
def main(): parser = argparse.ArgumentParser(prog='cmsRWSHelper') parser.add_argument( '-v', '--verbose', action='store_true', help="tell on stderr what's happening") # FIXME It would be nice to use '--rankings' with action='store' # and nargs='+' but it doesn't seem to work with subparsers... parser.add_argument( '-r', '--ranking', dest='rankings', action='append', default=None, choices=list(xrange(len(config.rankings_address))), metavar='shard', type=int, help="select which RWS to connect to (omit for 'all')") subparsers = parser.add_subparsers( title='available actions', metavar='action', help='what to ask the RWS to do with the entity') # Create the parser for the "get" command parser_get = subparsers.add_parser('get', help="retrieve the entity") parser_get.set_defaults(action='get') # Create the parser for the "create" command parser_create = subparsers.add_parser('create', help="create the entity") parser_create.set_defaults(action='create') parser_create.add_argument( 'file', type=argparse.FileType('rb'), help="file holding the entity body to send ('-' for stdin)") # Create the parser for the "update" command parser_update = subparsers.add_parser('update', help='update the entity') parser_update.set_defaults(action='update') parser_update.add_argument( 'file', type=argparse.FileType('rb'), help="file holding the entity body to send ('-' for stdin)") # Create the parser for the "delete" command parser_delete = subparsers.add_parser('delete', help='delete the entity') parser_delete.set_defaults(action='delete') # Create the group for entity-related arguments group = parser.add_argument_group( title='entity reference') group.add_argument( 'entity_type', action='store', choices=ENTITY_TYPES, metavar='type', help="type of the entity (e.g. contest, user, task, etc.)") group.add_argument( 'entity_id', action='store', type=six.text_type, metavar='id', help='ID of the entity (usually a short codename)') # Parse the given arguments args = parser.parse_args() args.entity_id = quote(args.entity_id) if args.verbose: verb = args.action[:4] + 'ting' logger.info("%s entity '%ss/%s'" % (verb.capitalize(), args.entity_type, args.entity_id)) if args.rankings is not None: shards = args.rankings else: shards = list(xrange(len(config.rankings_address))) s = Session() error = False for shard in shards: url, username, password = get_parameters( shard, args.entity_type, args.entity_id) if args.verbose: logger.info( "Preparing %s request to %s (username: %s; password: %s)" % (ACTION_METHODS[args.action], url, username, password)) req = Request(ACTION_METHODS[args.action], url, auth=(username, password)).prepare() if hasattr(args, 'file'): if args.verbose: logger.info("Reading file contents to use as message body") req.body = args.file.read() if args.verbose: logger.info("Sending request") try: res = s.send(req, verify=config.https_certfile) except RequestException as e: logger.error("Failed") logger.info(repr(e)) error = True continue if args.verbose: logger.info("Response received") if res.status_code != (201 if args.action == "create" else 200): logger.error("Unexpected status code: %d" % res.status_code) error = True continue if args.action == "get": print(res.content) if error: sys.exit(1)