Esempio n. 1
0
    def _authenticate(self):
        params = {
            # 'webhost': URL_BASE,
            'service': URL_MODERN,
            # 'source': URL_SSO_LOGIN,
            # 'redirectAfterAccountLoginUrl': URL_MODERN,
            # 'redirectAfterAccountCreationUrl': URL_MODERN,
            # 'gauthHost': URL_SSO_LOGIN,
            # 'locale': 'en_US',
            # 'id': 'gauth-widget',
            # 'cssUrl': 'https://static.garmincdn.com/com.garmin.connect/ui/css/gauth-custom-v1.2-min.css',
            # 'clientId': 'GarminConnect',
            # 'rememberMeShown': 'true',
            # 'rememberMeChecked': 'false',
            # 'createAccountShown': 'true',
            # 'openCreateAccount': 'false',
            # 'usernameShown': 'false',
            # 'displayNameShown': 'false',
            # 'consumeServiceTicket': 'false',
            # 'initialFocus': 'true',
            # 'embedWidget': 'false',
            # 'generateExtraServiceTicket': 'true',
        }

        data = {
            'username': self._username,
            'password': self._password,
            'embed': 'false',
            # 'lt': 'e1s1',
            # '_eventId': 'submit',
            # 'displayNameRequired': 'false',
        }

        login_response = self._session.post(URL_SSO_LOGIN,
                                            params=params,
                                            data=data)
        logging.debug('SSO Request: %s',
                      curlify.to_curl(login_response.request))
        login_response.raise_for_status()

        auth_ticket_url = self._extract_auth_ticket_url(login_response.text)
        logging.debug("Extracted auth ticket url: %s", auth_ticket_url)

        auth_response = self._session.get(auth_ticket_url)
        logging.debug('Auth Request: %s',
                      curlify.to_curl(auth_response.request))
        auth_response.raise_for_status()

        # There is auth info in here needed in order to fetch other services.
        self._preferences = self._extract_json(auth_response.text,
                                               'VIEWER_USERPREFERENCES')
        self.profile = self._extract_json(auth_response.text, 'SOCIAL_PROFILE')
Esempio n. 2
0
def requestScan():
    requests.packages.urllib3.disable_warnings()
    url = "https://"+smartCheckLB+"/api/scans"
    data = {"source": {
        "type": "docker",
        "registry": registry,
        "repository": repository,
        "tag": 'latest',
        "credentials": {
            "aws": {
                "region": "us-east-2",
                "accessKeyID": aws_access_key,
                "secretAccessKey": aws_secret_key
                }
            }
        },
        "webhooks": [{
        "hookURL": createWebHook()}]}
    headers = {'Content-Type': 'application/json', 'Authorization': 'Bearer '+requestToken(), 'X-API-Version': '2018-05-01'}
    try:
        response = requests.request("POST", url, json=data, headers=headers, verify=False)
        print(curlify.to_curl(response.request))
    except requests.exceptions.RequestException as e:
        print (e)
        sys.exit(1)
    return response.json()['id']
Esempio n. 3
0
def show_curl(response_object, verify=True):
    if TAPIS_CLI_SHOW_CURL:
        try:
            curl_text = curlify.to_curl(response_object.request, verify)
        except Exception as err:
            curl_text = 'Failed to render curl command: {0}'.format(err)
        print_stderr(curl_text)
Esempio n. 4
0
 def _request(self, method_name, endpoint_url, data=None, headers=None):
     if endpoint_url.startswith('http'):
         endpoint_url = self.transform_url_to_defined_endpoint(endpoint_url)
     method = getattr(requests, method_name)
     full_url = self._create_full_url(endpoint_url)
     if type(data) is dict or type(data) is list:
         data = json.dumps(data)
     headers = headers or {}
     headers.update(self.headers)
     response = method(full_url, data, headers=headers, timeout=30)
     CURL_LOGGER.info(curlify.to_curl(response.request))
     try:
         if response.status_code >= 500:
             error = HTTPError()
             error.response = response
             raise error
         elif response.status_code >= 400:
             LOGGER.error("ERROR {} {}: {} {}".format(
                 method_name.upper(), response.status_code, full_url,
                 response))
         else:
             LOGGER.debug("SUCCESS {} {}: {} {}".format(
                 method_name.upper(), response.status_code, full_url,
                 json.dumps(data)))
         return self._handle_response(response)
     except HTTPError as e:
         LOGGER.debug('request:%s %s\n%r', method_name, full_url, data)
         LOGGER.error("ERROR {} ({}): {} {} {} {}".format(
             method_name.upper(), e.response.status_code, full_url,
             json.dumps(data), e.response.content, e.response.text))
         raise (e)
Esempio n. 5
0
def get_upload_status(upload_id, token, api_key):
    """
    Retrieve the status of a previously uploaded file. Status values may be (as of the time of this comment):
    INVALID - Image has failed validity check.
    UPLOADING - Uploading the image has started, chunks are still coming in.
    PENDING - File has been received by Climate and is being processed.
    INBOX - The image is awaiting user acceptance in their Data Inbox.
    IMPORTING - The user has accepted the upload in their Data Inbox and the final processing is underway.
    SUCCESS - User has accepted the upload through their Data Inbox and the image is now viewable.
    :param upload_id: uuid of upload
    :param token: access_token
    :param api_key: Provided by Climate
    :return: status json object containing upload id and status.
    """
    uri = '{}/v4/uploads/{}/status'.format(api_uri, upload_id)
    headers = {
        'authorization': bearer_token(token),
        'accept': json_content_type,
        'x-api-key': api_key
    }

    res = requests.get(uri, headers=headers)
    Logger().info(to_curl(res.request))

    if res.status_code == 200:
        return res.json()
    else:
        return None
def reauthorize(refresh_token, client_id, client_secret):
    """
    Access_tokens expire after 4 hours. At any point before the end of that
    period you may request a new access_token (and refresh_token) by submitting
    a POST request to the /api/oauth/token end-point. Note that the data
    submitted is slightly different than on initial authorization. Refresh
    tokens are good for 30 days from their date of issue. Once this end-point
    is called, the refresh token that is passed to this call is immediately set
    to expired one hour from "now" and the newly issues refresh token will
    expire 30 days from "now". Make sure to store the new refresh token so you
    can use it in the future to get a new auth tokens as needed. If you lose
    the refresh token there is no effective way to retrieve a new refresh token
    without having the user log in again.
    :param refresh_token: refresh_token supplied by initial
        (or subsequent refresh) call.
    :param client_id: Provided by Climate.
    :param client_secret: Provided by Climate.
    :return: Object containing user data, access_token and refresh_token.
    """
    headers = {
        'authorization': authorization_header(client_id, client_secret),
        'content-type': 'application/x-www-form-urlencoded',
        'accept': 'application/json'
    }
    data = {'grant_type': 'refresh_token', 'refresh_token': refresh_token}
    res = requests.post(token_uri, headers=headers, data=urlencode(data))
    Logger().info(to_curl(res.request))
    if res.status_code == 200:
        return res.json()

    log_http_error(res)
    return None
def get_scouting_observation_attachments(token, api_key,
                                         scouting_observation_id):
    """
    Retrieve attachments associated with a given scouting observation. Photos
    added to scouting notes in the FieldView app are capped to 20MB, and we
    won’t store photos larger than that in a scouting note.
    https://dev.fieldview.com/technical-documentation/ for possible status
    values and their meaning.
    :param token: access_token
    :param api_key: Provided by Climate
    :param scouting_observation_id: Unique identifier of the
        Scouting Observation.
    """
    uri = '{}/v4/layers/scoutingObservations/{}/attachments'.format(
        api_uri, scouting_observation_id)
    headers = {
        'authorization': bearer_token(token),
        'accept': json_content_type,
        'x-api-key': api_key
    }

    res = requests.get(uri, headers=headers)
    Logger().info(to_curl(res.request))

    if res.status_code == 200:
        return res.json()['results']

    log_http_error(res)
    return []
def get_boundary(boundary_id, token, api_key):
    """
    Retrieve field boundary from Climate. Note that boundary objects are
    immutable, so whenever a field's boundary is updated the boundaryId
    property of the field will change and you will need to fetch the
    updated boundary.
    :param boundary_id: UUID of field boundary to retrieve.
    :param token: access_token
    :param api_key: Provided by Climate
    :return: geojson object representing the boundary of the field.
    """
    uri = '{}/v4/boundaries/{}'.format(api_uri, boundary_id)
    headers = {
        'authorization': bearer_token(token),
        'accept': json_content_type,
        'x-api-key': api_key
    }

    res = requests.get(uri, headers=headers)
    Logger().info(to_curl(res.request))

    if res.status_code == 200:
        return res.json()

    log_http_error(res)
    return None
def get_scouting_observation(token, api_key, scouting_observation_id):
    """
    Retrieve an individual scouting observation by id. Ids are retrieved via
    the /layers/scoutingObservations route.
    https://dev.fieldview.com/technical-documentation/ for possible status
    values and their meaning.
    :param token: access_token
    :param api_key: Provided by Climate
    :param scouting_observation_id: Unique identifier of the
        Scouting Observation.
    """
    uri = '{}/v4/layers/scoutingObservations/{}'.format(
        api_uri, scouting_observation_id)
    headers = {
        'authorization': bearer_token(token),
        'accept': json_content_type,
        'x-api-key': api_key
    }

    res = requests.get(uri, headers=headers)
    Logger().info(to_curl(res.request))

    if res.status_code == 200:
        return res.json()

    log_http_error(res)
    return None
Esempio n. 10
0
def get_upload_status(upload_id, token, api_key):
    """
    Retrieve the status of an upload. See
    https://dev.fieldview.com/technical-documentation/ for possible status
    values and their meaning.
    :param upload_id: id of upload
    :param token: access_token
    :param api_key: Provided by Climate
    :return: status json object containing upload id and status.
    """
    uri = '{}/v4/uploads/{}/status'.format(api_uri, upload_id)
    headers = {
        'authorization': bearer_token(token),
        'accept': json_content_type,
        'x-api-key': api_key
    }

    res = requests.get(uri, headers=headers)
    Logger().info(to_curl(res.request))

    if res.status_code == 200:
        return res.json()

    log_http_error(res)
    return None
    def wrapper(*args, **kwargs):
        response = function(*args, **kwargs)
        msg = curlify.to_curl(response.request)
        logging.info(f'{response.status_code} {msg}')
        allure.attach(
            body=msg.encode('utf8'),
            name=f'Request {response.status_code} {response.request.method} {response.request.url}',
            attachment_type=allure.attachment_type.TEXT,
            extension='txt')

        try:
            response.json()
            allure.attach(
                body=json.dumps(response.json(), indent=4, ensure_ascii=False).encode('utf8'),
                name=f'Response {response.status_code} {response.request.method} '
                     f'{response.request.url}',
                attachment_type=allure.attachment_type.JSON,
                extension='json')

        except ValueError:
            logging.error('RESPONSE IN NOT JSON FORMAT')
            allure.attach(
                body=response.text.encode('utf8'),
                name=f'NOT JSON Response {response.status_code} {response.request.method} '
                     f'{response.request.url}',
                attachment_type=allure.attachment_type.TEXT,
                extension='txt')
        return response
Esempio n. 12
0
def authorize(login_code, client_id, client_secret, redirect_uri):
    """
    Exchanges the login code provided on the redirect request for an
    access_token and refresh_token. Also gets user data.
    :param login_code: Authorization code returned from Log In with FieldView
        on redirect uri.
    :param client_id: Provided by Climate.
    :param client_secret: Provided by Climate.
    :param redirect_uri: Uri to your redirect page. Needs to be the same as
        the redirect uri provided in the initial Log In with FieldView request.
    :return: Object containing user data, access_token and refresh_token.
    """
    headers = {
        'authorization': authorization_header(client_id, client_secret),
        'content-type': 'application/x-www-form-urlencoded',
        'accept': 'application/json'
    }
    data = {
        'grant_type': 'authorization_code',
        'redirect_uri': redirect_uri,
        'code': login_code
    }
    res = requests.post(token_uri, headers=headers, data=urlencode(data))
    Logger().info(to_curl(res.request))
    if res.status_code == 200:
        return res.json()

    Logger().error("Auth failed: %s" % res.status_code)
    Logger().error("Auth failed: %s" % res.json())
    return None
Esempio n. 13
0
    def request(self, method: str, url_path: str, **kwargs):
        url = self._build_url(url_path)
        logger.info(f'Performing "{method}" request to "{url}"')

        if kwargs:
            for k, v in kwargs.items():
                if v is not None:
                    message = json.dumps(v, ensure_ascii=False, indent=4)
                    logger.info(f'Request param "{k}": {message}')

        resp = super(RemoteApiSession, self).request(method, url, **kwargs)
        logger.info(curlify.to_curl(resp.request))
        logger.info(f'Response status code is "{resp.status_code}"')

        try:
            message = json.dumps(resp.json(), ensure_ascii=False, indent=4)
            logger.info('\n' + message)
        except ValueError:
            logger.info('\n' + resp.text)

        headers = json.dumps({k: v for k, v in resp.headers.items()})
        logger.info(f'Headers: {headers}')

        total_seconds = resp.elapsed.total_seconds()
        logger.info(f'Response time is "{total_seconds}" seconds')

        return resp
Esempio n. 14
0
def get_fields(token, api_key, next_token=None):
    """
    Retrieve a user's field list from Climate. Note that fields (like most data) is paginated to support very large
    data sets. If the status code returned is 206 (partial content), then there is more data to get. The x-next-token
    header provides a "marker" that can be used on another request to get the next page of data. Continue fetching
    data until the status is 200. Note that x-next-token is based on date modified, so storing x-next-token can used
    as a method to fetch updates over longer periods of time (though also note that this will not result in fetching
    deleted objects since they no longer appear in lists regardless of their modified date).
    :param token: access_token
    :param api_key: Provided by Climate.
    :param next_token: Pagination token from previous request, or None.
    :return: A (possibly empty) list of fields.
    """
    uri = '{}/v4/fields'.format(api_uri)
    headers = {
        'authorization': bearer_token(token),
        'accept': json_content_type,
        'x-api-key': api_key,
        'x-next-token': next_token
    }

    res = requests.get(uri, headers=headers)
    Logger().info(to_curl(res.request))

    if res.status_code == 200:
        return res.json()['results']
    if res.status_code == 206:
        next_token = res.headers['x-next-token']
        return res.json()['results'] + get_fields(token, api_key, next_token)
    else:
        return []
Esempio n. 15
0
    def _request(self, method, url, **kwargs):
        url = self.favroBaseUrl + url

        kwargs.update({'auth': self.authHeader})
        if 'headers' in kwargs and isinstance(kwargs['headers'], dict):
            kwargs['headers'].update(self.organization)
        else:
            kwargs.update({'headers': self.organization})

        r = requests_retry_session().request(method, url, **kwargs)

        # try:
        #     r = self.requests.request(method, url, **kwargs)
        # except Exception as e:
        #     r = self.requests.request(method, url, **kwargs)
        #     curl = curlify.to_curl(r.request)
        #     print("Request Exception: %s\n%s" % (str(e), curl))

        rateLimitRemaining = int(r.headers.get('X-RateLimit-Remaining', 666))
        rateLimit = int(r.headers.get('X-RateLimit-Limit', 666))
        rateLimitReset = r.headers.get('X-RateLimit-Reset', None)

        if r.status_code == 429:
            raise Exception(
                "[%s] Rate limit exceeded: %s/%s until %s" %
                (r.status_code, rateLimitRemaining, rateLimit, rateLimitReset))

        if rateLimitRemaining % 100 == 0:
            print("Favro Rate limits: %s/%s" % (rateLimitRemaining, rateLimit))

        if not r.ok:
            curl = curlify.to_curl(r.request)
            raise Exception("(%s/%s) Request returned code %s: %s in %s" %
                            (rateLimitRemaining, rateLimit, r.status_code,
                             str(r.content) + str(r.reason), curl))

        output = r.json()
        if method == 'delete':
            return output

        page = output.get('page', 0)
        pages = output.get('pages', 0)
        requestId = r.headers.get('X-Favro-Backend-Identifier', None)
        while page < pages - 1:
            params = kwargs.setdefault('params', {})
            params.update({'requestId': requestId, 'page': page + 1})
            pagedrequest = requests_retry_session().request(
                method, url, **kwargs)
            pagedrequestjson = pagedrequest.json()
            page = pagedrequestjson.get('page', 0)
            newpages = pagedrequestjson.get('pages', 0)
            if newpages != pages:
                raise Exception("pages quantity mismatch")
            requestId = pagedrequest.headers.get('X-Favro-Backend-Identifier',
                                                 None)
            entities = pagedrequestjson.get('entities', [])
            output['entities'] += entities

        return output
Esempio n. 16
0
def test_verify():
    request = requests.Request(
        'GET',
        "http://google.ru",
        headers={"user-agent": "UA"},
    )
    assert curlify.to_curl(request.prepare(), verify=False) == (
        "curl -X GET -H 'user-agent: UA' --insecure http://google.ru/")
Esempio n. 17
0
def test_comressed():
    request = requests.Request(
        'GET',
        "http://google.ru",
        headers={"user-agent": "UA"},
    )
    assert curlify.to_curl(request.prepare(), compressed=True) == (
        "curl -X 'GET' -H 'user-agent: UA' --compressed 'http://google.ru/'")
Esempio n. 18
0
def test_post_json():
    data = {'foo': 'bar'}
    url = 'https://httpbin.org/post'

    r = requests.Request('POST', url, json=data)
    assert curlify.to_curl(
        r.prepare()) == ("curl -X 'POST' -H 'Content-Length: 14' "
                         "-H 'Content-Type: application/json' "
                         "-d '{\"foo\": \"bar\"}' 'https://httpbin.org/post'")
Esempio n. 19
0
def test_compressed():
    url = "https://httpbin.org/get"
    request = requests.Request('GET', url, headers={"User-agent": "UA"})

    assert curlify.to_curl(request.prepare(),
                           compressed=True) == ("curl -X GET"
                                                " -H 'User-agent: UA'"
                                                " --compressed"
                                                f" {url}")
Esempio n. 20
0
def getCURLData(IP="127.0.0.1",URI="switches"):
	URL="http://%s:9000/stats/%s"%(IP,URI)
	print "URL:"+URL
	response = requests.get(URL)
	logging.warning(curlify.to_curl(response.request)) 
	if (response.status_code == requests.codes.ok):
		return(response.json())
	else:
		logging.ERROR("URL:"+URL+"\t %d"%(response.status_code))
		return(None)
Esempio n. 21
0
def test_post_json():
    url = 'https://httpbin.org/post'
    data = {'foo': 'bar'}
    request = requests.Request('POST', url, json=data)

    curl_cmd = curlify.to_curl(request.prepare())

    assert curl_cmd == ("curl -X POST -H 'Content-Length: 14' "
                        "-H 'Content-Type: application/json' "
                        "-d '{\"foo\": \"bar\"}' https://httpbin.org/post")
Esempio n. 22
0
 def as_curl_command(self, headers: Optional[Dict[str, Any]] = None) -> str:
     """Construct a curl command for a given case."""
     base_url = self.get_full_base_url()
     kwargs = self.as_requests_kwargs(base_url)
     if headers:
         final_headers = kwargs["headers"] or {}
         final_headers.update(headers)
         kwargs["headers"] = final_headers
     request = requests.Request(**kwargs)
     return curlify.to_curl(request.prepare())
Esempio n. 23
0
def test_prepare_request():
    request = requests.Request(
        'GET',
        "http://google.ru",
        headers={"user-agent": "UA"},
    )

    assert curlify.to_curl(request.prepare()) == ("curl -X 'GET' "
                                                  "-H 'user-agent: UA' "
                                                  "'http://google.ru/'")
Esempio n. 24
0
def request_money():
    """Request Money Wrapper Function

    Takes the following body parameters:
        - amount {number}
        - contactName {string}
        - email {string}
        - memo {string, optional}
        - returnURL {string, optional}

    """
    data = request.data
    dataDict = json.loads(data)

    source_money_request_id = str(uuid.uuid4()).replace('-', '')
    response = requests.post(
        'https://gateway-web.beta.interac.ca/publicapi/api/v2/money-requests/send',
        headers={
            'accessToken': f"Bearer {os.getenv('ACCESS_TOKEN')}",
            'thirdPartyAccessId': os.getenv('THIRD_PARTY_ACCESS_ID'),
            'apiRegistrationId': os.getenv('API_REGISTRATION_ID'),
            'requestId': str(uuid.uuid4()),
            'deviceId': str(uuid.uuid4())
        },
        json={
            'sourceMoneyRequestId':
            source_money_request_id,
            'requestedFrom': {
                'contactName':
                dataDict['contactName'],
                'language':
                'en',
                'notificationPreferences': [{
                    'handle': dataDict['email'],
                    'handleType': 'email',
                    'active': True
                }]
            },
            'amount':
            dataDict['amount'],
            'currency':
            'CAD',
            'editableFulfillAmount':
            False,
            'requesterMessage':
            dataDict.get('memo', None),
            'expiryDate':
            arrow.utcnow().shift(hours=24).format('YYYY-MM-DDTHH:mm:ss') +
            '.835Z',
            'supressResponderNotifications':
            False
        })
    print(curlify.to_curl(response.request))

    return jsonify(json.loads(response.text)), response.status_code
Esempio n. 25
0
def test_verify():
    url = 'https://httpbin.org/get'
    request = requests.Request(
        'GET',
        url,
        headers={"user-agent": "UA"},
    )

    assert curlify.to_curl(
        request.prepare(),
        verify=False) == (f"curl -X GET -H 'user-agent: UA' --insecure {url}")
Esempio n. 26
0
def test_prepare_request():
    url = 'https://httpbin.org/get'
    request = requests.Request(
        'GET',
        url,
        headers={"User-agent": "UA"},
    )

    assert curlify.to_curl(request.prepare()) == ("curl -X GET"
                                                  " -H 'User-agent: UA'"
                                                  f" {url}")
    def _request(self, method_name, endpoint_url, data=None, headers=None, can_retry=True):
        """
        Making an http call with a specific method
        In case of an Unauthorized response. The auth client will refresh the token and send the
        request again
        :param method_name:
        :param endpoint_url:
        :param data:
        :param headers:
        :param can_retry:
        :return: the response of the http request
        """
        full_url = self._create_full_url(endpoint_url)
        if type(data) is dict or type(data) is list:
            data = json.dumps(data)
        original_headers = headers
        headers = headers or {}
        if self.auth_client is not None:
            headers.update(self.auth_client.get_headers())
        req = Request(method_name, full_url, data=data, headers=headers)
        prepped_request = self.req_session.prepare_request(req)
        response = self.req_session.send(prepped_request, timeout=30)
        self.curl_logger.debug(curlify.to_curl(response.request))
        try:
            if response.status_code >= 500:
                error = HTTPError()
                error.response = response
                raise error

            elif (response.status_code == 401 or response.status_code == 403) and can_retry:
                self.logger.debug(
                    "ERROR - Refreshing token {} {}: {} {}".format(method_name.upper(),
                                                                   response.status_code, full_url,
                                                                   response))
                if self.auth_client is not None:
                    self.auth_client.refresh_token()
                    return self._request(method_name, endpoint_url, data, original_headers,
                                  can_retry=False)
            elif response.status_code > 403:
                self.logger.debug(
                    "ERROR {} {}: {} {}".format(method_name.upper(), response.status_code, full_url,
                                                response))
            else:
                self.logger.debug(
                    "SUCCESS {} {}: {} {}".format(method_name.upper(), response.status_code,
                                                  full_url, json.dumps(data)))
            return self._handle_response(response)
        except HTTPError as e:
            self.logger.debug('request:%s %s\n%r', method_name, full_url, data)
            self.logger.warning(
                "ERROR {} ({}): {} {} {} {}".format(method_name.upper(), e.response.status_code,
                                                    full_url, json.dumps(data), e.response.content,
                                                    e.response.text))
            raise (e)
Esempio n. 28
0
def graphcall():
    token = _get_token_from_cache(app_config.SCOPE)
    if not token:
        return redirect(url_for("login"))
    response = requests.get(  # Use token to call downstream service
        app_config.ENDPOINT,
        headers={'Authorization': 'Bearer ' + token['access_token']},
        )
    print ('[INFO] Graph call: ', curlify.to_curl(response.request))
    graph_data = response.json()
    return render_template('display.html', result=graph_data)
Esempio n. 29
0
def test_post_binary_file():
    r = requests.Request(method='POST',
                         url='https://httpbin.org/post',
                         files={'file': open('cat.jpg', 'rb')},
                         headers={'Content-Type': 'multipart/form-data'})

    curlified = curlify.to_curl(r.prepare())
    expected = 'curl -X POST -H \'Content-Length: 55558\' ' \
               '-H \'Content-Type: multipart/form-data\' ' \
               '-F [email protected] https://httpbin.org/post'

    assert curlified == expected
Esempio n. 30
0
def get_scouting_observations(token,
                              api_key,
                              limit=100,
                              next_token=None,
                              occurred_after=None,
                              occurred_before=None):
    """
    Retrieve a list of scouting observations created or updated by the user
    identified by the Authorization header.
    https://dev.fieldview.com/technical-documentation/ for possible status
    values and their meaning.
    :param token: access_token
    :param api_key: Provided by Climate
    :param next-token: Opaque string which allows for fetching the next batch
        of results.
    :param limit: Max number of results to return per batch. Must be between
        1 and 100 inclusive.
    :param occurred_after: Optional start time by which to filter layer
         results.
    :param occurred_before: Optional end time by which to filter layer results.
    :return: status json object containing scouting observation list
        and status.
    """
    uri = '{}/v4/layers/scoutingObservations'.format(api_uri)
    headers = {
        'authorization': bearer_token(token),
        'accept': json_content_type,
        'x-api-key': api_key,
        'x-limit': str(limit),
        'x-next-token': next_token
    }
    params = {
        'occurredAfter': occurred_after,
        'occurredBefore': occurred_before
    }

    res = requests.get(uri, headers=headers, params=params)
    Logger().info(to_curl(res.request))

    if res.status_code == 200:
        return res.json()['results']
    if res.status_code == 206:
        next_token = res.headers['x-next-token']
        return res.json()['results'] + \
            get_scouting_observations(token,
                                      api_key,
                                      limit,
                                      next_token,
                                      occurred_after,
                                      occurred_before)
    log_http_error(res)
    return []
Esempio n. 31
0
    def call(
        self,
        method,
        path,
        params=None,
        headers=None,
        files=None,
        url_override=None,
        api_version=None,
    ):
        """Makes an API call.
        Args:
            method: The HTTP method name (e.g. 'GET').
            path: A tuple of path tokens or a full URL string. A tuple will
                be translated to a url as follows:
                graph_url/tuple[0]/tuple[1]...
                It will be assumed that if the path is not a string, it will be
                iterable.
            params (optional): A mapping of request parameters where a key
                is the parameter name and its value is a string or an object
                which can be JSON-encoded.
            headers (optional): A mapping of request headers where a key is the
                header name and its value is the header value.
            files (optional): An optional mapping of file names to binary open
                file objects. These files will be attached to the request.
        Returns:
            A FacebookResponse object containing the response body, headers,
            http status, and summary of the call that was made.
        Raises:
            FacebookResponse.error() if the request failed.
        """
        if not params:
            params = {}
        if not headers:
            headers = {}
        if not files:
            files = {}

        api_version = api_version or self._api_version

        if api_version and not re.search('v[0-9]+\.[0-9]+', api_version):
            raise FacebookBadObjectError(
                'Please provide the API version in the following format: %s'
                % self.API_VERSION,
            )

        self._num_requests_attempted += 1

        if not isinstance(path, six.string_types):
            # Path is not a full path
            path = "/".join((
                url_override or self._session.GRAPH,
                api_version,
                '/'.join(map(str, path)),
            ))

        # Include api headers in http request
        headers = headers.copy()
        headers.update(FacebookAdsApi.HTTP_DEFAULT_HEADERS)

        if params:
            params = _top_level_param_json_encode(params)

        # Get request response and encapsulate it in a FacebookResponse
        if method in ('GET', 'DELETE'):
            response = self._session.requests.request(
                method,
                path,
                params=params,
                headers=headers,
                files=files,
                timeout=self._session.timeout
            )

        else:
            response = self._session.requests.request(
                method,
                path,
                data=params,
                headers=headers,
                files=files,
                timeout=self._session.timeout
            )
        if self._enable_debug_logger:
            print(curlify.to_curl(response.request))
        fb_response = FacebookResponse(
            body=response.text,
            headers=response.headers,
            http_status=response.status_code,
            call={
                'method': method,
                'path': path,
                'params': params,
                'headers': headers,
                'files': files,
            },
        )

        if fb_response.is_failure():
            raise fb_response.error()

        self._num_requests_succeeded += 1
        return fb_response