当前位置: 首页>>代码示例>>Python>>正文


Python httplib.OK属性代码示例

本文整理汇总了Python中httplib.OK属性的典型用法代码示例。如果您正苦于以下问题:Python httplib.OK属性的具体用法?Python httplib.OK怎么用?Python httplib.OK使用的例子?那么恭喜您, 这里精选的属性代码示例或许可以为您提供帮助。您也可以进一步了解该属性所在httplib的用法示例。


在下文中一共展示了httplib.OK属性的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: test_get

# 需要导入模块: import httplib [as 别名]
# 或者: from httplib import OK [as 别名]
def test_get(
      self, mock_config, mock_urlfetch, mock_app_identity, mock_logging):
    test_destination_url = cloud_datastore_export._DESTINATION_URL
    test_bucket_name = 'gcp_bucket_name'
    mock_config.side_effect = [test_bucket_name, True]
    expected_url = (
        cloud_datastore_export._DATASTORE_API_URL % self.test_application_id)
    mock_urlfetch.return_value.status_code = httplib.OK
    now = datetime.datetime(
        year=2017, month=1, day=1, hour=1, minute=1, second=15)
    with freezegun.freeze_time(now):
      self.testapp.get(self._CRON_URL)
      mock_urlfetch.assert_called_once_with(
          url=expected_url,
          payload=json.dumps({
              'project_id': self.test_application_id,
              'output_url_prefix': test_destination_url.format(
                  test_bucket_name, now.strftime('%Y_%m_%d-%H%M%S'))
          }),
          method=urlfetch.POST,
          deadline=60,
          headers={
              'Content-Type': 'application/json',
              'Authorization': 'Bearer mock_token'})
      self.assertEqual(mock_logging.call_count, 3) 
开发者ID:google,项目名称:loaner,代码行数:27,代码来源:cloud_datastore_export_test.py

示例2: do_POST

# 需要导入模块: import httplib [as 别名]
# 或者: from httplib import OK [as 别名]
def do_POST(self):
    """Handles a single API request e.g. memcache.Get()."""
    self.send_response(httplib.OK)
    self.send_header('Content-Type', 'application/octet-stream')
    self.end_headers()

    response = remote_api_pb.Response()
    try:
      request = remote_api_pb.Request()



      request.ParseFromString(
          self.rfile.read(int(self.headers['content-length'])))
      api_response = _ExecuteRequest(request).Encode()
      response.set_response(api_response)
    except Exception, e:
      logging.debug('Exception while handling %s\n%s',
                    request,
                    traceback.format_exc())
      response.set_exception(pickle.dumps(e))
      if isinstance(e, apiproxy_errors.ApplicationError):
        application_error = response.mutable_application_error()
        application_error.set_code(e.application_error)
        application_error.set_detail(e.error_detail) 
开发者ID:elsigh,项目名称:browserscope,代码行数:27,代码来源:api_server.py

示例3: query_job

# 需要导入模块: import httplib [as 别名]
# 或者: from httplib import OK [as 别名]
def query_job(job, user=None):
    """
    :type job: Job
    :type user: User
    """
    job = Job.objects.with_id(job), httplib.OK
    if job is None:
        return None, httplib.NOT_FOUND

    if request.method == 'GET':
        return job, httplib.OK

    elif request.method == 'POST':
        return job.modify(**request.json), httplib.OK

    elif job and request.method == 'DELETE':
        job.delete()
        return None, httplib.OK 
开发者ID:mitre,项目名称:cascade-server,代码行数:20,代码来源:api.py

示例4: automate_session

# 需要导入模块: import httplib [as 别名]
# 或者: from httplib import OK [as 别名]
def automate_session(session, user=None):
    """
    :type session: cascade.session.Session
    :type user: User
    """
    session = Session.objects.with_id(session)
    if not session:
        return None, httplib.NOT_FOUND

    if isinstance(request.json, dict):
        if request.json.get('analytics') is not None:
            requested_analytics = request.json['analytics']

            for requested_analytic in requested_analytics:
                analytic = Analytic.objects.with_id(requested_analytic['_id'])
                if analytic:
                    mode = requested_analytic.get('mode', analytic.mode)
                    config = AnalyticConfiguration(analytic=analytic, mode=mode)
                    session.update(add_to_set__state__analytics=config)
                    job = AnalyticJob.update_existing(analytic=analytic, user=user, session=session, mode=mode)
                    job.submit()
            return len(requested_analytics), httplib.OK

    return 0, httplib.BAD_REQUEST 
开发者ID:mitre,项目名称:cascade-server,代码行数:26,代码来源:api.py

示例5: submit_analytic

# 需要导入模块: import httplib [as 别名]
# 或者: from httplib import OK [as 别名]
def submit_analytic(user=None):
    if 'update_many' in request.args:
        if isinstance(request.json, dict) and request.json.get('analytics') is not None:
            count = 0
            for content in request.json['analytics']:
                _id = content.pop('_id', None)
                analytic = Analytic.objects.with_id(_id)
                if analytic is not None:
                    count += analytic.update(**content)

            return Analytic.objects(), httplib.OK
        return {}, httplib.BAD_REQUEST

    # creating a new analytic
    else:
        if request.json.get('platform', 'CASCADE') == 'CASCADE':
            analytic = CascadeAnalytic._from_son(request.json)
        else:
            analytic = ExternalAnalytic._from_son(request.json)
        analytic.save()

    return analytic.id, httplib.OK 
开发者ID:mitre,项目名称:cascade-server,代码行数:24,代码来源:api.py

示例6: make_query

# 需要导入模块: import httplib [as 别名]
# 或者: from httplib import OK [as 别名]
def make_query():
    try:
        query = parser.generate_query(request.json['query'])
        event_type, action = DataModelQueryLayer.get_data_model(query)
        return {'object': event_type.object_name, 'action': action, 'query': query}, httplib.OK

    except InvalidFieldError:
        return {'error': 'Invalid Data Model field in query'}, httplib.BAD_REQUEST

    except InvalidActionError:
        return {'error': 'Invalid Data Model action in query'}, httplib.BAD_REQUEST

    except InvalidObjectError:
        return {'error': 'Invalid Data Model object in query'}, httplib.BAD_REQUEST

    except parser.ParserError:
        return {'error': 'Unable to parse query'}, httplib.BAD_REQUEST 
开发者ID:mitre,项目名称:cascade-server,代码行数:19,代码来源:api.py

示例7: query_baselines

# 需要导入模块: import httplib [as 别名]
# 或者: from httplib import OK [as 别名]
def query_baselines(user=None):
    if request.method == 'GET':
        return AnalyticBaseline.objects(), httplib.OK

    elif request.method == 'POST':
        if isinstance(request.json, dict):
            if request.json.get('analytics') is not None and request.json.get('time') is not None:
                requested_analytics = request.json.get('analytics', [])
                time_range = DateRange.get_range(request.json['time'])

                count = 0
                for requested_analytic in requested_analytics:
                    analytic_id = requested_analytic.pop('_id', requested_analytic.get('id'))
                    analytic = Analytic.objects.with_id(analytic_id)

                    if analytic is None:
                        continue

                    job = TuningJob.update_existing(analytic=analytic, range=time_range, user=user)
                    job.submit()
                    count += 1
                return count, httplib.OK
    return [], httplib.BAD_REQUEST 
开发者ID:mitre,项目名称:cascade-server,代码行数:25,代码来源:api.py

示例8: _refresh_access_token

# 需要导入模块: import httplib [as 别名]
# 或者: from httplib import OK [as 别名]
def _refresh_access_token(self):
        """
        Request new access token to send with requests to Brightcove. Access Token expires every 5 minutes.
        """
        url = "https://oauth.brightcove.com/v3/access_token"
        params = {"grant_type": "client_credentials"}
        auth_string = base64.encodestring(
            '{}:{}'.format(self.api_key, self.api_secret)
        ).replace('\n', '')
        headers = {
            "Content-Type": "application/x-www-form-urlencoded",
            "Authorization": "Basic " + auth_string
        }
        try:
            resp = requests.post(url, headers=headers, data=params)
            if resp.status_code == httplib.OK:
                result = resp.json()
                return result['access_token']
        except IOError:
            log.exception(_("Connection issue. Couldn't refresh API access token."))
            return None 
开发者ID:appsembler,项目名称:xblock-video,代码行数:23,代码来源:brightcove.py

示例9: get

# 需要导入模块: import httplib [as 别名]
# 或者: from httplib import OK [as 别名]
def get(self, url, headers=None, can_retry=True):
        """
        Issue REST GET request to a given URL. Can throw ApiClientError or its subclass.

        Arguments:
            url (str): API url to fetch a resource from.
            headers (dict): Headers necessary as per API, e.g. authorization bearer to perform authorised requests.
            can_retry (bool): True if in a case of authentication error it can refresh access token and retry a call.
        Returns:
            Response in python native data format.
        """
        headers_ = {'Authorization': 'Bearer ' + str(self.access_token)}
        if headers is not None:
            headers_.update(headers)
        resp = requests.get(url, headers=headers_)
        if resp.status_code == httplib.OK:
            return resp.json()
        elif resp.status_code == httplib.UNAUTHORIZED and can_retry:
            self.access_token = self._refresh_access_token()
            return self.get(url, headers, can_retry=False)
        else:
            raise BrightcoveApiClientError 
开发者ID:appsembler,项目名称:xblock-video,代码行数:24,代码来源:brightcove.py

示例10: get

# 需要导入模块: import httplib [as 别名]
# 或者: from httplib import OK [as 别名]
def get(self, url, headers=None, can_retry=False):
        """
        Issue REST GET request to a given URL. Can throw ApiClientError or its subclass.

        Arguments:
            url (str): API url to fetch a resource from.
            headers (dict): Headers necessary as per API, e.g. authorization bearer to perform
            authorised requests.
        Returns:
            Response in python native data format.
        """
        headers_ = {
            'Authorization': 'Bearer {}'.format(self.access_token.encode(encoding='utf-8')),
            'Accept': 'application/json'
        }
        if headers is not None:
            headers_.update(headers)
        resp = requests.get(url, headers=headers_)
        if resp.status_code == httplib.OK:
            return resp.json()
        else:
            raise VimeoApiClientError(_("Can't fetch requested data from API.")) 
开发者ID:appsembler,项目名称:xblock-video,代码行数:24,代码来源:vimeo.py

示例11: _logout

# 需要导入模块: import httplib [as 别名]
# 或者: from httplib import OK [as 别名]
def _logout(self):
        """Posts a logout request to the server.

            Returns:
                str     -   response string from server upon logout success

        """
        flag, response = self.make_request('POST', self._commcell_object._services['LOGOUT'])

        if flag:
            self._commcell_object._headers['Authtoken'] = None

            if response.status_code == httplib.OK:
                return response.text
            else:
                return 'Failed to logout the user'
        else:
            return 'User already logged out' 
开发者ID:CommvaultEngg,项目名称:cvpysdk,代码行数:20,代码来源:cvpysdk.py

示例12: autoscroll

# 需要导入模块: import httplib [as 别名]
# 或者: from httplib import OK [as 别名]
def autoscroll():
    response = {"result": "success"}
    status_code = http_status.OK

    data = request.get_json()
    if data is None:
        data = request.form
    try:
        api_queue.put(Action("autoscroll", (data["is_enabled"], float(data["interval"]))))
    except KeyError:
        response = {"result": "KeyError", "error": "keys is_enabled and interval not posted."}
        status_code = http_status.UNPROCESSABLE_ENTITY
    except ValueError:
        response = {"result": "ValueError", "error": "invalid data type(s)."}
        status_code = http_status.UNPROCESSABLE_ENTITY

    return jsonify(response), status_code 
开发者ID:pimoroni,项目名称:scroll-phat-hd,代码行数:19,代码来源:http.py

示例13: scroll

# 需要导入模块: import httplib [as 别名]
# 或者: from httplib import OK [as 别名]
def scroll():
    response = {"result": "success"}
    status_code = http_status.OK

    data = request.get_json()
    if data is None:
        data = request.form
    try:
        api_queue.put(Action("scroll", (int(data["x"]), int(data["y"]))))
    except KeyError:
        response = {"result": "KeyError", "error": "keys x and y not posted."}
        status_code = http_status.UNPROCESSABLE_ENTITY
    except ValueError:
        response = {"result": "ValueError", "error": "invalid integer."}
        status_code = http_status.UNPROCESSABLE_ENTITY

    return jsonify(response), status_code 
开发者ID:pimoroni,项目名称:scroll-phat-hd,代码行数:19,代码来源:http.py

示例14: flip

# 需要导入模块: import httplib [as 别名]
# 或者: from httplib import OK [as 别名]
def flip():
    response = {"result": "success"}
    status_code = http_status.OK

    data = request.get_json()
    if data is None:
        data = request.form
    try:
        api_queue.put(Action("flip", (bool(data["x"]), bool(data["y"]))))
    except TypeError:
        response = {"result": "TypeError", "error": "Could not cast data correctly. Both `x` and `y` must be set to true or false."}
        status_code = http_status.UNPROCESSABLE_ENTITY
    except KeyError:
        response = {"result": "KeyError", "error": "Could not cast data correctly. Both `x` and `y` must be in the posted json data."}
        status_code = http_status.UNPROCESSABLE_ENTITY

    return jsonify(response), status_code 
开发者ID:pimoroni,项目名称:scroll-phat-hd,代码行数:19,代码来源:http.py

示例15: test_client_request_with_parameters

# 需要导入模块: import httplib [as 别名]
# 或者: from httplib import OK [as 别名]
def test_client_request_with_parameters(jedihttp):
    filepath = utils.fixture_filepath('goto.py')
    request_data = {
        'source': read_file(filepath),
        'line': 10,
        'col': 3,
        'source_path': filepath
    }

    response = requests.post(
        'http://127.0.0.1:{0}/gotodefinition'.format(PORT),
        json=request_data,
        auth=HmacAuth(SECRET))

    assert_that(response.status_code, equal_to(httplib.OK))

    hmachelper = hmaclib.JediHTTPHmacHelper(SECRET)
    assert_that(hmachelper.is_response_authenticated(response.headers,
                                                     response.content)) 
开发者ID:vheon,项目名称:JediHTTP,代码行数:21,代码来源:end_to_end_test.py


注:本文中的httplib.OK属性示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。