docstring
stringlengths
52
499
function
stringlengths
67
35.2k
__index_level_0__
int64
52.6k
1.16M
A helper method to get or create a backend with thread locking. This ensures that only one backend is used per-file per-process, so that thread and process locks are appropriately shared. Args: filename: The full path to the credential storage file. Returns: An instance of :class:`_MultiprocessStorageBackend`.
def _get_backend(filename): filename = os.path.abspath(filename) with _backends_lock: if filename not in _backends: _backends[filename] = _MultiprocessStorageBackend(filename) return _backends[filename]
325,564
Converts stringifed scope value to a list. If scopes is a list then it is simply passed through. If scopes is an string then a list of each individual scope is returned. Args: scopes: a string or iterable of strings, the scopes. Returns: The scopes in a list.
def string_to_scopes(scopes): if not scopes: return [] elif isinstance(scopes, six.string_types): return scopes.split(' ') else: return scopes
325,577
Parses unique key-value parameters from urlencoded content. Args: content: string, URL-encoded key-value pairs. Returns: dict, The key-value pairs from ``content``. Raises: ValueError: if one of the keys is repeated.
def parse_unique_urlencoded(content): urlencoded_params = urllib.parse.parse_qs(content) params = {} for key, value in six.iteritems(urlencoded_params): if len(value) != 1: msg = ('URL-encoded content contains a repeated value:' '%s -> %s' % (key, ', '.join(value))) raise ValueError(msg) params[key] = value[0] return params
325,578
Adds a query parameter to a url. Replaces the current value if it already exists in the URL. Args: url: string, url to add the query parameter to. name: string, query parameter name. value: string, query parameter value. Returns: Updated query parameter. Does not update the url if value is None.
def _add_query_parameter(url, name, value): if value is None: return url else: return update_query_params(url, {name: value})
325,580
Adds a user-agent to the headers. Args: headers: dict, request headers to add / modify user agent within. user_agent: str, the user agent to add. Returns: dict, the original headers passed in, but modified if the user agent is not None.
def _apply_user_agent(headers, user_agent): if user_agent is not None: if 'user-agent' in headers: headers['user-agent'] = (user_agent + ' ' + headers['user-agent']) else: headers['user-agent'] = user_agent return headers
325,584
Forces header keys and values to be strings, i.e not unicode. The httplib module just concats the header keys and values in a way that may make the message header a unicode string, which, if it then tries to contatenate to a binary request body may result in a unicode decode error. Args: headers: dict, A dictionary of headers. Returns: The same dictionary but with all the keys converted to strings.
def clean_headers(headers): clean = {} try: for k, v in six.iteritems(headers): if not isinstance(k, six.binary_type): k = str(k) if not isinstance(v, six.binary_type): v = str(v) clean[_helpers._to_bytes(k)] = _helpers._to_bytes(v) except UnicodeEncodeError: from oauth2client.client import NonAsciiHeaderError raise NonAsciiHeaderError(k, ': ', v) return clean
325,585
Prepares an HTTP object's request method for auth. Wraps HTTP requests with logic to catch auth failures (typically identified via a 401 status code). In the event of failure, tries to refresh the token used and then retry the original request. Args: credentials: Credentials, the credentials used to identify the authenticated user. http: httplib2.Http, an http object to be used to make auth requests.
def wrap_http_for_auth(credentials, http): orig_request_method = http.request # The closure that will replace 'httplib2.Http.request'. def new_request(uri, method='GET', body=None, headers=None, redirections=httplib2.DEFAULT_MAX_REDIRECTS, connection_type=None): if not credentials.access_token: _LOGGER.info('Attempting refresh to obtain ' 'initial access_token') credentials._refresh(orig_request_method) # Clone and modify the request headers to add the appropriate # Authorization header. headers = _initialize_headers(headers) credentials.apply(headers) _apply_user_agent(headers, credentials.user_agent) body_stream_position = None # Check if the body is a file-like stream. if all(getattr(body, stream_prop, None) for stream_prop in _STREAM_PROPERTIES): body_stream_position = body.tell() resp, content = request(orig_request_method, uri, method, body, clean_headers(headers), redirections, connection_type) # A stored token may expire between the time it is retrieved and # the time the request is made, so we may need to try twice. max_refresh_attempts = 2 for refresh_attempt in range(max_refresh_attempts): if resp.status not in REFRESH_STATUS_CODES: break _LOGGER.info('Refreshing due to a %s (attempt %s/%s)', resp.status, refresh_attempt + 1, max_refresh_attempts) credentials._refresh(orig_request_method) credentials.apply(headers) if body_stream_position is not None: body.seek(body_stream_position) resp, content = request(orig_request_method, uri, method, body, clean_headers(headers), redirections, connection_type) return resp, content # Replace the request method with our own closure. http.request = new_request # Set credentials as a property of the request method. http.request.credentials = credentials
325,586
Composes the value for the 'state' parameter. Packs the current request URI and an XSRF token into an opaque string that can be passed to the authentication server via the 'state' parameter. Args: request_handler: webapp.RequestHandler, The request. user: google.appengine.api.users.User, The current user. Returns: The state value as a string.
def _build_state_value(request_handler, user): uri = request_handler.request.url token = xsrfutil.generate_token(xsrf_secret_key(), user.user_id(), action_id=str(uri)) return uri + ':' + token
325,604
Parse the value of the 'state' parameter. Parses the value and validates the XSRF token in the state parameter. Args: state: string, The value of the state parameter. user: google.appengine.api.users.User, The current user. Returns: The redirect URI, or None if XSRF token is not valid.
def _parse_state_value(state, user): uri, token = state.rsplit(':', 1) if xsrfutil.validate_token(xsrf_secret_key(), token, user.user_id(), action_id=uri): return uri else: return None
325,605
Constructor for AppAssertionCredentials Args: scope: string or iterable of strings, scope(s) of the credentials being requested. **kwargs: optional keyword args, including: service_account_id: service account id of the application. If None or unspecified, the default service account for the app is used.
def __init__(self, scope, **kwargs): self.scope = _helpers.scopes_to_string(scope) self._kwargs = kwargs self.service_account_id = kwargs.get('service_account_id', None) self._service_account_email = None # Assertion type is no longer used, but still in the # parent class signature. super(AppAssertionCredentials, self).__init__(None)
325,607
Refreshes the access token. Since the underlying App Engine app_identity implementation does its own caching we can skip all the storage hoops and just to a refresh using the API. Args: http: unused HTTP object Raises: AccessTokenRefreshError: When the refresh fails.
def _refresh(self, http): try: scopes = self.scope.split() (token, _) = app_identity.get_access_token( scopes, service_account_id=self.service_account_id) except app_identity.Error as e: raise client.AccessTokenRefreshError(str(e)) self.access_token = token
325,608
Write a Credentials to the datastore. Args: credentials: Credentials, the credentials to store.
def locked_put(self, credentials): entity = self._model.get_or_insert(self._key_name) setattr(entity, self._property_name, credentials) entity.put() if self._cache: self._cache.set(self._key_name, credentials.to_json())
325,620
Decorator that starts the OAuth 2.0 dance. Starts the OAuth dance for the logged in user if they haven't already granted access for this application. Args: method: callable, to be decorated method of a webapp.RequestHandler instance.
def oauth_required(self, method): def check_oauth(request_handler, *args, **kwargs): if self._in_error: self._display_error_message(request_handler) return user = users.get_current_user() # Don't use @login_decorator as this could be used in a # POST request. if not user: request_handler.redirect(users.create_login_url( request_handler.request.uri)) return self._create_flow(request_handler) # Store the request URI in 'state' so we can use it later self.flow.params['state'] = _build_state_value( request_handler, user) self.credentials = self._storage_class( self._credentials_class, None, self._credentials_property_name, user=user).get() if not self.has_credentials(): return request_handler.redirect(self.authorize_url()) try: resp = method(request_handler, *args, **kwargs) except client.AccessTokenRefreshError: return request_handler.redirect(self.authorize_url()) finally: self.credentials = None return resp return check_oauth
325,624
Create the Flow object. The Flow is calculated lazily since we don't know where this app is running until it receives a request, at which point redirect_uri can be calculated and then the Flow object can be constructed. Args: request_handler: webapp.RequestHandler, the request handler.
def _create_flow(self, request_handler): if self.flow is None: redirect_uri = request_handler.request.relative_url( self._callback_path) # Usually /oauth2callback self.flow = client.OAuth2WebServerFlow( self._client_id, self._client_secret, self._scope, redirect_uri=redirect_uri, user_agent=self._user_agent, auth_uri=self._auth_uri, token_uri=self._token_uri, revoke_uri=self._revoke_uri, **self._kwargs)
325,625
Returns an authorized http instance. Must only be called from within an @oauth_required decorated method, or from within an @oauth_aware decorated method where has_credentials() returns True. Args: *args: Positional arguments passed to httplib2.Http constructor. **kwargs: Positional arguments passed to httplib2.Http constructor.
def http(self, *args, **kwargs): return self.credentials.authorize( transport.get_http_object(*args, **kwargs))
325,627
Generates a URL-safe token for the given user, action, time tuple. Args: key: secret key to use. user_id: the user ID of the authenticated user. action_id: a string identifier of the action they requested authorization for. when: the time in seconds since the epoch at which the user was authorized for this action. If not set the current time is used. Returns: A string XSRF protection token.
def generate_token(key, user_id, action_id='', when=None): digester = hmac.new(_helpers._to_bytes(key, encoding='utf-8')) digester.update(_helpers._to_bytes(str(user_id), encoding='utf-8')) digester.update(DELIMITER) digester.update(_helpers._to_bytes(action_id, encoding='utf-8')) digester.update(DELIMITER) when = _helpers._to_bytes(str(when or int(time.time())), encoding='utf-8') digester.update(when) digest = digester.digest() token = base64.urlsafe_b64encode(digest + DELIMITER + when) return token
325,630
Validate parsed client secrets from a file. Args: clientsecrets_dict: dict, a dictionary holding the client secrets. Returns: tuple, a string of the client type and the information parsed from the file.
def _validate_clientsecrets(clientsecrets_dict): _INVALID_FILE_FORMAT_MSG = ( 'Invalid file format. See ' 'https://developers.google.com/api-client-library/' 'python/guide/aaa_client_secrets') if clientsecrets_dict is None: raise InvalidClientSecretsError(_INVALID_FILE_FORMAT_MSG) try: (client_type, client_info), = clientsecrets_dict.items() except (ValueError, AttributeError): raise InvalidClientSecretsError( _INVALID_FILE_FORMAT_MSG + ' ' 'Expected a JSON object with a single property for a "web" or ' '"installed" application') if client_type not in VALID_CLIENT: raise InvalidClientSecretsError( 'Unknown client type: {0}.'.format(client_type)) for prop_name in VALID_CLIENT[client_type]['required']: if prop_name not in client_info: raise InvalidClientSecretsError( 'Missing property "{0}" in a client type of "{1}".'.format( prop_name, client_type)) for prop_name in VALID_CLIENT[client_type]['string']: if client_info[prop_name].startswith('[['): raise InvalidClientSecretsError( 'Property "{0}" is not configured.'.format(prop_name)) return client_type, client_info
325,632
Refreshes the access token. Args: http: unused HTTP object
def _refresh(self, http): self.devshell_response = _SendRecv() self.access_token = self.devshell_response.access_token expires_in = self.devshell_response.expires_in if expires_in is not None: delta = datetime.timedelta(seconds=expires_in) self.token_expiry = client._UTCNOW() + delta else: self.token_expiry = None
325,638
Constructor. Args: service_name: string, The name of the service under which the credentials are stored. user_name: string, The name of the user to store credentials for.
def __init__(self, service_name, user_name): super(Storage, self).__init__(lock=threading.Lock()) self._service_name = service_name self._user_name = user_name
325,639
Write Credentials to file. Args: credentials: Credentials, the credentials to store.
def locked_put(self, credentials): keyring.set_password(self._service_name, self._user_name, credentials.to_json())
325,641
Convert the contents of a PKCS#12 key to PEM using pyOpenSSL. Args: private_key_bytes: Bytes. PKCS#12 key in DER format. private_key_password: String. Password for PKCS#12 key. Returns: String. PEM contents of ``private_key_bytes``.
def pkcs12_key_as_pem(private_key_bytes, private_key_password): private_key_password = _helpers._to_bytes(private_key_password) pkcs12 = crypto.load_pkcs12(private_key_bytes, private_key_password) return crypto.dump_privatekey(crypto.FILETYPE_PEM, pkcs12.get_privatekey())
325,642
Verifies a message against a signature. Args: message: string or bytes, The message to verify. If string, will be encoded to bytes as utf-8. signature: string or bytes, The signature on the message. If string, will be encoded to bytes as utf-8. Returns: True if message was signed by the private key associated with the public key that this object was constructed with.
def verify(self, message, signature): message = _helpers._to_bytes(message, encoding='utf-8') signature = _helpers._to_bytes(signature, encoding='utf-8') try: crypto.verify(self._pubkey, signature, message, 'sha256') return True except crypto.Error: return False
325,643
Construct a Verified instance from a string. Args: key_pem: string, public key in PEM format. is_x509_cert: bool, True if key_pem is an X509 cert, otherwise it is expected to be an RSA key in PEM format. Returns: Verifier instance. Raises: OpenSSL.crypto.Error: if the key_pem can't be parsed.
def from_string(key_pem, is_x509_cert): key_pem = _helpers._to_bytes(key_pem) if is_x509_cert: pubkey = crypto.load_certificate(crypto.FILETYPE_PEM, key_pem) else: pubkey = crypto.load_privatekey(crypto.FILETYPE_PEM, key_pem) return OpenSSLVerifier(pubkey)
325,644
Signs a message. Args: message: bytes, Message to be signed. Returns: string, The signature of the message for the given key.
def sign(self, message): message = _helpers._to_bytes(message, encoding='utf-8') return crypto.sign(self._key, message, 'sha256')
325,645
Construct a Signer instance from a string. Args: key: string, private key in PKCS12 or PEM format. password: string, password for the private key file. Returns: Signer instance. Raises: OpenSSL.crypto.Error if the key can't be parsed.
def from_string(key, password=b'notasecret'): key = _helpers._to_bytes(key) parsed_pem_key = _helpers._parse_pem_key(key) if parsed_pem_key: pkey = crypto.load_privatekey(crypto.FILETYPE_PEM, parsed_pem_key) else: password = _helpers._to_bytes(password, encoding='utf-8') pkey = crypto.load_pkcs12(key, password).get_privatekey() return OpenSSLSigner(pkey)
325,646
Verifies a message against a signature. Args: message: string or bytes, The message to verify. If string, will be encoded to bytes as utf-8. signature: string or bytes, The signature on the message. Returns: True if message was signed by the private key associated with the public key that this object was constructed with.
def verify(self, message, signature): message = _helpers._to_bytes(message, encoding='utf-8') return PKCS1_v1_5.new(self._pubkey).verify( SHA256.new(message), signature)
325,647
Construct a Verified instance from a string. Args: key_pem: string, public key in PEM format. is_x509_cert: bool, True if key_pem is an X509 cert, otherwise it is expected to be an RSA key in PEM format. Returns: Verifier instance.
def from_string(key_pem, is_x509_cert): if is_x509_cert: key_pem = _helpers._to_bytes(key_pem) pemLines = key_pem.replace(b' ', b'').split() certDer = _helpers._urlsafe_b64decode(b''.join(pemLines[1:-1])) certSeq = DerSequence() certSeq.decode(certDer) tbsSeq = DerSequence() tbsSeq.decode(certSeq[0]) pubkey = RSA.importKey(tbsSeq[6]) else: pubkey = RSA.importKey(key_pem) return PyCryptoVerifier(pubkey)
325,648
Signs a message. Args: message: string, Message to be signed. Returns: string, The signature of the message for the given key.
def sign(self, message): message = _helpers._to_bytes(message, encoding='utf-8') return PKCS1_v1_5.new(self._key).sign(SHA256.new(message))
325,649
Construct a Signer instance from a string. Args: key: string, private key in PEM format. password: string, password for private key file. Unused for PEM files. Returns: Signer instance. Raises: NotImplementedError if the key isn't in PEM format.
def from_string(key, password='notasecret'): parsed_pem_key = _helpers._parse_pem_key(_helpers._to_bytes(key)) if parsed_pem_key: pkey = RSA.importKey(parsed_pem_key) else: raise NotImplementedError( 'No key in PEM format was detected. This implementation ' 'can only use the PyCrypto library for keys in PEM ' 'format.') return PyCryptoSigner(pkey)
325,650
Generates a 'code_verifier' as described in section 4.1 of RFC 7636. This is a 'high-entropy cryptographic random string' that will be impractical for an attacker to guess. Args: n_bytes: integer between 31 and 96, inclusive. default: 64 number of bytes of entropy to include in verifier. Returns: Bytestring, representing urlsafe base64-encoded random data.
def code_verifier(n_bytes=64): verifier = base64.urlsafe_b64encode(os.urandom(n_bytes)).rstrip(b'=') # https://tools.ietf.org/html/rfc7636#section-4.1 # minimum length of 43 characters and a maximum length of 128 characters. if len(verifier) < 43: raise ValueError("Verifier too short. n_bytes must be > 30.") elif len(verifier) > 128: raise ValueError("Verifier too long. n_bytes must be < 97.") else: return verifier
325,656
Creates a 'code_challenge' as described in section 4.2 of RFC 7636 by taking the sha256 hash of the verifier and then urlsafe base64-encoding it. Args: verifier: bytestring, representing a code_verifier as generated by code_verifier(). Returns: Bytestring, representing a urlsafe base64-encoded sha256 hash digest, without '=' padding.
def code_challenge(verifier): digest = hashlib.sha256(verifier).digest() return base64.urlsafe_b64encode(digest).rstrip(b'=')
325,657
Constructor for AppAssertionCredentials Args: email: an email that specifies the service account to use. Only necessary if using custom service accounts (see https://cloud.google.com/compute/docs/access/create-enable-service-accounts-for-instances#createdefaultserviceaccount).
def __init__(self, email=None, *args, **kwargs): if 'scopes' in kwargs: warnings.warn(_SCOPES_WARNING) kwargs['scopes'] = None # Assertion type is no longer used, but still in the # parent class signature. super(AppAssertionCredentials, self).__init__(None, *args, **kwargs) self.service_account_email = email self.scopes = None self.invalid = True
325,658
Retrieves service account info for invalid credentials. Args: http: an object to be used to make HTTP requests.
def _retrieve_info(self, http): if self.invalid: info = _metadata.get_service_account_info( http, service_account=self.service_account_email or 'default') self.invalid = False self.service_account_email = info['email'] self.scopes = info['scopes']
325,659
Refreshes the access token. Skip all the storage hoops and just refresh using the API. Args: http: an object to be used to make HTTP requests. Raises: HttpAccessTokenRefreshError: When the refresh fails.
def _refresh(self, http): try: self._retrieve_info(http) self.access_token, self.token_expiry = _metadata.get_token( http, service_account=self.service_account_email) except http_client.HTTPException as err: raise client.HttpAccessTokenRefreshError(str(err))
325,660
Constructor for Storage. Args: model: string, fully qualified name of db.Model model class. key_name: string, key name for the entity that has the credentials key_value: string, key value for the entity that has the credentials. property_name: string, name of the property that is an CredentialsProperty.
def __init__(self, model_class, key_name, key_value, property_name): super(DjangoORMStorage, self).__init__() self.model_class = model_class self.key_name = key_name self.key_value = key_value self.property_name = property_name
325,661
Write a Credentials to the Django datastore. Args: credentials: Credentials, the credentials to store.
def locked_put(self, credentials): entity, _ = self.model_class.objects.get_or_create( **{self.key_name: self.key_value}) setattr(entity, self.property_name, credentials) entity.save()
325,663
Save the credentials to the dictionary. Args: credentials: A :class:`oauth2client.client.OAuth2Credentials` instance.
def locked_put(self, credentials): serialized = credentials.to_json() self._dictionary[self._key] = serialized
325,667
Validates a value as a proper Flow object. Args: value: A value to be set on the property. Raises: TypeError if the value is not an instance of Flow.
def _validate(self, value): _LOGGER.info('validate: Got type %s', type(value)) if value is not None and not isinstance(value, client.Flow): raise TypeError( 'Property {0} must be convertible to a flow ' 'instance; received: {1}.'.format(self._name, value))
325,668
Converts our stored JSON string back to the desired type. Args: value: A value from the datastore to be converted to the desired type. Returns: A deserialized Credentials (or subclass) object, else None if the value can't be parsed.
def _from_base_type(self, value): if not value: return None try: # Uses the from_json method of the implied class of value credentials = client.Credentials.new_from_json(value) except ValueError: credentials = None return credentials
325,669
Creates a Web Server Flow Args: request: A Django request object. scopes: the request oauth2 scopes. return_url: The URL to return to after the flow is complete. Defaults to the path of the current request. Returns: An OAuth2 flow object that has been stored in the session.
def _make_flow(request, scopes, return_url=None): # Generate a CSRF token to prevent malicious requests. csrf_token = hashlib.sha256(os.urandom(1024)).hexdigest() request.session[_CSRF_KEY] = csrf_token state = json.dumps({ 'csrf_token': csrf_token, 'return_url': return_url, }) flow = client.OAuth2WebServerFlow( client_id=django_util.oauth2_settings.client_id, client_secret=django_util.oauth2_settings.client_secret, scope=scopes, state=state, redirect_uri=request.build_absolute_uri( urlresolvers.reverse("google_oauth:callback"))) flow_key = _FLOW_KEY.format(csrf_token) request.session[flow_key] = jsonpickle.encode(flow) return flow
325,670
Looks up the flow in session to recover information about requested scopes. Args: csrf_token: The token passed in the callback request that should match the one previously generated and stored in the request on the initial authorization view. Returns: The OAuth2 Flow object associated with this flow based on the CSRF token.
def _get_flow_for_token(csrf_token, request): flow_pickle = request.session.get(_FLOW_KEY.format(csrf_token), None) return None if flow_pickle is None else jsonpickle.decode(flow_pickle)
325,671
View that handles the user's return from OAuth2 provider. This view verifies the CSRF state and OAuth authorization code, and on success stores the credentials obtained in the storage provider, and redirects to the return_url specified in the authorize view and stored in the session. Args: request: Django request. Returns: A redirect response back to the return_url.
def oauth2_callback(request): if 'error' in request.GET: reason = request.GET.get( 'error_description', request.GET.get('error', '')) reason = html.escape(reason) return http.HttpResponseBadRequest( 'Authorization failed {0}'.format(reason)) try: encoded_state = request.GET['state'] code = request.GET['code'] except KeyError: return http.HttpResponseBadRequest( 'Request missing state or authorization code') try: server_csrf = request.session[_CSRF_KEY] except KeyError: return http.HttpResponseBadRequest( 'No existing session for this flow.') try: state = json.loads(encoded_state) client_csrf = state['csrf_token'] return_url = state['return_url'] except (ValueError, KeyError): return http.HttpResponseBadRequest('Invalid state parameter.') if client_csrf != server_csrf: return http.HttpResponseBadRequest('Invalid CSRF token.') flow = _get_flow_for_token(client_csrf, request) if not flow: return http.HttpResponseBadRequest('Missing Oauth2 flow.') try: credentials = flow.step2_exchange(code) except client.FlowExchangeError as exchange_error: return http.HttpResponseBadRequest( 'An error has occurred: {0}'.format(exchange_error)) get_storage(request).put(credentials) signals.oauth2_authorized.send(sender=signals.oauth2_authorized, request=request, credentials=credentials) return shortcuts.redirect(return_url)
325,672
Write Credentials to file. Args: credentials: Credentials, the credentials to store. Raises: IOError if the file is a symbolic link.
def locked_put(self, credentials): self._create_file_if_needed() _helpers.validate_file(self._filename) f = open(self._filename, 'w') f.write(credentials.to_json()) f.close()
325,678
Convert the field value from the provided model to a string. Used during model serialization. Args: obj: db.Model, model object Returns: string, the serialized field value
def value_to_string(self, obj): value = self._get_val_from_obj(obj) return self.get_prep_value(value)
325,682
Make a signed JWT. See http://self-issued.info/docs/draft-jones-json-web-token.html. Args: signer: crypt.Signer, Cryptographic signer. payload: dict, Dictionary of data to convert to JSON and then sign. key_id: string, (Optional) Key ID header. Returns: string, The JWT for the payload.
def make_signed_jwt(signer, payload, key_id=None): header = {'typ': 'JWT', 'alg': 'RS256'} if key_id is not None: header['kid'] = key_id segments = [ _helpers._urlsafe_b64encode(_helpers._json_encode(header)), _helpers._urlsafe_b64encode(_helpers._json_encode(payload)), ] signing_input = b'.'.join(segments) signature = signer.sign(signing_input) segments.append(_helpers._urlsafe_b64encode(signature)) logger.debug(str(segments)) return b'.'.join(segments)
325,683
Verifies signed content using a list of certificates. Args: message: string or bytes, The message to verify. signature: string or bytes, The signature on the message. certs: iterable, certificates in PEM format. Raises: AppIdentityError: If none of the certificates can verify the message against the signature.
def _verify_signature(message, signature, certs): for pem in certs: verifier = Verifier.from_string(pem, is_x509_cert=True) if verifier.verify(message, signature): return # If we have not returned, no certificate confirms the signature. raise AppIdentityError('Invalid token signature')
325,684
执行持久化处理: Args: key: 待处理的源文件 fops: 处理详细操作,规格详见 https://developer.qiniu.com/dora/manual/1291/persistent-data-processing-pfop force: 强制执行持久化处理开关 Returns: 一个dict变量,返回持久化处理的persistentId,类似{"persistentId": 5476bedf7823de4068253bae}; 一个ResponseInfo对象
def execute(self, key, fops, force=None): ops = ';'.join(fops) data = {'bucket': self.bucket, 'key': key, 'fops': ops} if self.pipeline: data['pipeline'] = self.pipeline if self.notify_url: data['notifyURL'] = self.notify_url if force == 1: data['force'] = 1 url = '{0}/pfop'.format(config.get_default('default_api_host')) return http._post_with_auth(url, data, self.auth)
325,689
删除文件: 删除指定资源,具体规格参考: http://developer.qiniu.com/docs/v6/api/reference/rs/delete.html Args: bucket: 待获取信息资源所在的空间 key: 待获取资源的文件名 Returns: 一个dict变量,成功返回NULL,失败返回{"error": "<errMsg string>"} 一个ResponseInfo对象
def delete(self, bucket, key): resource = entry(bucket, key) return self.__rs_do('delete', resource)
325,711
重命名文件: 给资源进行重命名,本质为move操作。 Args: bucket: 待操作资源所在空间 key: 待操作资源文件名 key_to: 目标资源文件名 Returns: 一个dict变量,成功返回NULL,失败返回{"error": "<errMsg string>"} 一个ResponseInfo对象
def rename(self, bucket, key, key_to, force='false'): return self.move(bucket, key, bucket, key_to, force)
325,712
移动文件: 将资源从一个空间到另一个空间,具体规格参考: http://developer.qiniu.com/docs/v6/api/reference/rs/move.html Args: bucket: 待操作资源所在空间 bucket_to: 目标资源空间名 key: 待操作资源文件名 key_to: 目标资源文件名 Returns: 一个dict变量,成功返回NULL,失败返回{"error": "<errMsg string>"} 一个ResponseInfo对象
def move(self, bucket, key, bucket_to, key_to, force='false'): resource = entry(bucket, key) to = entry(bucket_to, key_to) return self.__rs_do('move', resource, to, 'force/{0}'.format(force))
325,713
抓取文件: 从指定URL抓取资源,并将该资源存储到指定空间中,具体规格参考: http://developer.qiniu.com/docs/v6/api/reference/rs/fetch.html Args: url: 指定的URL bucket: 目标资源空间 key: 目标资源文件名 Returns: 一个dict变量,成功返回NULL,失败返回{"error": "<errMsg string>"} 一个ResponseInfo对象
def fetch(self, url, bucket, key=None): resource = urlsafe_base64_encode(url) to = entry(bucket, key) return self.__io_do(bucket, 'fetch', resource, 'to/{0}'.format(to))
325,714
镜像回源预取文件: 从镜像源站抓取资源到空间中,如果空间中已经存在,则覆盖该资源,具体规格参考 http://developer.qiniu.com/docs/v6/api/reference/rs/prefetch.html Args: bucket: 待获取资源所在的空间 key: 代获取资源文件名 Returns: 一个dict变量,成功返回NULL,失败返回{"error": "<errMsg string>"} 一个ResponseInfo对象
def prefetch(self, bucket, key): resource = entry(bucket, key) return self.__io_do(bucket, 'prefetch', resource)
325,715
修改文件mimeType: 主动修改指定资源的文件类型,具体规格参考: http://developer.qiniu.com/docs/v6/api/reference/rs/chgm.html Args: bucket: 待操作资源所在空间 key: 待操作资源文件名 mime: 待操作文件目标mimeType
def change_mime(self, bucket, key, mime): resource = entry(bucket, key) encode_mime = urlsafe_base64_encode(mime) return self.__rs_do('chgm', resource, 'mime/{0}'.format(encode_mime))
325,716
修改文件的存储类型 修改文件的存储类型为普通存储或者是低频存储,参考文档: https://developer.qiniu.com/kodo/api/3710/modify-the-file-type Args: bucket: 待操作资源所在空间 key: 待操作资源文件名 storage_type: 待操作资源存储类型,0为普通存储,1为低频存储
def change_type(self, bucket, key, storage_type): resource = entry(bucket, key) return self.__rs_do('chtype', resource, 'type/{0}'.format(storage_type))
325,717
修改文件的状态 修改文件的存储类型为可用或禁用: Args: bucket: 待操作资源所在空间 key: 待操作资源文件名 storage_type: 待操作资源存储类型,0为启用,1为禁用
def change_status(self, bucket, key, status, cond): resource = entry(bucket, key) if cond and isinstance(cond, dict): condstr = "" for k, v in cond.items(): condstr += "{0}={1}&".format(k, v) condstr = urlsafe_base64_encode(condstr[:-1]) return self.__rs_do('chstatus', resource, 'status/{0}'.format(status), 'cond', condstr) return self.__rs_do('chstatus', resource, 'status/{0}'.format(status))
325,718
创建存储空间 https://developer.qiniu.com/kodo/api/1382/mkbucketv2 Args: bucket_name: 存储空间名 region: 存储区域
def mkbucketv2(self, bucket_name, region): bucket_name = urlsafe_base64_encode(bucket_name) return self.__rs_do('mkbucketv2', bucket_name, 'region', region)
325,721
获得账号下应用的密钥 列出指定应用的密钥,仅当访问者对指定应用有管理权限时有效: 用户对创建的应用有管理权限。 用户对使用的第三方应用没有管理权限,第三方应用的运维方有管理权限。 Args: - app_uri: 应用的完整标识 Returns: 返回一个tuple对象,其格式为(<result>, <ResponseInfo>) - result 成功返回秘钥列表,失败返回None - ResponseInfo 请求的Response信息
def get_app_keys(self, app_uri): url = '{0}/v3/apps/{1}/keys'.format(self.host, app_uri) return http._get_with_qiniu_mac(url, None, self.auth)
325,740
获得账号下可用的应用的密钥 列出指定应用的可用密钥 Args: - app_uri: 应用的完整标识 Returns: 返回一个tuple对象,其格式为(<result>, <ResponseInfo>) - result 成功返回可用秘钥列表,失败返回None - ResponseInfo 请求的Response信息
def get_valid_app_auth(self, app_uri): ret, retInfo = self.get_app_keys(app_uri) if ret is None: return None for k in ret: if (k.get('state') == 'enabled'): return QiniuMacAuth(k.get('ak'), k.get('sk')) return None
325,741
获得指定应用所在区域的产品信息 Args: - app_uri: 应用的完整标识 Returns: 返回产品信息列表,若失败则返回None
def get_app_region_products(self, app_uri): apps, retInfo = self.list_apps() if apps is None: return None for app in apps: if (app.get('uri') == app_uri): return self.get_region_products(app.get('region')) return
325,743
获得指定区域的产品信息 Args: - region: 区域,如:"nq" Returns: 返回该区域的产品信息,若失败则返回None
def get_region_products(self, region): regions, retInfo = self.list_regions() if regions is None: return None for r in regions: if r.get('name') == region: return r.get('products')
325,744
创建应用 在指定区域创建一个新应用,所属应用为当前请求方。 Args: - args: 请求参数(json),参考 http://kirk-docs.qiniu.com/apidocs/ Returns: - result 成功返回所创建的应用信息,若失败则返回None - ResponseInfo 请求的Response信息
def create_app(self, args): url = '{0}/v3/apps'.format(self.host) return http._post_with_qiniu_mac(url, args, self.auth)
325,747
删除应用 删除指定标识的应用,当前请求方对该应用应有删除权限。 Args: - app_uri: 应用的完整标识 Returns: - result 成功返回空dict{},若失败则返回None - ResponseInfo 请求的Response信息
def delete_app(self, app_uri): url = '{0}/v3/apps/{1}'.format(self.host, app_uri) return http._delete_with_qiniu_mac(url, None, self.auth)
325,748
带请求体的签名(本质上是管理凭证的签名) Args: url: 待签名请求的url body: 待签名请求的body content_type: 待签名请求的body的Content-Type Returns: 管理凭证
def token_of_request(self, url, body=None, content_type=None): parsed_url = urlparse(url) query = parsed_url.query path = parsed_url.path data = path if query != '': data = ''.join([data, '?', query]) data = ''.join([data, "\n"]) if body: mimes = [ 'application/x-www-form-urlencoded' ] if content_type in mimes: data += body return '{0}:{1}'.format(self.__access_key, self.__token(data))
325,752
生成私有资源下载链接 Args: url: 私有空间资源的原始URL expires: 下载凭证有效期,默认为3600s Returns: 私有资源的下载链接
def private_download_url(self, url, expires=3600): deadline = int(time.time()) + expires if '?' in url: url += '&' else: url += '?' url = '{0}e={1}'.format(url, str(deadline)) token = self.token(url) return '{0}&token={1}'.format(url, token)
325,753
生成上传凭证 Args: bucket: 上传的空间名 key: 上传的文件名,默认为空 expires: 上传凭证的过期时间,默认为3600s policy: 上传策略,默认为空 Returns: 上传凭证
def upload_token( self, bucket, key=None, expires=3600, policy=None, strict_policy=True): if bucket is None or bucket == '': raise ValueError('invalid bucket name') scope = bucket if key is not None: scope = '{0}:{1}'.format(bucket, key) args = dict( scope=scope, deadline=int(time.time()) + expires, ) if policy is not None: self.__copy_policy(policy, args, strict_policy) return self.__upload_token(args)
325,754
回调验证 Args: origin_authorization: 回调时请求Header中的Authorization字段 url: 回调请求的url body: 回调请求的body content_type: 回调请求body的Content-Type Returns: 返回true表示验证成功,返回false表示验证失败
def verify_callback( self, origin_authorization, url, body, content_type='application/x-www-form-urlencoded'): token = self.token_of_request(url, body, content_type) authorization = 'QBox {0}'.format(token) return origin_authorization == authorization
325,756
创建服务组 创建新一个指定名称的服务组,并创建其下的服务。 Args: - args: 服务组描述,参考 http://kirk-docs.qiniu.com/apidocs/ Returns: 返回一个tuple对象,其格式为(<result>, <ResponseInfo>) - result 成功返回空dict{},失败返回{"error": "<errMsg string>"} - ResponseInfo 请求的Response信息
def create_stack(self, args): url = '{0}/v3/stacks'.format(self.host) return self.__post(url, args)
325,763
删除服务组 删除服务组内所有服务并销毁服务组。 Args: - stack: 服务所属的服务组名称 Returns: 返回一个tuple对象,其格式为(<result>, <ResponseInfo>) - result 成功返回空dict{},失败返回{"error": "<errMsg string>"} - ResponseInfo 请求的Response信息
def delete_stack(self, stack): url = '{0}/v3/stacks/{1}'.format(self.host, stack) return self.__delete(url)
325,764
获取服务组 查看服务组的属性信息。 Args: - stack: 服务所属的服务组名称 Returns: 返回一个tuple对象,其格式为(<result>, <ResponseInfo>) - result 成功返回stack信息,失败返回{"error": "<errMsg string>"} - ResponseInfo 请求的Response信息
def get_stack(self, stack): url = '{0}/v3/stacks/{1}'.format(self.host, stack) return self.__get(url)
325,765
启动服务组 启动服务组中的所有停止状态的服务。 Args: - stack: 服务所属的服务组名称 Returns: 返回一个tuple对象,其格式为(<result>, <ResponseInfo>) - result 成功返回空dict{},失败返回{"error": "<errMsg string>"} - ResponseInfo 请求的Response信息
def start_stack(self, stack): url = '{0}/v3/stacks/{1}/start'.format(self.host, stack) return self.__post(url)
325,766
停止服务组 停止服务组中所有运行状态的服务。 Args: - stack: 服务所属的服务组名称 Returns: 返回一个tuple对象,其格式为(<result>, <ResponseInfo>) - result 成功返回空dict{},失败返回{"error": "<errMsg string>"} - ResponseInfo 请求的Response信息
def stop_stack(self, stack): url = '{0}/v3/stacks/{1}/stop'.format(self.host, stack) return self.__post(url)
325,767
获得服务列表 列出指定名称的服务组内所有的服务, 返回一组详细的服务信息。 Args: - stack: 服务所属的服务组名称 Returns: 返回一个tuple对象,其格式为(<result>, <ResponseInfo>) - result 成功返回服务信息列表[<ervice1>, <service2>, ...],失败返回{"error": "<errMsg string>"} - ResponseInfo 请求的Response信息
def list_services(self, stack): url = '{0}/v3/stacks/{1}/services'.format(self.host, stack) return self.__get(url)
325,768
创建服务 创建一个服务,平台会异步地按模板分配资源并部署所有容器。 Args: - stack: 服务所属的服务组名称 - args: 服务具体描述请求参数(json),参考 http://kirk-docs.qiniu.com/apidocs/ Returns: 返回一个tuple对象,其格式为(<result>, <ResponseInfo>) - result 成功返回空dict{},失败返回{"error": "<errMsg string>"} - ResponseInfo 请求的Response信息
def create_service(self, stack, args): url = '{0}/v3/stacks/{1}/services'.format(self.host, stack) return self.__post(url, args)
325,769
删除服务 删除指定名称服务,并自动销毁服务已部署的所有容器和存储卷。 Args: - stack: 服务所属的服务组名称 - service: 服务名 Returns: 返回一个tuple对象,其格式为(<result>, <ResponseInfo>) - result 成功返回空dict{},失败返回{"error": "<errMsg string>"} - ResponseInfo 请求的Response信息
def delete_service(self, stack, service): url = '{0}/v3/stacks/{1}/services/{2}'.format(self.host, stack, service) return self.__delete(url)
325,770
查看服务 查看指定名称服务的属性。 Args: - stack: 服务所属的服务组名称 - service: 服务名 Returns: 返回一个tuple对象,其格式为(<result>, <ResponseInfo>) - result 成功返回服务信息,失败返回{"error": "<errMsg string>"} - ResponseInfo 请求的Response信息
def get_service_inspect(self, stack, service): url = '{0}/v3/stacks/{1}/services/{2}/inspect'.format(self.host, stack, service) return self.__get(url)
325,771
启动服务 启动指定名称服务的所有容器。 Args: - stack: 服务所属的服务组名称 - service: 服务名 Returns: 返回一个tuple对象,其格式为(<result>, <ResponseInfo>) - result 成功返回空dict{},失败返回{"error": "<errMsg string>"} - ResponseInfo 请求的Response信息
def start_service(self, stack, service): url = '{0}/v3/stacks/{1}/services/{2}/start'.format(self.host, stack, service) return self.__post(url)
325,772
停止服务 停止指定名称服务的所有容器。 Args: - stack: 服务所属的服务组名称 - service: 服务名 Returns: 返回一个tuple对象,其格式为(<result>, <ResponseInfo>) - result 成功返回空dict{},失败返回{"error": "<errMsg string>"} - ResponseInfo 请求的Response信息
def stop_service(self, stack, service): url = '{0}/v3/stacks/{1}/services/{2}/stop'.format(self.host, stack, service) return self.__post(url)
325,773
扩容存储卷 为指定名称的服务增加存储卷资源,并挂载到部署的容器中。 Args: - stack: 服务所属的服务组名称 - service: 服务名 - volume: 存储卷名 - args: 请求参数(json),参考 http://kirk-docs.qiniu.com/apidocs/ Returns: 返回一个tuple对象,其格式为(<result>, <ResponseInfo>) - result 成功返回空dict{},失败返回{"error": "<errMsg string>"} - ResponseInfo 请求的Response信息
def extend_service_volume(self, stack, service, volume, args): url = '{0}/v3/stacks/{1}/services/{2}/volumes/{3}/extend'.format(self.host, stack, service, volume) return self.__post(url, args)
325,775
删除存储卷 从部署的容器中移除挂载,并销毁指定服务下指定名称的存储卷, 并重新启动该容器。 Args: - stack: 服务所属的服务组名称 - service: 服务名 - volume: 存储卷名 Returns: 返回一个tuple对象,其格式为(<result>, <ResponseInfo>) - result 成功返回空dict{},失败返回{"error": "<errMsg string>"} - ResponseInfo 请求的Response信息
def delete_service_volume(self, stack, service, volume): url = '{0}/v3/stacks/{1}/services/{2}/volumes/{3}'.format(self.host, stack, service, volume) return self.__delete(url)
325,776
列出容器列表 列出应用内所有部署的容器, 返回一组容器IP。 Args: - stack: 要列出容器的服务组名(可不填,表示默认列出所有) - service: 要列出容器服务的服务名(可不填,表示默认列出所有) Returns: 返回一个tuple对象,其格式为(<result>, <ResponseInfo>) - result 成功返回容器的ip数组,失败返回{"error": "<errMsg string>"} - ResponseInfo 请求的Response信息
def list_containers(self, stack=None, service=None): url = '{0}/v3/containers'.format(self.host) params = {} if stack is not None: params['stack'] = stack if service is not None: params['service'] = service return self.__get(url, params or None)
325,777
查看容器 查看指定IP的容器,返回容器属性。 Args: - ip: 容器ip Returns: 返回一个tuple对象,其格式为(<result>, <ResponseInfo>) - result 成功返回容器的信息,失败返回{"error": "<errMsg string>"} - ResponseInfo 请求的Response信息
def get_container_inspect(self, ip): url = '{0}/v3/containers/{1}/inspect'.format(self.host, ip) return self.__get(url)
325,778
启动容器 启动指定IP的容器。 Args: - ip: 容器ip Returns: 返回一个tuple对象,其格式为(<result>, <ResponseInfo>) - result 成功返回空dict{},失败返回{"error": "<errMsg string>"} - ResponseInfo 请求的Response信息
def start_container(self, ip): url = '{0}/v3/containers/{1}/start'.format(self.host, ip) return self.__post(url)
325,779
停止容器 停止指定IP的容器。 Args: - ip: 容器ip Returns: 返回一个tuple对象,其格式为(<result>, <ResponseInfo>) - result 成功返回空dict{},失败返回{"error": "<errMsg string>"} - ResponseInfo 请求的Response信息
def stop_container(self, ip): url = '{0}/v3/containers/{1}/stop'.format(self.host, ip) return self.__post(url)
325,780
重启容器 重启指定IP的容器。 Args: - ip: 容器ip Returns: 返回一个tuple对象,其格式为(<result>, <ResponseInfo>) - result 成功返回空dict{},失败返回{"error": "<errMsg string>"} - ResponseInfo 请求的Response信息
def restart_container(self, ip): url = '{0}/v3/containers/{1}/restart'.format(self.host, ip) return self.__post(url)
325,781
申请接入点 申请指定配置的接入点资源。 Args: - args: 请求参数(json),参考 http://kirk-docs.qiniu.com/apidocs/ Returns: 返回一个tuple对象,其格式为(<result>, <ResponseInfo>) - result 成功返回申请到的接入点信息,失败返回{"error": "<errMsg string>"} - ResponseInfo 请求的Response信息
def create_ap(self, args): url = '{0}/v3/aps'.format(self.host) return self.__post(url, args)
325,782
搜索接入点 查看指定接入点的所有配置信息,包括所有监听端口的配置。 Args: - mode: 搜索模式,可以是domain、ip、host - query: 搜索文本 Returns: 返回一个tuple对象,其格式为(<result>, <ResponseInfo>) - result 成功返回搜索结果,失败返回{"error": "<errMsg string>"} - ResponseInfo 请求的Response信息
def search_ap(self, mode, query): url = '{0}/v3/aps/search?{1}={2}'.format(self.host, mode, query) return self.__get(url)
325,783
查看接入点 给出接入点的域名或IP,查看配置信息,包括所有监听端口的配置。 Args: - apid: 接入点ID Returns: 返回一个tuple对象,其格式为(<result>, <ResponseInfo>) - result 成功返回接入点信息,失败返回{"error": "<errMsg string>"} - ResponseInfo 请求的Response信息
def get_ap(self, apid): url = '{0}/v3/aps/{1}'.format(self.host, apid) return self.__get(url)
325,784
更新接入点 更新指定接入点的配置,如带宽。 Args: - apid: 接入点ID - args: 请求参数(json),参考 http://kirk-docs.qiniu.com/apidocs/ Returns: 返回一个tuple对象,其格式为(<result>, <ResponseInfo>) - result 成功返回空dict{},失败返回{"error": "<errMsg string>"} - ResponseInfo 请求的Response信息
def update_ap(self, apid, args): url = '{0}/v3/aps/{1}'.format(self.host, apid) return self.__post(url, args)
325,785
更新接入点端口配置 更新接入点指定端口的配置。 Args: - apid: 接入点ID - port: 要设置的端口号 - args: 请求参数(json),参考 http://kirk-docs.qiniu.com/apidocs/ Returns: 返回一个tuple对象,其格式为(<result>, <ResponseInfo>) - result 成功返回空dict{},失败返回{"error": "<errMsg string>"} - ResponseInfo 请求的Response信息
def set_ap_port(self, apid, port, args): url = '{0}/v3/aps/{1}/{2}'.format(self.host, apid, port) return self.__post(url, args)
325,786
释放接入点 销毁指定接入点资源。 Args: - apid: 接入点ID Returns: 返回一个tuple对象,其格式为(<result>, <ResponseInfo>) - result 成功返回空dict{},失败返回{"error": "<errMsg string>"} - ResponseInfo 请求的Response信息
def delete_ap(self, apid): url = '{0}/v3/aps/{1}'.format(self.host, apid) return self.__delete(url)
325,787
绑定自定义域名 绑定用户自定义的域名,仅对公网域名模式接入点生效。 Args: - apid: 接入点ID - args: 请求参数(json),参考 http://kirk-docs.qiniu.com/apidocs/ Returns: 返回一个tuple对象,其格式为(<result>, <ResponseInfo>) - result 成功返回空dict{},失败返回{"error": "<errMsg string>"} - ResponseInfo 请求的Response信息
def publish_ap(self, apid, args): url = '{0}/v3/aps/{1}/publish'.format(self.host, apid) return self.__post(url, args)
325,788
解绑自定义域名 解绑用户自定义的域名,仅对公网域名模式接入点生效。 Args: - apid: 接入点ID - args: 请求参数(json),参考 http://kirk-docs.qiniu.com/apidocs/ Returns: 返回一个tuple对象,其格式为(<result>, <ResponseInfo>) - result 成功返回空dict{},失败返回{"error": "<errMsg string>"} - ResponseInfo 请求的Response信息
def unpublish_ap(self, apid, args): url = '{0}/v3/aps/{1}/unpublish'.format(self.host, apid) return self.__post(url, args)
325,789
查看健康检查结果 检查接入点的指定端口的后端健康状况。 Args: - apid: 接入点ID - port: 要设置的端口号 Returns: 返回一个tuple对象,其格式为(<result>, <ResponseInfo>) - result 成功返回健康状况,失败返回{"error": "<errMsg string>"} - ResponseInfo 请求的Response信息
def get_ap_port_healthcheck(self, apid, port): url = '{0}/v3/aps/{1}/{2}/healthcheck'.format(self.host, apid, port) return self.__get(url)
325,790
临时关闭接入点端口 临时关闭接入点端口,仅对公网域名,公网ip有效。 Args: - apid: 接入点ID - port: 要设置的端口号 Returns: 返回一个tuple对象,其格式为(<result>, <ResponseInfo>) - result 成功返回空dict{},失败返回{"error": "<errMsg string>"} - ResponseInfo 请求的Response信息
def disable_ap_port(self, apid, port): url = '{0}/v3/aps/{1}/{2}/disable'.format(self.host, apid, port) return self.__post(url)
325,791
开启接入点端口 开启临时关闭的接入点端口,仅对公网域名,公网ip有效。 Args: - apid: 接入点ID - port: 要设置的端口号 Returns: 返回一个tuple对象,其格式为(<result>, <ResponseInfo>) - result 成功返回空dict{},失败返回{"error": "<errMsg string>"} - ResponseInfo 请求的Response信息
def enable_ap_port(self, apid, port): url = '{0}/v3/aps/{1}/{2}/enable'.format(self.host, apid, port) return self.__post(url)
325,792
获取一次性代理地址 对内网地址获取一个一次性的外部可访问的代理地址 Args: - backend: 后端地址,如:"10.128.0.1:8080" Returns: 返回一个tuple对象,其格式为(<result>, <ResponseInfo>) - result 成功返回代理地址信息,失败返回{"error": "<errMsg string>"} - ResponseInfo 请求的Response信息
def get_web_proxy(self, backend): url = '{0}/v3/webproxy'.format(self.host) return self.__post(url, {'backend': backend})
325,793
上传二进制流到七牛 Args: up_token: 上传凭证 key: 上传文件名 data: 上传二进制流 params: 自定义变量,规格参考 http://developer.qiniu.com/docs/v6/api/overview/up/response/vars.html#xvar mime_type: 上传数据的mimeType check_crc: 是否校验crc32 progress_handler: 上传进度 Returns: 一个dict变量,类似 {"hash": "<Hash string>", "key": "<Key string>"} 一个ResponseInfo对象
def put_data( up_token, key, data, params=None, mime_type='application/octet-stream', check_crc=False, progress_handler=None, fname=None): final_data = '' if hasattr(data, 'read'): while True: tmp_data = data.read(config._BLOCK_SIZE) if len(tmp_data) == 0: break else: final_data += tmp_data else: final_data = data crc = crc32(final_data) return _form_put(up_token, key, final_data, params, mime_type, crc, progress_handler, fname)
325,794
上传文件到七牛 Args: up_token: 上传凭证 key: 上传文件名 file_path: 上传文件的路径 params: 自定义变量,规格参考 http://developer.qiniu.com/docs/v6/api/overview/up/response/vars.html#xvar mime_type: 上传数据的mimeType check_crc: 是否校验crc32 progress_handler: 上传进度 upload_progress_recorder: 记录上传进度,用于断点续传 Returns: 一个dict变量,类似 {"hash": "<Hash string>", "key": "<Key string>"} 一个ResponseInfo对象
def put_file(up_token, key, file_path, params=None, mime_type='application/octet-stream', check_crc=False, progress_handler=None, upload_progress_recorder=None, keep_last_modified=False): ret = {} size = os.stat(file_path).st_size # fname = os.path.basename(file_path) with open(file_path, 'rb') as input_stream: file_name = os.path.basename(file_path) modify_time = int(os.path.getmtime(file_path)) if size > config._BLOCK_SIZE * 2: ret, info = put_stream(up_token, key, input_stream, file_name, size, params, mime_type, progress_handler, upload_progress_recorder=upload_progress_recorder, modify_time=modify_time, keep_last_modified=keep_last_modified) else: crc = file_crc32(file_path) ret, info = _form_put(up_token, key, input_stream, params, mime_type, crc, progress_handler, file_name, modify_time=modify_time, keep_last_modified=keep_last_modified) return ret, info
325,795
计算文件的crc32检验码: Args: filePath: 待计算校验码的文件路径 Returns: 文件内容的crc32校验码。
def file_crc32(filePath): crc = 0 with open(filePath, 'rb') as f: for block in _file_iter(f, _BLOCK_SIZE): crc = binascii.crc32(block, crc) & 0xFFFFFFFF return crc
325,806
读取输入流: Args: input_stream: 待读取文件的二进制流 size: 二进制流的大小 Raises: IOError: 文件流读取失败
def _file_iter(input_stream, size, offset=0): input_stream.seek(offset) d = input_stream.read(size) while d: yield d d = input_stream.read(size)
325,807