Exemplo n.º 1
0
def lambda_handler(event, context):
    # Autorize
    url = "https://api.mgmt.cloud.vmware.com/iaas/api/login"
    payload = "{\n\t\"refreshToken\": \""+auth_token+"\"\n}"
    headers = {
    'Content-Type': 'application/json'
    }
    response = requests.request("POST", url, headers=headers, data = payload)
    data = response.json()
    token = (data['token'])
    #print ("Token : "+token)
    
    #Request 
    url = "https://api.mgmt.cloud.vmware.com/pipeline/api/pipelines/"+pipeline+"/executions"
    headers = {
    'Content-Type': 'application/json',
    'Authorization': 'Bearer '+token
    }
    response = requests.request("POST", url, headers=headers, data = payload)
    #print(response)
    
    return {
        'statusCode': 200,
        'body': json.dumps('Demo Env comming up!')
    }
Exemplo n.º 2
0
    def test_3_from_requests_error(self):

        req = Request(
            method='GET',
            url='%s/get' % EXAMPLE_ORIGIN)

        with self.assertRaises(RequestException):
            requests.request(**vars(req))
    def submit_file(self, filename, filepath, analysis_callback_url):
        json_response = {"error": "file not available"}

        print("Submit file > filename:{0} @ path: {1}".format(
            filename, filepath))

        headers = {
            "filename": filename,
            "callbackurl": analysis_callback_url,
            "apikey": self.apikey,
            "content-type": "application/octet-stream",
            "rule": "sanitize"
        }

        before_submission = datetime.datetime.now()
        endpoint_details = self.api_endpoints["submit_file"]
        metadefender_url = self.server_url + endpoint_details["endpoint"]

        if self.supports_dowload_file:
            # MetaDefender Cloud supports downloadfrom URL, therefore the payload will not be sent
            headers["downloadfrom"] = filepath
            response = requests.request(endpoint_details["type"],
                                        metadefender_url,
                                        headers=headers,
                                        timeout=(2, 30))
        else:
            with open(filepath, 'rb') as payload:
                response = requests.request(endpoint_details["type"],
                                            metadefender_url,
                                            data=payload,
                                            headers=headers,
                                            timeout=(2, 30))

        json_response = json.loads(response.text)

        print("MetaDefender response: {0}".format(json_response))

        http_status = response.status_code
        total_submission_time = datetime.datetime.now() - before_submission

        print(
            "{timestamp} {name} >> time: {total_time}, http status: {status}, response: {id}"
            .format(timestamp=before_submission,
                    name=filename,
                    total_time=total_submission_time,
                    status=http_status,
                    id=response.text))

        json_response["status"] = "ok" if ('data_id'
                                           in json_response) else "failed"
        return json_response
def get_content(e):
    data = f""
    _t = ""
    _m_verb = "GET"
    api_path = e["requestContext"]["resourcePath"]
    logger.debug(f"api_path:{api_path}")

    if api_path == "/content/authorized-read" or api_path == "/content/authorized-write":
        _t = _cog_auth_token(api_path.split("-")[1])

    if api_path == "/content/authorized-write":
        _m_verb = "POST"

    try:
        resp = requests.request(_m_verb,
                                global_args.PREMIUM_CONTENT_API_URL,
                                headers={"Authorization": _t})
        logger.debug(f"ResData:{resp.text}")
        data = json.loads(resp.text)
        if "message" in data:
            data = data["message"]
    except Exception as e:
        logger.error(f"{str(e)}")

    if not data:
        data = "Something Obviously went wrong, Let me check"
    logger.debug(data)
    return data
Exemplo n.º 5
0
    def get_distance_matrix(input_origins, input_destinations):
        user_location_seperator = ','
        destinations_seperator = '|'

        input_origins = [str(value) for (key, value) in input_origins.items()]
        origins = user_location_seperator.join(input_origins)

        destinations = ''
        for input_destination in input_destinations:
            input_destination = [
                str(value) for (key, value) in input_destination.items()
            ]
            destinations += user_location_seperator.join(
                input_destination) + destinations_seperator
        destinations = destinations[:-1]

        querystring = {
            "units": "metric",
            "origins": origins,
            "destinations": destinations,
            "key": API_KEY
        }

        response = requests.request("GET",
                                    GOOGLE_DISTANCE_MATRIX_ENDPOINT,
                                    params=querystring)
        return response.json()
Exemplo n.º 6
0
def lambda_handler(event, context):
    client = boto3.client('rekognition')
    print(client)
    for record in event['Records']:
        bucket = record['s3']['bucket']['name']
        key = record['s3']['object']['key']
        print(key)
        label_res = client.detect_labels(
            Image={'S3Object': {
                'Bucket': bucket,
                'Name': key
            }},
            MaxLabels=100,
            MinConfidence=50)
        print('1')
        labels = [label['Name'] for label in label_res['Labels']]
        print(labels)
        fields = {
            'objectKey': key,
            'bucket': bucket,
            'createdTimestamp': time.time(),
            'labels': labels
        }
        response = requests.request('POST',
                                    es_domian,
                                    headers=headers,
                                    data=json.dumps(fields))
        print(response.json())
    # TODO implement
    return {'statusCode': 200, 'body': json.dumps('Hello from Lambda!')}
def yelp(cuisine):
    url = "https://api.yelp.com/v3/businesses/search"
    payload = ""
    headers = {'Authorization': 'Bearear Auth'}

    recommendation = []
    for i in range(10):
        requestData = {
            "term": cuisine + ", restaurants",
            "location": 'Manhattan',
            "categories": "Food",
            "limit": "50",
            "offset": 50 * i
        }

        response = requests.request("GET",
                                    url,
                                    data=payload,
                                    headers=headers,
                                    params=requestData)
        message = json.loads(response.text)

        if len(message['businesses']) < 1:
            return []

        recommendation += message['businesses']

    return recommendation
def pce_request(pce,
                org_id,
                key,
                secret,
                verb,
                path,
                params=None,
                data=None,
                json=None,
                extra_headers=None):
    base_url = os.path.join(pce, 'orgs', org_id)
    headers = {
        'user-agent': 'aws-lambda-quarantine',
    }
    print(base_url)
    if extra_headers:
        headers.update(extra_headers)
        print(headers)
    if json:
        print(json)
    response = requests.request(verb,
                                os.path.join(base_url, path),
                                auth=(key, secret),
                                headers=headers,
                                params=params,
                                json=json,
                                data=data)
    return response
Exemplo n.º 9
0
def yelp_api(request):

    url = "https://api.yelp.com/v3/businesses/search"
    query = request

    payload = ""
    headers = {'Authorization': "Bearer --", 'cache-control': "no-cache"}

    response = requests.request("GET",
                                url,
                                data=payload,
                                headers=headers,
                                params=request)

    message = json.loads(response.text)

    if len(message['businesses']) < 0:
        return 'We were unable to find any restaurants.'

    finalStr = "Hello! These are my " + request[
        'categories'] + " restaurant suggestions for " + request[
            'peoplenum'] + " people, for " + request[
                'Date'] + " at " + request['Time'] + ". "
    count = 1
    for business in message['businesses']:
        finalStr = finalStr + " " + str(count) + "." + business[
            'name'] + ", located at " + business['location']['address1'] + " "
        count += 1

    return final
Exemplo n.º 10
0
def jira_handler(user_id):
    jira_token = "XXXXXXXXXXXXXXXXXXX"
    user_info = get_user_info(user_id)
    user_profile = user_info["profile"]
    username = user_profile["display_name"]
    email = user_profile["email"]
    
    url = "https://sunilbansiwal.atlassian.net/rest/api/3/user"

    auth = HTTPBasicAuth("*****@*****.**", jira_token)
    
    headers = {
      "Accept": "application/json",
      "Content-Type": "application/json"
    }
    
    payload = dumps( {
      "emailAddress": "*****@*****.**",
      "displayName": username,
    })
    
    response = requests.request(
      "POST",
      url,
      data=payload,
      headers=headers,
      auth=auth
    )
    
    print("Jira reponse : ", response.text)
 
    reponse = dumps(loads(response.text), sort_keys=True, indent=4, separators=(",", ": "))
    json_response = loads(reponse)
    return json_response
Exemplo n.º 11
0
def github_handler(username, user_id):
    git_token = "XXXXXXXXXXXXXXXXXXX"
    url = "https://api.github.com/orgs/test-webhookevents/memberships/" + str(username)
    #url = "https://api.github.com/orgs/test-webhook-events/members"

    headers = {
      "Accept": "application/json",
      "Content-Type": "application/json",
      "Authorization": "Bearer " + git_token
    }
    
    payload = dumps( {
      "role": "member"
    })
    
    response = requests.request(
      "PUT",
      url,
      data=payload,
      headers=headers
    )
    
    return {
        "isBase64Encoded": True,
        "statusCode": 200,
        "body": dumps(loads(response.text), sort_keys=True, indent=4, separators=(",", ": ")),
        "headers": { }
    }
Exemplo n.º 12
0
def restaurantApiCall(requestData):

    url = "https://api.yelp.com/v3/businesses/search"

    querystring = requestData

    payload = ""
    headers = {
        'Authorization':
        'Bearer 5SzEAKiD8ZnWoWKRihJy4cQicMDlTQx4aVUeWo_jXA9Pw4bkQvXFbyQtYz6Xqo-n3v2enO5FT1Tl8wrmGfKw8kiXgR0PoJENhxWF8YSUk8kcWmM0c9PeFBsc2keEXHYx'
    }

    response = requests.request("GET",
                                url,
                                data=payload,
                                headers=headers,
                                params=querystring)
    message = json.loads(response.text)

    if len(message['businesses']) < 0:
        return 'There is no restaurants under this description'

    textString = "Hey! Here are our " + requestData[
        'categories'] + " restaurant suggestions for " + requestData[
            'peoplenum'] + " people, for " + requestData[
                'Date'] + " at " + requestData['Time'] + ". "
    count = 1
    for business in message['businesses']:
        textString = textString + " " + str(
            count) + ") " + business['name'] + ", " + business['location'][
                'address1'] + ", " + business['phone']
        count += 1

    textString = textString + ". Have a great day!"
    return textString
Exemplo n.º 13
0
def get_auth_token(globalVars):
    url = "https://%s.redlock.io/login" % (tenant)
    headers = {'Content-Type': 'application/json'}
    payload = json.dumps(globalVars)
    response = requests.request("POST", url, headers=headers, data=payload)
    token = response.json()['token']
    return token
Exemplo n.º 14
0
def get_everything(coord):
    url = "https://api3.geo.admin.ch/rest/services/api/MapServer/identify"
    y = str(coord[0])
    x = str(coord[1])
    querystring = {
        "geometryType": "esriGeometryPoint",
        "returnGeometry": "false",
        "layers": "all:ch.bfe.solarenergie-eignung-daecher",
        "geometry": str(x + "," + y),
        "mapExtent": str(x + "," + y + "," + x + "," + y),
        "imageDisplay": "532,360,96",
        "tolerance": "1",
        "order": "distance",
        "lang": "de"
    }
    payload = ""
    user_agent = "Mozilla/5.0 (Windows NT 6.1; rv:5.0) Gecko/20100101 Firefox/5.02"
    headers = {'User-Agent': user_agent}
    response = requests.request("GET",
                                url,
                                data=payload,
                                headers=headers,
                                params=querystring)

    return json.loads(response.text)
Exemplo n.º 15
0
def lambda_handler(event, context):
    user_name = event["queryStringParameters"]["screen_name"]
    tweet_id = event["queryStringParameters"]["id"]
    tweet_url = f'https://twitter.com/{user_name}/status/{tweet_id}'
    url_parameters = {
        "url": tweet_url,
        "hide_threat": "true",
        "align": "center",
        "maxwidth": "550"
    }

    response = requests.request("GET",
                                url,
                                data="",
                                headers=headers,
                                params=url_parameters)

    return {
        "statusCode": 200,
        "headers": {
            'Content-Type': 'application/json',
            'Access-Control-Allow-Origin': '*'
        },
        "body": json.dump(response.text)
    }
Exemplo n.º 16
0
def restaurant_api_call(request_data):
    url = "https://api.yelp.com/v3/businesses/search"

    querystring = request_data

    payload = ""
    headers = {
        'Authorization':
        "Bearer m68Jb9xYu4eUQH0RKbjlFGOj6lzCEEdExprjLAj3Bw8inSDYbODwF1EO13wr1QXaz68XUeoB-Ay-yxwaC4y1KqqHOWc6towlxTvyAXKooWHtYAepY4okWAbeP1SlXHYx",
        'cache-control': "no-cache"
    }

    response = requests.request("GET",
                                url,
                                data=payload,
                                headers=headers,
                                params=querystring)

    message = json.loads(response.text)

    if len(message['businesses']) < 0:
        return 'Unable to find restaurants'

    textString = "Hello! These are my " + request_data[
        'categories'] + " restaurant suggestions for " + request_data[
            'peoplenum'] + " people, for " + request_data[
                'Date'] + " at " + request_data['Time'] + ". "
    count = 1
    for business in message['businesses']:
        textString = textString + " " + str(count) + "." + business[
            'name'] + ", located at " + business['location']['address1'] + " "
        count += 1

    textString = textString + " Enjoy your meal!"
Exemplo n.º 17
0
def sendEmail(email, room):
    # send email using sendgrid
    print("Sending email...")
    jsonData = {
        "personalizations": [{
            "to": [{
                "email": email
            }],
            "dynamic_template_data": {
                "roomNo": room,
            }
        }],
        "from": {
            "email": "*****@*****.**",
            "name": "Ganga Hostel Mailbox"
        },
        "template_id":
        SENDGRID_TEMPLATE_ID
    }
    payload = json.dumps(jsonData)
    authHeader = "Bearer " + SENDGRID_API_KEY
    headers = {
        'content-type': "application/json",
        'authorization': authHeader,
    }

    url = "https://api.sendgrid.com/v3/mail/send"
    response = requests.request("POST", url, data=payload, headers=headers)
    print(response.text)
Exemplo n.º 18
0
def request(host, path, api_key, url_params=None):
    """Given your API_KEY, send a GET request to the API.

    Args:
        host (str): The domain host of the API.
        path (str): The path of the API after the domain.
        API_KEY (str): Your API Key.
        url_params (dict): An optional set of query parameters in the request.

    Returns:
        dict: The JSON response from the request.

    Raises:
        HTTPError: An error occurs from the HTTP request.
    """
    url_params = url_params or {}
    url = '{0}{1}'.format(host, quote(path.encode('utf8')))
    headers = {
        'Authorization': 'Bearer %s' % api_key,
    }

    print(u'Querying {0} ...'.format(url))

    response = requests.request('GET', url, headers=headers, params=url_params)

    return response.json()
Exemplo n.º 19
0
def find_restaurant(message):
    # Yelp Fusion no longer uses OAuth as of December 7, 2017.
    # You no longer need to provide Client ID to fetch Data
    # It now uses private keys to authenticate requests (API Key)
    # You can find it on
    # https://www.yelp.com/developers/v3/manage_app

    API_KEY = '1d0HZ4tOdS7Lgyh3LOyFmyXU76WsbScZjt03awEvsrkABOTO-BytlmJrb1gA2t3MCaAt8EunBgDozMKF4BrY4DNMWPyVuhzxaOvuu8chnnaCDiPOrwrmzx7f8HjnW3Yx'

    # API constants, you shouldn't have to change these.
    API_HOST = 'https://api.yelp.com'
    SEARCH_PATH = '/v3/businesses/search'
    BUSINESS_PATH = '/v3/businesses/'  # Business ID will come after slash.

    # Defaults for our simple example.
    DEFAULT_TERM = 'restaurant'
    DEFAULT_LOCATION = 'Manhanttan'
    SEARCH_LIMIT = 5

    url_params = {
        'term': DEFAULT_TERM,
        'location': message['MealLocation'],
        'categories': message['MealCuisine'],
        'limit': SEARCH_LIMIT
    }

    url = API_HOST + SEARCH_PATH

    headers = {
        'Authorization': 'Bearer ' + API_KEY,
    }

    response = requests.request('GET', url, headers=headers, params=url_params)

    return response.json()
Exemplo n.º 20
0
def restaurantApiCall(requestData):

    url = "https://api.yelp.com/v3/businesses/search"

    querystring = requestData

    payload = ""
    headers = {
        'Authorization':
        "Bearer 2bmxTzMXxwdNuU031BYWHhr3oM7u3SNqagh4OEho0e7HHGWDf-kniHdBVrnAYi1Yn4j4ipZ__lm5uStqOTklsCO07mVXj7oGKRR54LOMFQ8V_mYJmrOtFPK7WwaPXHYx",
        'cache-control': "no-cache"
    }

    response = requests.request("GET",
                                url,
                                data=payload,
                                headers=headers,
                                params=querystring)
    message = json.loads(response.text)

    if len(message['businesses']) < 0:
        return 'Could not find any restaurants'

    textString = "Hello! These are my " + requestData[
        'categories'] + " restaurant suggestions for " + requestData[
            'peoplenum'] + " people, for " + requestData[
                'Date'] + " at " + requestData['Time'] + ". "
    count = 1
    for business in message['businesses']:
        textString = textString + " " + str(count) + "." + business[
            'name'] + ", located at " + business['location']['address1'] + " "
        count += 1

    textString = textString + " Enjoy your food!"
    return textString
Exemplo n.º 21
0
def yelpApiCall(requestData):

    url = "https://api.yelp.com/v3/businesses/search"

    querystring = requestData

    payload = ""
    headers = {
        'Authorization':
        "Bearer 7NjA90modOdaeEn6bLkfmOoy3YIibnWpCUki41GqXzW5z0nlxHPwRpjXeAJ1ycwHd0qeiipWT-9vtxH-WcSdM5zj9TcHhJrEzW6n_4tuQCS5YHUOnmvg_Ax4KYmKXHYx",
        'cache-control': "no-cache",
        'Postman-Token': "d1b24c2d-4f0d-4a67-b5fa-48f40f6fa447"
    }

    response = requests.request("GET",
                                url,
                                data=payload,
                                headers=headers,
                                params=querystring)
    message = json.loads(response.text)

    if len(message['businesses']) <= 0:
        return []

    return message['businesses']
Exemplo n.º 22
0
def restaurantApiCall(requestData):

    url = "https://api.yelp.com/v3/businesses/search"

    querystring = requestData

    payload = ""
    headers = {
        'Authorization':
        "Bearer aou0be_EWze5tuimQZY8bAV_gGU3EemoYqjkuQp1OoOipAAwIwRvGH8j0Q3tXE88u8oGWgINl0Id-a0EBxLzCKu8m1PNN9SH_uTX_yiZPlrKtvNl9_CsaV34R-CNXHYx",
        'cache-control': "no-cache"
    }

    response = requests.request("GET",
                                url,
                                data=payload,
                                headers=headers,
                                params=querystring)
    message = json.loads(response.text)

    if len(message['businesses']) < 0:
        return 'Unable to find restaurants'

    textString = "Hello! These are my " + requestData[
        'categories'] + " restaurant suggestions for " + requestData[
            'peoplenum'] + " people, for " + requestData[
                'Date'] + " at " + requestData['Time'] + ". "
    count = 1
    for business in message['businesses']:
        textString = textString + " " + str(count) + "." + business[
            'name'] + ", located at " + business['location']['address1'] + " "
        count += 1

    textString = textString + " Enjoy your meal!"
    return textString
def disapproval_message(user_id, user_type, tool):
    url = "https://slack.com/api/chat.postMessage"

    headers = {
        "Content-type": "application/json",
        "Accept": "application/json",
        "Authorization": "Bearer " + access_token
    }

    data = {
        "channel":
        user_id,
        "text":
        user_type + " has disapproved your request for `" + tool + "` access"
    }

    response = requests.request("POST", url, headers=headers, data=dumps(data))

    response = dumps(loads(response.text),
                     sort_keys=True,
                     indent=4,
                     separators=(",", ": "))
    json_response = loads(response)
    #print(json_response)
    return json_response
def request_manager(payload):
    manager_info = get_user_info("U015UKJKXNW")
    manager_profile = manager_info["profile"]

    user_info = get_user_info(payload["user"]["id"])
    user_profile = user_info["profile"]

    accessTool = payload["actions"][0]["name"]
    url = "https://slack.com/api/chat.postMessage"

    headers = {
        "Content-type": "application/json",
        "Accept": "application/json",
        "Authorization": "Bearer " + access_token
    }

    data = {
        "channel":
        "U015UKJKXNW",
        "text":
        "Hi " + manager_profile["real_name"],
        "attachments": [{
            #"text": user_profile["real_name"] + " wants " + payload["actions"][0]["name"] + " access",
            "text":
            "<@" + payload["user"]["id"] + ">" + " wants `" +
            payload["actions"][0]["name"] + "` access",
            "fallback":
            "Shame... buttons aren't supported in this land",
            "callback_id":
            payload["user"]["id"],
            "color":
            "#3AA3E3",
            "attachment_type":
            "default",
            "actions": [{
                "name": "approve",
                "text": "Approve",
                "type": "button",
                "value": accessTool,
                "style": "primary"
            }, {
                "name": "disapprove",
                "text": "Disapprove",
                "type": "button",
                "value": accessTool,
                "style": "danger"
            }]
        }]
    }

    response = requests.request("POST", url, headers=headers, data=dumps(data))

    response = dumps(loads(response.text),
                     sort_keys=True,
                     indent=4,
                     separators=(",", ": "))
    json_response = loads(response)
    #print(json_response)
    return json_response
Exemplo n.º 25
0
def get_coin_price(currency1, currency2, exchange, api_key):
    url = 'https://min-api.cryptocompare.com/data/price?fsym={}&tsyms={}&api_key={}&e={}'.format(
        currency1, currency2, api_key, exchange)

    headers = {'Content-Type': "application/json"}
    response = requests.request("GET", url, headers=headers).json()

    return response
Exemplo n.º 26
0
def request(host, path, api_key, url_params=None):
    url_params = url_params or {}
    url = '{0}{1}'.format(host, urllib.parse.quote(path.encode('utf8')))
    headers = {
        'Authorization': 'Bearer %s' % api_key,
    }
    response = requests.request('GET', url, headers=headers, params=url_params)
    return response.json()
def request_admin(payload):
    admin_info = get_user_info("U015QP5QHN0")
    admin_profile = admin_info["profile"]

    user_id = payload["original_message"]["attachments"][0]["callback_id"]
    username = payload["original_message"]["attachments"][0]["fallback"]
    message = payload["original_message"]["attachments"][0]["text"]
    url = "https://slack.com/api/chat.postMessage"

    accessTool = payload["actions"][0]["value"]

    headers = {
        "Content-type": "application/json",
        "Accept": "application/json",
        "Authorization": "Bearer " + access_token
    }

    data = {
        "channel":
        "U015QP5QHN0",
        "text":
        "Hi " + admin_profile["real_name"],
        "attachments": [{
            "text":
            message,
            "fallback":
            username,
            "callback_id":
            user_id,
            "color":
            "#3AA3E3",
            "attachment_type":
            "default",
            "actions": [{
                "name": "approve",
                "text": "Approve",
                "type": "button",
                "value": accessTool,
                "style": "primary"
            }, {
                "name": "disapprove",
                "text": "Disapprove",
                "type": "button",
                "value": accessTool,
                "style": "danger"
            }]
        }]
    }

    response = requests.request("POST", url, headers=headers, data=dumps(data))

    response = dumps(loads(response.text),
                     sort_keys=True,
                     indent=4,
                     separators=(",", ": "))
    json_response = loads(response)
    #print(json_response)
    return json_response
 def _exec_request(self,
                   url: Text,
                   method: Text,
                   headers: Dict = None,
                   json: Dict = None) -> Response:
     return requests.request(method=method,
                             url=url,
                             headers=headers,
                             json=json)
Exemplo n.º 29
0
    def test_4_from_requests_redirect(self):

        req = Request(method='GET', url='%s/redirect/2' % HTTPBIN_ORIGIN)

        resp = requests.request(**vars(req))
        har_log = harlib.HarLog(resp)
        self.assertEqual(len(har_log.entries), 3)

        to_resp = har_log.encode(requests.Response)
        self.assertEqualResponse(to_resp, resp)
Exemplo n.º 30
0
def call_redlock_api(auth_token, action, endpoint, payload, globalVars):
    url = "https://%s.prismacloud.io/" % tenant + endpoint
    headers = {
        'Content-Type': 'application/json',
        'x-redlock-auth': auth_token
    }
    payload = json.dumps(payload)
    LOGGER.info(payload)
    response = requests.request(action, url, headers=headers, data=payload)
    return response
Exemplo n.º 31
0
def request(host, path, url_params=None):
    url_params = url_params or {}
    url = urljoin(host, path)
    headers = {
        'Authorization': 'Authorization',  # put authorization here
    }

    response = requests.request('GET', url, headers=headers, params=url_params)
    rjson = response.json()
    #business_list = rjson['businesses']
    return rjson
Exemplo n.º 32
0
    def test_4_from_requests_redirect(self):

        req = Request(
            method='GET',
            url='%s/redirect/2' % HTTPBIN_ORIGIN)

        resp = requests.request(**vars(req))
        har_log = harlib.HarLog(resp)
        self.assertEqual(len(har_log.entries), 3)

        to_resp = har_log.encode(requests.Response)
        self.assertEqualResponse(to_resp, resp)