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


Python Session.delete方法代码示例

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


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

示例1: JoolaBaseClient

# 需要导入模块: from requests import Session [as 别名]
# 或者: from requests.Session import delete [as 别名]
class JoolaBaseClient(object):
    def __init__(self, base_url, credentials=None, api_token=None, **kwargs):
        self.base_url = str(base_url)
        self.session = Session()

        self.session.mount('http://', CachingHTTPAdapter())
        self.session.mount('https://', CachingHTTPAdapter())

        if api_token:
            self.session.auth = APITokenAuth(api_token)
        elif credentials:
            self.session.auth = credentials

    def list(self):
        return self.session.get(self.base_url)

    def get(self, lookup):
        return self.session.get('%s%s' % (self.base_url, str(lookup)))

    def insert(self, **kwargs):
        return self.session.post(self.base_url, data=kwargs)

    def patch(self, lookup, **kwargs):
        return self.session.patch('%s%s' % (self.base_url, str(lookup)), data=kwargs)

    def delete(self, lookup):
        return self.session.delete('%s%s' % (self.base_url, str(lookup)))
开发者ID:joola,项目名称:joola.io.sdk-python,代码行数:29,代码来源:client.py

示例2: __init__

# 需要导入模块: from requests import Session [as 别名]
# 或者: from requests.Session import delete [as 别名]
class Flowdock:
    """Simple wrapper for Flowdock REST API."""

    API_URL = "https://api.flowdock.com"

    def __init__(self, api_key, debug=False, print_function=None):
        """Initialize Flowdock API wrapper.

        @param debug Print debug info if True
        @param print_function Use this function to print debug info. By default
        use python builtin print. Mainly for using click.echo without requiring
        click as dependency.
        """
        self.session = Session()
        # requests accepts http basic auth as tuple (user, pass), however,
        # Flowdoc uses only api key as username without password
        self.session.auth = (api_key, None)
        self.debug = debug
        self.print = print_function if print_function else print

    def get_organizations(self):
        """Get list of organizations this user has access to"""
        url = "{}/organizations".format(self.API_URL)
        if self.debug:
            self.print("Sending GET request to URL {}".format(url))
        r = self.session.get(url)
        r.raise_for_status()
        return r.json()

    def find_user_orgs(self, email):
        """Find organizations this user belongs to"""
        orgs = self.get_organizations()
        return [org for org in orgs if Flowdock.user_in_org(email, org)]

    @staticmethod
    def user_in_org(email, org):
        """Chek if user is part of organization"""
        for user in org['users']:
            if user['email'] == email:
                return True
        return False

    def delete_user_from_org(self, user, org):
        url = "{}/organizations/{}/users/{}".format(self.API_URL,
                                                    org['parameterized_name'],
                                                    user['id'])
        if self.debug:
            self.print("Sending DELETE request to url {}".format(url))

        r = self.session.delete(url)
        r.raise_for_status()

    def close(self):
        self.session.close()
开发者ID:pombredanne,项目名称:flowdock-management,代码行数:56,代码来源:flowdock.py

示例3: HTTPClient

# 需要导入模块: from requests import Session [as 别名]
# 或者: from requests.Session import delete [as 别名]
class HTTPClient(abstract_http_client.AbstractHTTPClient):
    def __init__(self, base_url, user_name, user_pass='', http_debug_enabled=False):
        """Initialize a new paymill interface connection. Requires a private key."""
        self.base_url = base_url
        self.session = Session()
        self.session.auth = (user_name, "")
        self.session.verify = False
        self.operations = dict(GET=self.get, POST=self.post, PUT=self.put, DELETE=self.delete)
        #for internal usage
        self.response = None
        http_debug(enabled=http_debug_enabled)

    def __call__(self, request_type, params, url, return_type):
        try:
            return self.operations[request_type](params, url, return_type)
        except ValueError as v:
            # JSON encoding failed
            #=>PAYMILL API sent us an error, without JSON data
            if self.response is not None:
                raise PMError(self.response.content, self.response.status_code)
            else:
                raise PMError()

    def put(self, params, url, return_type):
        return self._check_reponse(self.session.put(self.base_url + url, params,
                                                    hooks=dict(response=self._request_callback)).json(), return_type)

    def post(self, params, url, return_type):
        json = self.session.post(self.base_url + url, params, hooks=dict(response=self._request_callback)).json()
        return self._check_reponse(json, return_type)

    def delete(self, params, url, return_type):
        return self._check_reponse(self.session.delete(self.base_url + url, params=params,
                                                       hooks=dict(response=self._request_callback)).json(), return_type)

    def get(self, params, url, return_type):
        return self._check_reponse(self.session.get(self.base_url + url, params=params,
                                                    hooks=dict(response=self._request_callback)).json(), return_type)

    def _request_callback(self, r, *args, **kwargs):
        self.response = r

    def _check_reponse(self, json_data, return_type):
        if 'data' in json_data:
            #success
            if isinstance(json_data['data'], dict):
                return return_type(json_data['data'])
            else:
                return return_type(json_data)
        else:
            #error
            raise PMError(json_data, self.response.status_code)
开发者ID:Inkalabs,项目名称:paymill-python,代码行数:54,代码来源:http_client.py

示例4: DatabaseConnection

# 需要导入模块: from requests import Session [as 别名]
# 或者: from requests.Session import delete [as 别名]

#.........这里部分代码省略.........
        there is a seamless experience. """
        auth = None
        if user_or_apikey is not None:
            # ConnectorDB allows login using both basic auth or an apikey url param.
            # The python client uses basic auth for all logins
            if user_password is None:
                # Login by api key - the basic auth login uses "" user and
                # apikey as password
                user_password = user_or_apikey
                user_or_apikey = ""
            auth = HTTPBasicAuth(user_or_apikey, user_password)
            self.r.auth = auth

        # Set the websocket's authentication
        self.ws.setauth(auth)

    def close(self):
        """Closes the active connections to ConnectorDB"""
        self.r.close()

    def handleresult(self, r):
        """Handles HTTP error codes for the given request

        Raises:
            AuthenticationError on the appropriate 4** errors
            ServerError if the response is not an ok (2**)

        Arguments:
            r -- The request result
        """
        if r.status_code >= 400 and r.status_code < 500:
            msg = r.json()
            raise AuthenticationError(str(msg["code"]) + ": " + msg["msg"] +
                                      " (" + msg["ref"] + ")")
        elif r.status_code > 300:
            err = None
            try:
                msg = r.json()
                err = ServerError(str(msg["code"]) + ": " + msg["msg"] + " (" +
                                  msg["ref"] + ")")
            except:
                raise ServerError(
                    "Server returned error, but did not give a valid error message")
            raise err
        return r

    def ping(self):
        """Attempts to ping the server using current credentials, and responds with the path of the currently
        authenticated device"""
        return self.handleresult(self.r.get(self.url,
                                            params={"q": "this"})).text

    def query(self, query_type, query=None):
        """Run the given query on the connection (POST request to /query)"""
        return self.handleresult(self.r.post(urljoin(self.url + "query/",
                                                     query_type),
                                             data=json.dumps(query))).json()

    def create(self, path, data=None):
        """Send a POST CRUD API request to the given path using the given data which will be converted
        to json"""
        return self.handleresult(self.r.post(urljoin(self.url + CRUD_PATH,
                                                     path),
                                             data=json.dumps(data)))

    def read(self, path, params=None):
        """Read the result at the given path (GET) from the CRUD API, using the optional params dictionary
        as url parameters."""
        return self.handleresult(self.r.get(urljoin(self.url + CRUD_PATH,
                                                    path),
                                            params=params))

    def update(self, path, data=None):
        """Send an update request to the given path of the CRUD API, with the given data dict, which will be converted
        into json"""
        return self.handleresult(self.r.put(urljoin(self.url + CRUD_PATH,
                                                    path),
                                            data=json.dumps(data)))

    def delete(self, path):
        """Send a delete request to the given path of the CRUD API. This deletes the object. Or at least tries to."""
        return self.handleresult(self.r.delete(urljoin(self.url + CRUD_PATH,
                                                       path)))

    def get(self, path, params=None):
        """Sends a get request to the given path in the database and with optional URL parameters"""
        return self.handleresult(self.r.get(urljoin(self.url, path),
                                            params=params))

    def subscribe(self, stream, callback, transform=""):
        """Subscribe to the given stream with the callback"""
        return self.ws.subscribe(stream, callback, transform)

    def unsubscribe(self, stream, transform=""):
        """Unsubscribe from the given stream"""
        return self.ws.unsubscribe(stream, transform)

    def wsdisconnect(self):
        """Disconnects the websocket"""
        self.ws.disconnect()
开发者ID:connectordb,项目名称:connectordb-python,代码行数:104,代码来源:_connection.py

示例5: ApolloMonitor

# 需要导入模块: from requests import Session [as 别名]
# 或者: from requests.Session import delete [as 别名]
class ApolloMonitor(object):
    """Class for monitoring an Apache Apollo server"""
    def __init__(self, host, virtual_host, port=61680,
                 realm='Apollo', username='admin', password='password',
                 update_interval_s=5):
        """Construct a new ApolloMonitor that monitors the $virtual_host
           virtual-host on the Apollo server at $host:$port with credentials
           $username and $password.  Monitor for update events every
           $update_interval_s seconds (or, if seconds is None, not at all)."""
        # Prepare a URL opener
        self.auth = (username, password)
        self._url = ('http://%s:%d/broker/virtual-hosts/%s'
                     % (host, port, virtual_host))
        self._url_queues = self._url + '/queues.json'
        self._url_delete = self._url + '/queues/%s.json'
        self._s = Session()

        # Initialize the queue status dictionary
        self.queues = self._structure_queue_data(self._get_queue_data())
        for queue in self.queues.values():
            self.on_queue_init(queue)

        # Initialize the update wait event
        self.update_event = Event()
        self.update_event.clear()

        # Run updates in a loop
        if update_interval_s is not None:
            call_periodic(update_interval_s, self.do_update)

    def _get_queue_data(self):
        """Return a parsed structure containing the current queue data"""
        # Repeat until a full download is accomplished
        page_size = -1
        total_rows = 0
        while page_size < total_rows:
            # Determine the new page size
            page_size = total_rows + 1000
            url = self._url_queues + ('?ps=%d' % page_size)

            # Get the JSON-formatted data
            queues = self._s.get(url, auth=self.auth).json
            if callable(queues):
                queues = queues()

            # Extract the new page size and row counts
            page_size = queues['page_size']
            total_rows = queues['total_rows']

        # Operation Complete!
        return queues['rows']

    def _structure_queue_data(self, queues, exclude_temp=True):
        """Construct a dictionary mapping destination names to a queue data
           structure, optionally excluding temporary destinations."""
        return dict((q['id'], q)
                    for q in queues
                    if not exclude_temp or not q['id'].startswith('temp.'))

    def _detect_queue_changes(self, new_queues):
        """Fire events for handling new, updated, and deleted queues"""

        # We will send a blank logging message if there is at least one event
        any_events = False

        # Keep a list of the old queues
        old_queues = set(self.queues.keys())

        # Iterate over new_queues
        for q_id in new_queues:
            queue = new_queues[q_id]

            # Detect a modified queue
            if q_id in old_queues:
                # Report the update
                self.on_queue_update(self.queues[q_id], queue)
                old_queues.remove(q_id)
                any_events |= True
            else:
                # Report the new queue
                self.on_queue_new(queue)
                any_events |= True

            self.queues[q_id] = queue

        # Delete old queues
        for q_id in old_queues:
            # Report the removal
            self.on_queue_delete(self.queues[q_id])
            self.queues.pop(q_id)
            any_events |= True

        # Send a blank logging message if there were any events
        # (This causes logging output to appear in stanzas)
        if any_events:
            logger.debug('')

    def do_update(self):
        """Download new queue data and send update notifications"""
        new_queues = self._structure_queue_data(self._get_queue_data())
#.........这里部分代码省略.........
开发者ID:pombredanne,项目名称:apollo-1,代码行数:103,代码来源:queues.py

示例6: EsiAccess

# 需要导入模块: from requests import Session [as 别名]
# 或者: from requests.Session import delete [as 别名]
class EsiAccess(object):
    def __init__(self):
        self.settings = EsiSettings.getInstance()

        # session request stuff
        self._session = Session()
        self._session.headers.update({
            'Accept': 'application/json',
            'User-Agent': (
                'pyfa v{}'.format(config.version)
            )
        })
        self._session.proxies = NetworkSettings.getInstance().getProxySettingsInRequestsFormat()

    @property
    def sso_url(self):
        if self.settings.get("ssoMode") == SsoMode.CUSTOM:
            return "https://login.eveonline.com"
        return "https://www.pyfa.io"

    @property
    def esi_url(self):
        return "https://esi.tech.ccp.is"

    @property
    def oauth_verify(self):
        return '%s/verify/' % self.esi_url

    @property
    def oauth_authorize(self):
        return '%s/oauth/authorize' % self.sso_url

    @property
    def oauth_token(self):
        return '%s/oauth/token' % self.sso_url

    def getSkills(self, char):
        return self.get(char, ESIEndpoints.CHAR_SKILLS, character_id=char.characterID)

    def getSecStatus(self, char):
        return self.get(char, ESIEndpoints.CHAR, character_id=char.characterID)

    def getFittings(self, char):
        return self.get(char, ESIEndpoints.CHAR_FITTINGS, character_id=char.characterID)

    def postFitting(self, char, json_str):
        # @todo: new fitting ID can be recovered from resp.data,
        return self.post(char, ESIEndpoints.CHAR_FITTINGS, json_str, character_id=char.characterID)

    def delFitting(self, char, fittingID):
        return self.delete(char, ESIEndpoints.CHAR_DEL_FIT, character_id=char.characterID, fitting_id=fittingID)

    @staticmethod
    def update_token(char, tokenResponse):
        """ helper function to update token data from SSO response """
        char.accessToken = tokenResponse['access_token']
        char.accessTokenExpires = datetime.datetime.fromtimestamp(time.time() + tokenResponse['expires_in'])
        if 'refresh_token' in tokenResponse:
            char.refreshToken = config.cipher.encrypt(tokenResponse['refresh_token'].encode())

    def getLoginURI(self, redirect=None):
        self.state = str(uuid.uuid4())

        if self.settings.get("ssoMode") == SsoMode.AUTO:
            args = {
                'state': self.state,
                'pyfa_version': config.version,
                'login_method': self.settings.get('loginMode'),
                'client_hash': config.getClientSecret()
            }

            if redirect is not None:
                args['redirect'] = redirect

            return '%s?%s' % (
                self.oauth_authorize,
                urlencode(args)
            )
        else:
            return '%s?response_type=%s&redirect_uri=%s&client_id=%s%s%s' % (
                self.oauth_authorize,
                'code',
                quote('http://localhost:6461', safe=''),
                self.settings.get('clientID'),
                '&scope=%s' % '+'.join(scopes) if scopes else '',
                '&state=%s' % self.state
            )

    def get_oauth_header(self, token):
        """ Return the Bearer Authorization header required in oauth calls

        :return: a dict with the authorization header
        """
        return {'Authorization': 'Bearer %s' % token}

    def get_refresh_token_params(self, refreshToken):
        """ Return the param object for the post() call to get the access_token
        from the refresh_token

        :param code: the refresh token
#.........这里部分代码省略.........
开发者ID:bsmr-eve,项目名称:Pyfa,代码行数:103,代码来源:esiAccess.py

示例7: str

# 需要导入模块: from requests import Session [as 别名]
# 或者: from requests.Session import delete [as 别名]
                            content = s.get(item['@microsoft.graph.downloadUrl']).content
                            lang, return_val = self.mainMenu.agents.handle_agent_data(staging_key, content, listener_options)[0]
                            message = "[*] Uploading {}/{}/{}_2.txt, {} bytes".format(base_folder, staging_folder, agent_name, str(len(return_val)))
                            signal = json.dumps({
                                'print': False,
                                'message': message
                            })
                            dispatcher.send(signal, sender="listeners/onedrive/{}".format(listener_name))
                            s.put("%s/drive/root:/%s/%s/%s_2.txt:/content" % (base_url, base_folder, staging_folder, agent_name), data=return_val)
                            message = "[*] Deleting {}/{}/{}".format(base_folder, staging_folder, item['name'])
                            signal = json.dumps({
                                'print': False,
                                'message': message
                            })
                            dispatcher.send(signal, sender="listeners/onedrive/{}".format(listener_name))
                            s.delete("%s/drive/items/%s" % (base_url, item['id']))

                        if stage == '3': #Download stage 3, upload stage 4 (full agent code)
                            message = "[*] Downloading {}/{}/{}, {} bytes".format(base_folder, staging_folder, item['name'], item['size'])
                            signal = json.dumps({
                                'print': False,
                                'message': message
                            })
                            dispatcher.send(signal, sender="listeners/onedrive/{}".format(listener_name))
                            content = s.get(item['@microsoft.graph.downloadUrl']).content
                            lang, return_val = self.mainMenu.agents.handle_agent_data(staging_key, content, listener_options)[0]

                            session_key = self.mainMenu.agents.agents[agent_name]['sessionKey']
                            agent_token = renew_token(client_id, token['refresh_token']) #Get auth and refresh tokens for the agent to use
                            agent_code = str(self.generate_agent(listener_options, client_id, agent_token['access_token'],
                                                            agent_token['refresh_token'], redirect_uri, lang))
开发者ID:0xe7,项目名称:Empire,代码行数:33,代码来源:onedrive.py

示例8: Flowdock

# 需要导入模块: from requests import Session [as 别名]
# 或者: from requests.Session import delete [as 别名]
class Flowdock(object):
    """Simple wrapper for Flowdock REST API."""

    API_URL = "https://api.flowdock.com"

    def __init__(self, api_key, debug=False, print_function=None):
        """Initialize Flowdock API wrapper.

        debug -- Print debug info if True
        print_function -- Use this function to print debug info. By default use
        python builtin print. Mainly for using click.echo without requiring
        click as dependency.
        """
        self.session = Session()
        # requests accepts http basic auth as tuple (user, pass), however,
        # Flowdoc uses only api key as username without password
        self.session.auth = (api_key, None)
        self.print_debug = debug
        self.print = print_function if print_function else print

    def debug(self, message):
        if self.print_debug:
            self.print(message)

    def list_organizations(self):
        """List the organizations this user has access to"""
        url = "{}/organizations".format(self.API_URL)
        self.debug("Sending GET request to URL {}".format(url))
        res = self.session.get(url)
        res.raise_for_status()
        return res.json()

    def find_user_orgs(self, email):
        """Find organizations given user belongs to"""
        orgs = self.list_organizations()
        return [org for org in orgs if Flowdock.user_in_org(email, org)]

    @staticmethod
    def user_in_org(email, org):
        """Chek if user is part of organization"""
        for user in org['users']:
            if user['email'] == email:
                return True
        return False

    def delete_user_from_org(self, user, org):
        """Delete given user from given organization."""
        url = "{}/organizations/{}/users/{}".format(
            self.API_URL, org['parameterized_name'], user['id'])
        self.debug("Sending DELETE request to url {}".format(url))

        res = self.session.delete(url)
        res.raise_for_status()

    def find_inactive_in_org(self, org, days=90, null=False):
        """Find inactive users in Flowdock organization

        Flowdock has unofficial API /organizations/:organization/audits/users/
        that list when users have been last active in that organization. It is
        undocumented but seems to work fairly well. This method lists users
        that have not been active during last days.

        Arguments:
        org -- parameterized flowdock organization name to check
        Keyword arguments:
        days -- how many days since last activity is considered inactive.
        null -- list users whose last activity date is not known for some
        reason.
        """
        url = "{}/organizations/{}/audits/users/".format(
            self.API_URL, org)
        self.debug("Sending GET request to URL {}".format(url))
        res = self.session.get(url)
        res.raise_for_status()
        users = res.json()

        if null:
            return [x for x in users if x['accessed_at'] is None]

        limit = datetime.now() - timedelta(days=days)
        users = [x for x in users if x['accessed_at'] is not None]
        users = [x for x in users if _last_access_before(x, limit)]
        return users

    def close(self):
        """Close the http session used internally.

        This method should be called when the API object is not needed anymore
        to free resources from client and server.
        """
        self.session.close()
开发者ID:futurice,项目名称:flowdock-management,代码行数:93,代码来源:flowdock.py

示例9: __init__

# 需要导入模块: from requests import Session [as 别名]
# 或者: from requests.Session import delete [as 别名]
class CouchbaseServer:
    """ Installs Couchbase Server on machine host"""

    def __init__(self, url):
        self.url = url

        # Strip http prefix and port to store host
        host = self.url.replace("http://", "")
        host = host.replace(":8091", "")
        self.host = host
        self.remote_executor = RemoteExecutor(self.host)

        self._session = Session()
        self._session.auth = ("Administrator", "password")

    def delete_buckets(self):
        count = 0
        while count < 3:
            resp = self._session.get("{}/pools/default/buckets".format(self.url))
            log_r(resp)
            resp.raise_for_status()

            obj = json.loads(resp.text)

            existing_bucket_names = []
            for entry in obj:
                existing_bucket_names.append(entry["name"])

            log_info("Existing buckets: {}".format(existing_bucket_names))
            log_info("Deleting buckets: {}".format(existing_bucket_names))

            # HACK around Couchbase Server issue where issuing a bucket delete via REST occasionally returns 500 error
            delete_num = 0
            # Delete existing buckets
            for bucket_name in existing_bucket_names:
                resp = self._session.delete("{0}/pools/default/buckets/{1}".format(self.url, bucket_name))
                log_r(resp)
                if resp.status_code == 200:
                    delete_num += 1

            if delete_num == len(existing_bucket_names):
                break
            else:
                # A 500 error may have occured, query for buckets and try to delete them again
                time.sleep(5)
                count += 1

        # Check that max retries did not occur
        if count == 3:
            raise CBServerError("Max retries for bucket creation hit. Could not delete buckets!")

    def wait_for_ready_state(self):
        """
        Verify all server node is in are in a "healthy" state to avoid sync_gateway startup failures
        Work around for this - https://github.com/couchbase/sync_gateway/issues/1745
        """
        start = time.time()
        while True:

            if time.time() - start > keywords.constants.CLIENT_REQUEST_TIMEOUT:
                raise Exception("Verify Docs Present: TIMEOUT")

            # Verfy the server is in a "healthy", not "warmup" state
            try:
                resp = self._session.get("{}/pools/nodes".format(self.url))
                log_r(resp)
            except ConnectionError:
                # If bringing a server online, there may be some connnection issues. Continue and try again.
                time.sleep(1)
                continue

            resp_obj = resp.json()

            all_nodes_healthy = True
            for node in resp_obj["nodes"]:
                if node["status"] != "healthy":
                    all_nodes_healthy = False
                    log_info("Node is still not healthy. Status: {} Retrying ...".format(node["status"]))
                    time.sleep(1)

            if not all_nodes_healthy:
                continue

            log_info("All nodes are healthy")
            log_debug(resp_obj)
            # All nodes are heathy if it made it to here
            break

    def get_available_ram(self):
        """
        Call the Couchbase REST API to get the total memory available on the machine
        """
        resp = self._session.get("{}/pools/default".format(self.url))
        resp.raise_for_status()
        resp_json = resp.json()

        # Workaround for https://github.com/couchbaselabs/mobile-testkit/issues/709
        # where some node report mem_total = 0. Loop over all the nodes and find highest val
        mem_total_highest = 0
        for node in resp_json["nodes"]:
#.........这里部分代码省略.........
开发者ID:couchbaselabs,项目名称:mobile-testkit,代码行数:103,代码来源:CouchbaseServer.py

示例10: HTTPClient

# 需要导入模块: from requests import Session [as 别名]
# 或者: from requests.Session import delete [as 别名]
class HTTPClient(object):
    def __init__(self, base_url, auth_params):
        """Initialize a new opp connection. Requires user name and password."""
        logger.debug("START: OPP API connection with BASE_URL: {0}".format(base_url))
        self.base_url = base_url
        self.session = Session()
        self.session.verify = opp.config.config.ssl_verify
        self.auth_params = auth_params
        self.operations = dict(GET=self.get, POST=self.post, PUT=self.put, DELETE=self.delete)
        # for internal usage
        self.response = None

    def __call__(self, request_type, params, url, return_type):
        """

        :param request_type:
        :param params:
        :param url:
        :param return_type:
        :return: :raise ValueError:
        """
        if request_type == 'POST':
            params.update({"customParameters[SHOPPER_pluginId]": "Python"})
            if opp.config.config.mode == opp.config.TEST_INTERNAL:
                params.update({"testMode": "INTERNAL"})
            if opp.config.config.mode == opp.config.TEST_EXTERNAL:
                params.update({"testMode": "EXTERNAL"})
        if self.auth_params:
            params.update(self.auth_params)
        try:
            result = self.operations[request_type](params, url, return_type)
            logger.debug("SUCCESS: {0} {1}".format(request_type, url))
            return result
        except ValueError as v:
            # JSON encoding failed
            logger.debug("ERROR: {0} {1}".format(request_type, url))

            if self.response is not None:
                raise ValueError(self.response.content, self.response.status_code)
            else:
                raise ValueError()

    def put(self, params, url, return_type):
        """

        :param params:
        :param url:
        :param return_type:
        :return:
        """
        return self._check_response(self.session.put(self.base_url + url, params,
                                                     timeout=opp.config.config.request_timeout,
                                                     hooks=dict(response=self._request_callback), ).json(), return_type)

    def post(self, params, url, return_type):
        """

        :param params:
        :param url:
        :param return_type:
        :return:
        """
        json = self.session.post(self.base_url + url, params, timeout=opp.config.config.request_timeout,
                                 hooks=dict(response=self._request_callback)).json()
        return self._check_response(json, return_type)

    def delete(self, params, url, return_type):
        """

        :param params:
        :param url:
        :param return_type:
        :return:
        """
        return self._check_response(self.session.delete(self.base_url + url, params=params,
                                                        timeout=opp.config.config.request_timeout,
                                                        hooks=dict(response=self._request_callback)).json(),
                                    return_type)

    def get(self, params, url, return_type):
        """

        :param params:
        :param url:
        :param return_type:
        :return:
        """
        return self._check_response(self.session.get(self.base_url + url, params=params,
                                                     timeout=opp.config.config.request_timeout,
                                                     hooks=dict(response=self._request_callback)).json(), return_type)

    def _request_callback(self, r, *args, **kwargs):
        """

        :param r:
        :param args:
        :param kwargs:
        """
        self.response = r

#.........这里部分代码省略.........
开发者ID:OpenPaymentPlatform,项目名称:python,代码行数:103,代码来源:core.py

示例11: teardown_marathon_tf_session

# 需要导入模块: from requests import Session [as 别名]
# 或者: from requests.Session import delete [as 别名]
def teardown_marathon_tf_session(marathon_url_str, marathon_usr, marathon_usrpwd, tsknom_str, tsk_idx):
   s = Session()
   marathon_url_str = marathon_url_str.replace("marathon://", "http://")
   resp = s.delete(url='%s/v2/apps/%s%d' % (marathon_url_str, tsknom_str, tsk_idx), auth=HTTPBasicAuth(marathon_usr, marathon_usrpwd))
开发者ID:ct-clmsn,项目名称:distributed-tensorflow-orchestration,代码行数:6,代码来源:dtforchestrator.py

示例12: DefaultClient

# 需要导入模块: from requests import Session [as 别名]
# 或者: from requests.Session import delete [as 别名]

#.........这里部分代码省略.........
            headers=res.headers,
            status_code=res.status_code,
            content=res.text,
            status_text=res.reason
        )

    def patch(self, url, data=None, params=None, headers=None, auth=None):
        """HTTP PATCH method.

        :param url: request URL
        :type url: str
        :param data: request payload
        :type data: str or dict or None
        :param params: request parameters
        :type params: dict or None
        :param headers: request headers
        :type headers: dict or None
        :param auth: username and password tuple
        :type auth: tuple or None
        :returns: ArangoDB http response object
        :rtype: arango.response.Response
        """
        res = self.session.patch(
            url=url,
            data=data,
            params=params,
            headers=headers,
        )
        return Response(
            method="patch",
            url=url,
            headers=res.headers,
            status_code=res.status_code,
            content=res.text,
            status_text=res.reason
        )

    def delete(self, url, params=None, headers=None, auth=None):
        """HTTP DELETE method.

        :param url: request URL
        :type url: str
        :param params: request parameters
        :type params: dict or None
        :param headers: request headers
        :type headers: dict or None
        :param auth: username and password tuple
        :type auth: tuple or None
        :returns: ArangoDB http response object
        :rtype: arango.response.Response
        """
        res = self.session.delete(
            url=url,
            params=params,
            headers=headers,
            auth=auth,
        )
        return Response(
            method="delete",
            url=url,
            headers=res.headers,
            status_code=res.status_code,
            content=res.text,
            status_text=res.reason
        )

    def options(self, url, data=None, params=None, headers=None, auth=None):
        """HTTP OPTIONS method.

        :param url: request URL
        :type url: str
        :param data: request payload
        :type data: str or dict or None
        :param params: request parameters
        :type params: dict or None
        :param headers: request headers
        :type headers: dict or None
        :param auth: username and password tuple
        :type auth: tuple or None
        :returns: ArangoDB http response object
        :rtype: arango.response.Response
        """
        res = self.session.options(
            url=url,
            data="" if data is None else data,
            params={} if params is None else params,
            headers={} if headers is None else headers,
        )
        return Response(
            method="options",
            url=url,
            headers=res.headers,
            status_code=res.status_code,
            content=res.text,
            status_text=res.reason
        )

    def close(self):
        """Close the HTTP session."""
        self.session.close()
开发者ID:allanino,项目名称:python-arango,代码行数:104,代码来源:default.py

示例13: HRClient

# 需要导入模块: from requests import Session [as 别名]
# 或者: from requests.Session import delete [as 别名]
class HRClient():
    def __init__(self, username, password):
        self.session = Session()
        self.session.hooks['response'].append(addArgsToHook(logAndValidate, getCsrf, session = self.session))
        self.login(username, password)

    def __enter__(self):
        return self

    def __exit__(self, *args):
        self.logout()

    # added dummy timeout argument to not skip CSRF passing
    def login(self, username, password):
        self.session.get(HR + '/dashboard', timeout = 120)
        data = {
            'login': username,
            'password': password,
            'remember_me': False,
        }
        self.session.post(HR + '/auth/login', json = data, timeout = 120)

    # added dummy timeout argument to not skip CSRF passing
    def logout(self):
        return self.session.delete(HR + '/auth/logout', timeout = 120)

    # added dummy timeout argument to not skip CSRF passing
    def getUserModel(self):
        url = HR_REST + CONTESTS + '/master/hackers/me'
        json = {"updated_modal_profiled_data": {"updated": True}}
        hooks = {'response': addArgsToHook(logAndValidate, getCsrf, session = self.session)}
        return self.session.put(url, json = json, hooks = hooks).json()['model']

    # TODO add validation and sanity checks on model counts
    def getNewModels(self, models):
        if not models:
            models = {}

        contests = {}
        url = HR_REST + '/hackers/me/myrank_contests'
        contestSlugs = {'master'} | {c['slug'] for c in self.getModels(url, type = 'recent')}
        for slug in contestSlugs:
            url = HR_REST + CONTESTS + '/' + slug

            # get submission info, not models
            submissionIds = {s['id'] for s in self.getModels(url + SUBMISSIONS)}
            if slug in models and 'submissions' in models[slug]:
                submissionIds -= models[slug]['submissions'].keys()

            # break out early if contest is already represented
            # TODO break each of these separate processes into separate functions and do sequentially
            if not submissionIds:
                continue

            # TODO is this necessary? does every challenge have an id?
            # get challenge info, not models
            challengeIds = {c['id'] for c in self.getModels(url + CHALLENGES)}
            if slug in models and 'challenges' in models[slug]:
                challengeIds -= models[slug]['challenges'].keys()

            # uncomment if only want challenge data for challenges attempted or with accompanying submissions
            #challengeSlugs = {sub['challenge_slug'] for sub in submissions.values()}
            #challengeIds = {sub['challenge_id'] for sub in submissions.values()}

            # begin creation of contest
            contest = {}
            contest['model'] = self.session.get(url).json()['model']
            contest['submissions'] = self.getModelsKeyed(url + SUBMISSIONS, submissionIds)
            contest['challenges'] = self.getModelsKeyed(url + CHALLENGES, challengeIds)
            contests[slug] = contest

        return contests

    def getModelsKeyed(self, url, ids):
        models = {}
        total = len(ids)

        for curr, i in enumerate(ids):
            model = self.session.get(url + '/' + str(i), data = {'remaining': total - curr - 1}).json()['model']
            if not model:
                continue
            models[i] = model

        return models

    # get all models from particular GET request
    # NOTE must make two calls because order is sometimes not preserved between requests
    def getModels(self, url, **params):
        r = self.session.get(url, params = params).json()
        count = len(r['models'])
        total = r['total']

        # return models if all have been acquired
        if count >= total:
            return r['models']

        params['limit'] = total
        return self.session.get(url, params = params).json()['models']
开发者ID:jlindsay90,项目名称:hackerrank-to-git,代码行数:100,代码来源:hackerrankops.py

示例14: Server

# 需要导入模块: from requests import Session [as 别名]
# 或者: from requests.Session import delete [as 别名]
class Server(object):
    def __init__(self, host="http://localhost:5984", auth=None,
                 trust_env=False):
        self.host = host
        self.session = Session()
        # trust env make use of get_netrc that is soooo slow
        self.session.trust_env = trust_env
        self.session.auth = auth
        self.session.headers = {
                "Content-Type": "application/json",
                }

    def __getitem__(self, name):
        return Database(name, server=self, create=False)

    def __len__(self):
        return len(self.get_databases())

    def __nonzero__(self):
        """
        Returns if server is available
        """

        try:
            self.session.head(self.host)
            return True
        except:
            return False

    def __delitem__(self, name):
        self.delete_db(name)

    def __contains__(self, db_or_name):
        """
        Tests if the database exists
        """

        name = db_or_name
        if isinstance(db_or_name, Database):
            name = db_or_name.name

        request = self.session.head(self.host + "/" + name)
        if request.status_code == 404:
            return False
        return True

    def __iter__(self):
        """
        Iterates over all the databases and returns Database instances
        """

        return (Database(name, server=self) for name in self.get_databases())

    def uuids(self, count=1):
        """
        Returns a a lists of "count" uuids generated in the server
        """

        request = self.session.get(self.host + "/_uuids",
                params={"count": count})
        return request.json()["uuids"]

    def get_databases(self):
        request = self.session.get(self.host + "/_all_dbs")
        return request.json()

    def version(self):
        request = self.session.get(self.host)
        return request.json()["version"]

    def create_db(self, name):
        """
        Try to create a new database or raise error

        Posible Errors: DBExists, AuthFail
        """

        return Database(name, server=self, create=True)

    def delete_db(self, db_or_name):
        """
        Try to delete database or raise error

        Posible Errors: DBNotExists, AuthFail
        """

        name = db_or_name
        if isinstance(db_or_name, Database):
            name = db_or_name.name

        request = self.session.delete(self.host + "/" + name)
        if not request.ok:
            if request.status_code == 401:
                raise excepts.AuthFail
            elif request.status_code == 404:
                raise excepts.DBNotExists
            raise Exception(request.status_code)
开发者ID:Roger,项目名称:coucher,代码行数:99,代码来源:client.py


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