Search is not available for this dataset
identifier
stringlengths
1
155
parameters
stringlengths
2
6.09k
docstring
stringlengths
11
63.4k
docstring_summary
stringlengths
0
63.4k
function
stringlengths
29
99.8k
function_tokens
sequence
start_point
sequence
end_point
sequence
language
stringclasses
1 value
docstring_language
stringlengths
2
7
docstring_language_predictions
stringlengths
18
23
is_langid_reliable
stringclasses
2 values
Storage.get
(self)
Retrieve credential. The Storage lock must *not* be held when this is called. Returns: oauth2client.client.Credentials
Retrieve credential.
def get(self): """Retrieve credential. The Storage lock must *not* be held when this is called. Returns: oauth2client.client.Credentials """ self.acquire_lock() try: return self.locked_get() finally: self.release_lock()
[ "def", "get", "(", "self", ")", ":", "self", ".", "acquire_lock", "(", ")", "try", ":", "return", "self", ".", "locked_get", "(", ")", "finally", ":", "self", ".", "release_lock", "(", ")" ]
[ 396, 4 ]
[ 408, 31 ]
python
en
['en', 'pt', 'en']
False
Storage.put
(self, credentials)
Write a credential. The Storage lock must be held when this is called. Args: credentials: Credentials, the credentials to store.
Write a credential.
def put(self, credentials): """Write a credential. The Storage lock must be held when this is called. Args: credentials: Credentials, the credentials to store. """ self.acquire_lock() try: self.locked_put(credentials) finally: self.release_lock()
[ "def", "put", "(", "self", ",", "credentials", ")", ":", "self", ".", "acquire_lock", "(", ")", "try", ":", "self", ".", "locked_put", "(", "credentials", ")", "finally", ":", "self", ".", "release_lock", "(", ")" ]
[ 410, 4 ]
[ 422, 31 ]
python
en
['es', 'pt', 'en']
False
Storage.delete
(self)
Delete credential. Frees any resources associated with storing the credential. The Storage lock must *not* be held when this is called. Returns: None
Delete credential.
def delete(self): """Delete credential. Frees any resources associated with storing the credential. The Storage lock must *not* be held when this is called. Returns: None """ self.acquire_lock() try: return self.locked_delete() finally: self.release_lock()
[ "def", "delete", "(", "self", ")", ":", "self", ".", "acquire_lock", "(", ")", "try", ":", "return", "self", ".", "locked_delete", "(", ")", "finally", ":", "self", ".", "release_lock", "(", ")" ]
[ 424, 4 ]
[ 437, 31 ]
python
en
['en', 'la', 'en']
False
OAuth2Credentials.__init__
(self, access_token, client_id, client_secret, refresh_token, token_expiry, token_uri, user_agent, revoke_uri=None, id_token=None, token_response=None, scopes=None, token_info_uri=None, id_token_jwt=None)
Create an instance of OAuth2Credentials. This constructor is not usually called by the user, instead OAuth2Credentials objects are instantiated by the OAuth2WebServerFlow. Args: access_token: string, access token. client_id: string, client identifier. client_secret: string, client secret. refresh_token: string, refresh token. token_expiry: datetime, when the access_token expires. token_uri: string, URI of token endpoint. user_agent: string, The HTTP User-Agent to provide for this application. revoke_uri: string, URI for revoke endpoint. Defaults to None; a token can't be revoked if this is None. id_token: object, The identity of the resource owner. token_response: dict, the decoded response to the token request. None if a token hasn't been requested yet. Stored because some providers (e.g. wordpress.com) include extra fields that clients may want. scopes: list, authorized scopes for these credentials. token_info_uri: string, the URI for the token info endpoint. Defaults to None; scopes can not be refreshed if this is None. id_token_jwt: string, the encoded and signed identity JWT. The decoded version of this is stored in id_token. Notes: store: callable, A callable that when passed a Credential will store the credential back to where it came from. This is needed to store the latest access_token if it has expired and been refreshed.
Create an instance of OAuth2Credentials.
def __init__(self, access_token, client_id, client_secret, refresh_token, token_expiry, token_uri, user_agent, revoke_uri=None, id_token=None, token_response=None, scopes=None, token_info_uri=None, id_token_jwt=None): """Create an instance of OAuth2Credentials. This constructor is not usually called by the user, instead OAuth2Credentials objects are instantiated by the OAuth2WebServerFlow. Args: access_token: string, access token. client_id: string, client identifier. client_secret: string, client secret. refresh_token: string, refresh token. token_expiry: datetime, when the access_token expires. token_uri: string, URI of token endpoint. user_agent: string, The HTTP User-Agent to provide for this application. revoke_uri: string, URI for revoke endpoint. Defaults to None; a token can't be revoked if this is None. id_token: object, The identity of the resource owner. token_response: dict, the decoded response to the token request. None if a token hasn't been requested yet. Stored because some providers (e.g. wordpress.com) include extra fields that clients may want. scopes: list, authorized scopes for these credentials. token_info_uri: string, the URI for the token info endpoint. Defaults to None; scopes can not be refreshed if this is None. id_token_jwt: string, the encoded and signed identity JWT. The decoded version of this is stored in id_token. Notes: store: callable, A callable that when passed a Credential will store the credential back to where it came from. This is needed to store the latest access_token if it has expired and been refreshed. """ self.access_token = access_token self.client_id = client_id self.client_secret = client_secret self.refresh_token = refresh_token self.store = None self.token_expiry = token_expiry self.token_uri = token_uri self.user_agent = user_agent self.revoke_uri = revoke_uri self.id_token = id_token self.id_token_jwt = id_token_jwt self.token_response = token_response self.scopes = set(_helpers.string_to_scopes(scopes or [])) self.token_info_uri = token_info_uri # True if the credentials have been revoked or expired and can't be # refreshed. self.invalid = False
[ "def", "__init__", "(", "self", ",", "access_token", ",", "client_id", ",", "client_secret", ",", "refresh_token", ",", "token_expiry", ",", "token_uri", ",", "user_agent", ",", "revoke_uri", "=", "None", ",", "id_token", "=", "None", ",", "token_response", "=", "None", ",", "scopes", "=", "None", ",", "token_info_uri", "=", "None", ",", "id_token_jwt", "=", "None", ")", ":", "self", ".", "access_token", "=", "access_token", "self", ".", "client_id", "=", "client_id", "self", ".", "client_secret", "=", "client_secret", "self", ".", "refresh_token", "=", "refresh_token", "self", ".", "store", "=", "None", "self", ".", "token_expiry", "=", "token_expiry", "self", ".", "token_uri", "=", "token_uri", "self", ".", "user_agent", "=", "user_agent", "self", ".", "revoke_uri", "=", "revoke_uri", "self", ".", "id_token", "=", "id_token", "self", ".", "id_token_jwt", "=", "id_token_jwt", "self", ".", "token_response", "=", "token_response", "self", ".", "scopes", "=", "set", "(", "_helpers", ".", "string_to_scopes", "(", "scopes", "or", "[", "]", ")", ")", "self", ".", "token_info_uri", "=", "token_info_uri", "# True if the credentials have been revoked or expired and can't be", "# refreshed.", "self", ".", "invalid", "=", "False" ]
[ 450, 4 ]
[ 505, 28 ]
python
en
['en', 'en', 'en']
True
OAuth2Credentials.authorize
(self, http)
Authorize an httplib2.Http instance with these credentials. The modified http.request method will add authentication headers to each request and will refresh access_tokens when a 401 is received on a request. In addition the http.request method has a credentials property, http.request.credentials, which is the Credentials object that authorized it. Args: http: An instance of ``httplib2.Http`` or something that acts like it. Returns: A modified instance of http that was passed in. Example:: h = httplib2.Http() h = credentials.authorize(h) You can't create a new OAuth subclass of httplib2.Authentication because it never gets passed the absolute URI, which is needed for signing. So instead we have to overload 'request' with a closure that adds in the Authorization header and then calls the original version of 'request()'.
Authorize an httplib2.Http instance with these credentials.
def authorize(self, http): """Authorize an httplib2.Http instance with these credentials. The modified http.request method will add authentication headers to each request and will refresh access_tokens when a 401 is received on a request. In addition the http.request method has a credentials property, http.request.credentials, which is the Credentials object that authorized it. Args: http: An instance of ``httplib2.Http`` or something that acts like it. Returns: A modified instance of http that was passed in. Example:: h = httplib2.Http() h = credentials.authorize(h) You can't create a new OAuth subclass of httplib2.Authentication because it never gets passed the absolute URI, which is needed for signing. So instead we have to overload 'request' with a closure that adds in the Authorization header and then calls the original version of 'request()'. """ transport.wrap_http_for_auth(self, http) return http
[ "def", "authorize", "(", "self", ",", "http", ")", ":", "transport", ".", "wrap_http_for_auth", "(", "self", ",", "http", ")", "return", "http" ]
[ 507, 4 ]
[ 535, 19 ]
python
en
['en', 'en', 'en']
True
OAuth2Credentials.refresh
(self, http)
Forces a refresh of the access_token. Args: http: httplib2.Http, an http object to be used to make the refresh request.
Forces a refresh of the access_token.
def refresh(self, http): """Forces a refresh of the access_token. Args: http: httplib2.Http, an http object to be used to make the refresh request. """ self._refresh(http)
[ "def", "refresh", "(", "self", ",", "http", ")", ":", "self", ".", "_refresh", "(", "http", ")" ]
[ 537, 4 ]
[ 544, 27 ]
python
en
['en', 'en', 'en']
True
OAuth2Credentials.revoke
(self, http)
Revokes a refresh_token and makes the credentials void. Args: http: httplib2.Http, an http object to be used to make the revoke request.
Revokes a refresh_token and makes the credentials void.
def revoke(self, http): """Revokes a refresh_token and makes the credentials void. Args: http: httplib2.Http, an http object to be used to make the revoke request. """ self._revoke(http)
[ "def", "revoke", "(", "self", ",", "http", ")", ":", "self", ".", "_revoke", "(", "http", ")" ]
[ 546, 4 ]
[ 553, 26 ]
python
en
['en', 'en', 'en']
True
OAuth2Credentials.apply
(self, headers)
Add the authorization to the headers. Args: headers: dict, the headers to add the Authorization header to.
Add the authorization to the headers.
def apply(self, headers): """Add the authorization to the headers. Args: headers: dict, the headers to add the Authorization header to. """ headers['Authorization'] = 'Bearer ' + self.access_token
[ "def", "apply", "(", "self", ",", "headers", ")", ":", "headers", "[", "'Authorization'", "]", "=", "'Bearer '", "+", "self", ".", "access_token" ]
[ 555, 4 ]
[ 561, 64 ]
python
en
['en', 'en', 'en']
True
OAuth2Credentials.has_scopes
(self, scopes)
Verify that the credentials are authorized for the given scopes. Returns True if the credentials authorized scopes contain all of the scopes given. Args: scopes: list or string, the scopes to check. Notes: There are cases where the credentials are unaware of which scopes are authorized. Notably, credentials obtained and stored before this code was added will not have scopes, AccessTokenCredentials do not have scopes. In both cases, you can use refresh_scopes() to obtain the canonical set of scopes.
Verify that the credentials are authorized for the given scopes.
def has_scopes(self, scopes): """Verify that the credentials are authorized for the given scopes. Returns True if the credentials authorized scopes contain all of the scopes given. Args: scopes: list or string, the scopes to check. Notes: There are cases where the credentials are unaware of which scopes are authorized. Notably, credentials obtained and stored before this code was added will not have scopes, AccessTokenCredentials do not have scopes. In both cases, you can use refresh_scopes() to obtain the canonical set of scopes. """ scopes = _helpers.string_to_scopes(scopes) return set(scopes).issubset(self.scopes)
[ "def", "has_scopes", "(", "self", ",", "scopes", ")", ":", "scopes", "=", "_helpers", ".", "string_to_scopes", "(", "scopes", ")", "return", "set", "(", "scopes", ")", ".", "issubset", "(", "self", ".", "scopes", ")" ]
[ 563, 4 ]
[ 580, 48 ]
python
en
['en', 'en', 'en']
True
OAuth2Credentials.retrieve_scopes
(self, http)
Retrieves the canonical list of scopes for this access token. Gets the scopes from the OAuth2 provider. Args: http: httplib2.Http, an http object to be used to make the refresh request. Returns: A set of strings containing the canonical list of scopes.
Retrieves the canonical list of scopes for this access token.
def retrieve_scopes(self, http): """Retrieves the canonical list of scopes for this access token. Gets the scopes from the OAuth2 provider. Args: http: httplib2.Http, an http object to be used to make the refresh request. Returns: A set of strings containing the canonical list of scopes. """ self._retrieve_scopes(http) return self.scopes
[ "def", "retrieve_scopes", "(", "self", ",", "http", ")", ":", "self", ".", "_retrieve_scopes", "(", "http", ")", "return", "self", ".", "scopes" ]
[ 582, 4 ]
[ 595, 26 ]
python
en
['en', 'en', 'en']
True
OAuth2Credentials.from_json
(cls, json_data)
Instantiate a Credentials object from a JSON description of it. The JSON should have been produced by calling .to_json() on the object. Args: json_data: string or bytes, JSON to deserialize. Returns: An instance of a Credentials subclass.
Instantiate a Credentials object from a JSON description of it.
def from_json(cls, json_data): """Instantiate a Credentials object from a JSON description of it. The JSON should have been produced by calling .to_json() on the object. Args: json_data: string or bytes, JSON to deserialize. Returns: An instance of a Credentials subclass. """ data = json.loads(_helpers._from_bytes(json_data)) if (data.get('token_expiry') and not isinstance(data['token_expiry'], datetime.datetime)): try: data['token_expiry'] = datetime.datetime.strptime( data['token_expiry'], EXPIRY_FORMAT) except ValueError: data['token_expiry'] = None retval = cls( data['access_token'], data['client_id'], data['client_secret'], data['refresh_token'], data['token_expiry'], data['token_uri'], data['user_agent'], revoke_uri=data.get('revoke_uri', None), id_token=data.get('id_token', None), id_token_jwt=data.get('id_token_jwt', None), token_response=data.get('token_response', None), scopes=data.get('scopes', None), token_info_uri=data.get('token_info_uri', None)) retval.invalid = data['invalid'] return retval
[ "def", "from_json", "(", "cls", ",", "json_data", ")", ":", "data", "=", "json", ".", "loads", "(", "_helpers", ".", "_from_bytes", "(", "json_data", ")", ")", "if", "(", "data", ".", "get", "(", "'token_expiry'", ")", "and", "not", "isinstance", "(", "data", "[", "'token_expiry'", "]", ",", "datetime", ".", "datetime", ")", ")", ":", "try", ":", "data", "[", "'token_expiry'", "]", "=", "datetime", ".", "datetime", ".", "strptime", "(", "data", "[", "'token_expiry'", "]", ",", "EXPIRY_FORMAT", ")", "except", "ValueError", ":", "data", "[", "'token_expiry'", "]", "=", "None", "retval", "=", "cls", "(", "data", "[", "'access_token'", "]", ",", "data", "[", "'client_id'", "]", ",", "data", "[", "'client_secret'", "]", ",", "data", "[", "'refresh_token'", "]", ",", "data", "[", "'token_expiry'", "]", ",", "data", "[", "'token_uri'", "]", ",", "data", "[", "'user_agent'", "]", ",", "revoke_uri", "=", "data", ".", "get", "(", "'revoke_uri'", ",", "None", ")", ",", "id_token", "=", "data", ".", "get", "(", "'id_token'", ",", "None", ")", ",", "id_token_jwt", "=", "data", ".", "get", "(", "'id_token_jwt'", ",", "None", ")", ",", "token_response", "=", "data", ".", "get", "(", "'token_response'", ",", "None", ")", ",", "scopes", "=", "data", ".", "get", "(", "'scopes'", ",", "None", ")", ",", "token_info_uri", "=", "data", ".", "get", "(", "'token_info_uri'", ",", "None", ")", ")", "retval", ".", "invalid", "=", "data", "[", "'invalid'", "]", "return", "retval" ]
[ 598, 4 ]
[ 632, 21 ]
python
en
['en', 'en', 'en']
True
OAuth2Credentials.access_token_expired
(self)
True if the credential is expired or invalid. If the token_expiry isn't set, we assume the token doesn't expire.
True if the credential is expired or invalid.
def access_token_expired(self): """True if the credential is expired or invalid. If the token_expiry isn't set, we assume the token doesn't expire. """ if self.invalid: return True if not self.token_expiry: return False now = _UTCNOW() if now >= self.token_expiry: logger.info('access_token is expired. Now: %s, token_expiry: %s', now, self.token_expiry) return True return False
[ "def", "access_token_expired", "(", "self", ")", ":", "if", "self", ".", "invalid", ":", "return", "True", "if", "not", "self", ".", "token_expiry", ":", "return", "False", "now", "=", "_UTCNOW", "(", ")", "if", "now", ">=", "self", ".", "token_expiry", ":", "logger", ".", "info", "(", "'access_token is expired. Now: %s, token_expiry: %s'", ",", "now", ",", "self", ".", "token_expiry", ")", "return", "True", "return", "False" ]
[ 635, 4 ]
[ 651, 20 ]
python
en
['en', 'en', 'en']
True
OAuth2Credentials.get_access_token
(self, http=None)
Return the access token and its expiration information. If the token does not exist, get one. If the token expired, refresh it.
Return the access token and its expiration information.
def get_access_token(self, http=None): """Return the access token and its expiration information. If the token does not exist, get one. If the token expired, refresh it. """ if not self.access_token or self.access_token_expired: if not http: http = transport.get_http_object() self.refresh(http) return AccessTokenInfo(access_token=self.access_token, expires_in=self._expires_in())
[ "def", "get_access_token", "(", "self", ",", "http", "=", "None", ")", ":", "if", "not", "self", ".", "access_token", "or", "self", ".", "access_token_expired", ":", "if", "not", "http", ":", "http", "=", "transport", ".", "get_http_object", "(", ")", "self", ".", "refresh", "(", "http", ")", "return", "AccessTokenInfo", "(", "access_token", "=", "self", ".", "access_token", ",", "expires_in", "=", "self", ".", "_expires_in", "(", ")", ")" ]
[ 653, 4 ]
[ 664, 61 ]
python
en
['en', 'en', 'en']
True
OAuth2Credentials.set_store
(self, store)
Set the Storage for the credential. Args: store: Storage, an implementation of Storage object. This is needed to store the latest access_token if it has expired and been refreshed. This implementation uses locking to check for updates before updating the access_token.
Set the Storage for the credential.
def set_store(self, store): """Set the Storage for the credential. Args: store: Storage, an implementation of Storage object. This is needed to store the latest access_token if it has expired and been refreshed. This implementation uses locking to check for updates before updating the access_token. """ self.store = store
[ "def", "set_store", "(", "self", ",", "store", ")", ":", "self", ".", "store", "=", "store" ]
[ 666, 4 ]
[ 676, 26 ]
python
en
['en', 'en', 'en']
True
OAuth2Credentials._expires_in
(self)
Return the number of seconds until this token expires. If token_expiry is in the past, this method will return 0, meaning the token has already expired. If token_expiry is None, this method will return None. Note that returning 0 in such a case would not be fair: the token may still be valid; we just don't know anything about it.
Return the number of seconds until this token expires.
def _expires_in(self): """Return the number of seconds until this token expires. If token_expiry is in the past, this method will return 0, meaning the token has already expired. If token_expiry is None, this method will return None. Note that returning 0 in such a case would not be fair: the token may still be valid; we just don't know anything about it. """ if self.token_expiry: now = _UTCNOW() if self.token_expiry > now: time_delta = self.token_expiry - now # TODO(orestica): return time_delta.total_seconds() # once dropping support for Python 2.6 return time_delta.days * 86400 + time_delta.seconds else: return 0
[ "def", "_expires_in", "(", "self", ")", ":", "if", "self", ".", "token_expiry", ":", "now", "=", "_UTCNOW", "(", ")", "if", "self", ".", "token_expiry", ">", "now", ":", "time_delta", "=", "self", ".", "token_expiry", "-", "now", "# TODO(orestica): return time_delta.total_seconds()", "# once dropping support for Python 2.6", "return", "time_delta", ".", "days", "*", "86400", "+", "time_delta", ".", "seconds", "else", ":", "return", "0" ]
[ 678, 4 ]
[ 696, 24 ]
python
en
['en', 'en', 'en']
True
OAuth2Credentials._updateFromCredential
(self, other)
Update this Credential from another instance.
Update this Credential from another instance.
def _updateFromCredential(self, other): """Update this Credential from another instance.""" self.__dict__.update(other.__getstate__())
[ "def", "_updateFromCredential", "(", "self", ",", "other", ")", ":", "self", ".", "__dict__", ".", "update", "(", "other", ".", "__getstate__", "(", ")", ")" ]
[ 698, 4 ]
[ 700, 50 ]
python
en
['en', 'en', 'en']
True
OAuth2Credentials.__getstate__
(self)
Trim the state down to something that can be pickled.
Trim the state down to something that can be pickled.
def __getstate__(self): """Trim the state down to something that can be pickled.""" d = copy.copy(self.__dict__) del d['store'] return d
[ "def", "__getstate__", "(", "self", ")", ":", "d", "=", "copy", ".", "copy", "(", "self", ".", "__dict__", ")", "del", "d", "[", "'store'", "]", "return", "d" ]
[ 702, 4 ]
[ 706, 16 ]
python
en
['en', 'en', 'en']
True
OAuth2Credentials.__setstate__
(self, state)
Reconstitute the state of the object from being pickled.
Reconstitute the state of the object from being pickled.
def __setstate__(self, state): """Reconstitute the state of the object from being pickled.""" self.__dict__.update(state) self.store = None
[ "def", "__setstate__", "(", "self", ",", "state", ")", ":", "self", ".", "__dict__", ".", "update", "(", "state", ")", "self", ".", "store", "=", "None" ]
[ 708, 4 ]
[ 711, 25 ]
python
en
['en', 'en', 'en']
True
OAuth2Credentials._generate_refresh_request_body
(self)
Generate the body that will be used in the refresh request.
Generate the body that will be used in the refresh request.
def _generate_refresh_request_body(self): """Generate the body that will be used in the refresh request.""" body = urllib.parse.urlencode({ 'grant_type': 'refresh_token', 'client_id': self.client_id, 'client_secret': self.client_secret, 'refresh_token': self.refresh_token, }) return body
[ "def", "_generate_refresh_request_body", "(", "self", ")", ":", "body", "=", "urllib", ".", "parse", ".", "urlencode", "(", "{", "'grant_type'", ":", "'refresh_token'", ",", "'client_id'", ":", "self", ".", "client_id", ",", "'client_secret'", ":", "self", ".", "client_secret", ",", "'refresh_token'", ":", "self", ".", "refresh_token", ",", "}", ")", "return", "body" ]
[ 713, 4 ]
[ 721, 19 ]
python
en
['en', 'en', 'en']
True
OAuth2Credentials._generate_refresh_request_headers
(self)
Generate the headers that will be used in the refresh request.
Generate the headers that will be used in the refresh request.
def _generate_refresh_request_headers(self): """Generate the headers that will be used in the refresh request.""" headers = { 'content-type': 'application/x-www-form-urlencoded', } if self.user_agent is not None: headers['user-agent'] = self.user_agent return headers
[ "def", "_generate_refresh_request_headers", "(", "self", ")", ":", "headers", "=", "{", "'content-type'", ":", "'application/x-www-form-urlencoded'", ",", "}", "if", "self", ".", "user_agent", "is", "not", "None", ":", "headers", "[", "'user-agent'", "]", "=", "self", ".", "user_agent", "return", "headers" ]
[ 723, 4 ]
[ 732, 22 ]
python
en
['en', 'en', 'en']
True
OAuth2Credentials._refresh
(self, http)
Refreshes the access_token. This method first checks by reading the Storage object if available. If a refresh is still needed, it holds the Storage lock until the refresh is completed. Args: http: an object to be used to make HTTP requests. Raises: HttpAccessTokenRefreshError: When the refresh fails.
Refreshes the access_token.
def _refresh(self, http): """Refreshes the access_token. This method first checks by reading the Storage object if available. If a refresh is still needed, it holds the Storage lock until the refresh is completed. Args: http: an object to be used to make HTTP requests. Raises: HttpAccessTokenRefreshError: When the refresh fails. """ if not self.store: self._do_refresh_request(http) else: self.store.acquire_lock() try: new_cred = self.store.locked_get() if (new_cred and not new_cred.invalid and new_cred.access_token != self.access_token and not new_cred.access_token_expired): logger.info('Updated access_token read from Storage') self._updateFromCredential(new_cred) else: self._do_refresh_request(http) finally: self.store.release_lock()
[ "def", "_refresh", "(", "self", ",", "http", ")", ":", "if", "not", "self", ".", "store", ":", "self", ".", "_do_refresh_request", "(", "http", ")", "else", ":", "self", ".", "store", ".", "acquire_lock", "(", ")", "try", ":", "new_cred", "=", "self", ".", "store", ".", "locked_get", "(", ")", "if", "(", "new_cred", "and", "not", "new_cred", ".", "invalid", "and", "new_cred", ".", "access_token", "!=", "self", ".", "access_token", "and", "not", "new_cred", ".", "access_token_expired", ")", ":", "logger", ".", "info", "(", "'Updated access_token read from Storage'", ")", "self", ".", "_updateFromCredential", "(", "new_cred", ")", "else", ":", "self", ".", "_do_refresh_request", "(", "http", ")", "finally", ":", "self", ".", "store", ".", "release_lock", "(", ")" ]
[ 734, 4 ]
[ 762, 41 ]
python
en
['en', 'en', 'en']
True
OAuth2Credentials._do_refresh_request
(self, http)
Refresh the access_token using the refresh_token. Args: http: an object to be used to make HTTP requests. Raises: HttpAccessTokenRefreshError: When the refresh fails.
Refresh the access_token using the refresh_token.
def _do_refresh_request(self, http): """Refresh the access_token using the refresh_token. Args: http: an object to be used to make HTTP requests. Raises: HttpAccessTokenRefreshError: When the refresh fails. """ body = self._generate_refresh_request_body() headers = self._generate_refresh_request_headers() logger.info('Refreshing access_token') resp, content = transport.request( http, self.token_uri, method='POST', body=body, headers=headers) content = _helpers._from_bytes(content) if resp.status == http_client.OK: d = json.loads(content) self.token_response = d self.access_token = d['access_token'] self.refresh_token = d.get('refresh_token', self.refresh_token) if 'expires_in' in d: delta = datetime.timedelta(seconds=int(d['expires_in'])) self.token_expiry = delta + _UTCNOW() else: self.token_expiry = None if 'id_token' in d: self.id_token = _extract_id_token(d['id_token']) self.id_token_jwt = d['id_token'] else: self.id_token = None self.id_token_jwt = None # On temporary refresh errors, the user does not actually have to # re-authorize, so we unflag here. self.invalid = False if self.store: self.store.locked_put(self) else: # An {'error':...} response body means the token is expired or # revoked, so we flag the credentials as such. logger.info('Failed to retrieve access token: %s', content) error_msg = 'Invalid response {0}.'.format(resp.status) try: d = json.loads(content) if 'error' in d: error_msg = d['error'] if 'error_description' in d: error_msg += ': ' + d['error_description'] self.invalid = True if self.store is not None: self.store.locked_put(self) except (TypeError, ValueError): pass raise HttpAccessTokenRefreshError(error_msg, status=resp.status)
[ "def", "_do_refresh_request", "(", "self", ",", "http", ")", ":", "body", "=", "self", ".", "_generate_refresh_request_body", "(", ")", "headers", "=", "self", ".", "_generate_refresh_request_headers", "(", ")", "logger", ".", "info", "(", "'Refreshing access_token'", ")", "resp", ",", "content", "=", "transport", ".", "request", "(", "http", ",", "self", ".", "token_uri", ",", "method", "=", "'POST'", ",", "body", "=", "body", ",", "headers", "=", "headers", ")", "content", "=", "_helpers", ".", "_from_bytes", "(", "content", ")", "if", "resp", ".", "status", "==", "http_client", ".", "OK", ":", "d", "=", "json", ".", "loads", "(", "content", ")", "self", ".", "token_response", "=", "d", "self", ".", "access_token", "=", "d", "[", "'access_token'", "]", "self", ".", "refresh_token", "=", "d", ".", "get", "(", "'refresh_token'", ",", "self", ".", "refresh_token", ")", "if", "'expires_in'", "in", "d", ":", "delta", "=", "datetime", ".", "timedelta", "(", "seconds", "=", "int", "(", "d", "[", "'expires_in'", "]", ")", ")", "self", ".", "token_expiry", "=", "delta", "+", "_UTCNOW", "(", ")", "else", ":", "self", ".", "token_expiry", "=", "None", "if", "'id_token'", "in", "d", ":", "self", ".", "id_token", "=", "_extract_id_token", "(", "d", "[", "'id_token'", "]", ")", "self", ".", "id_token_jwt", "=", "d", "[", "'id_token'", "]", "else", ":", "self", ".", "id_token", "=", "None", "self", ".", "id_token_jwt", "=", "None", "# On temporary refresh errors, the user does not actually have to", "# re-authorize, so we unflag here.", "self", ".", "invalid", "=", "False", "if", "self", ".", "store", ":", "self", ".", "store", ".", "locked_put", "(", "self", ")", "else", ":", "# An {'error':...} response body means the token is expired or", "# revoked, so we flag the credentials as such.", "logger", ".", "info", "(", "'Failed to retrieve access token: %s'", ",", "content", ")", "error_msg", "=", "'Invalid response {0}.'", ".", "format", "(", "resp", ".", "status", ")", "try", ":", "d", "=", "json", ".", "loads", "(", "content", ")", "if", "'error'", "in", "d", ":", "error_msg", "=", "d", "[", "'error'", "]", "if", "'error_description'", "in", "d", ":", "error_msg", "+=", "': '", "+", "d", "[", "'error_description'", "]", "self", ".", "invalid", "=", "True", "if", "self", ".", "store", "is", "not", "None", ":", "self", ".", "store", ".", "locked_put", "(", "self", ")", "except", "(", "TypeError", ",", "ValueError", ")", ":", "pass", "raise", "HttpAccessTokenRefreshError", "(", "error_msg", ",", "status", "=", "resp", ".", "status", ")" ]
[ 764, 4 ]
[ 818, 76 ]
python
en
['en', 'gl', 'en']
True
OAuth2Credentials._revoke
(self, http)
Revokes this credential and deletes the stored copy (if it exists). Args: http: an object to be used to make HTTP requests.
Revokes this credential and deletes the stored copy (if it exists).
def _revoke(self, http): """Revokes this credential and deletes the stored copy (if it exists). Args: http: an object to be used to make HTTP requests. """ self._do_revoke(http, self.refresh_token or self.access_token)
[ "def", "_revoke", "(", "self", ",", "http", ")", ":", "self", ".", "_do_revoke", "(", "http", ",", "self", ".", "refresh_token", "or", "self", ".", "access_token", ")" ]
[ 820, 4 ]
[ 826, 70 ]
python
en
['en', 'en', 'en']
True
OAuth2Credentials._do_revoke
(self, http, token)
Revokes this credential and deletes the stored copy (if it exists). Args: http: an object to be used to make HTTP requests. token: A string used as the token to be revoked. Can be either an access_token or refresh_token. Raises: TokenRevokeError: If the revoke request does not return with a 200 OK.
Revokes this credential and deletes the stored copy (if it exists).
def _do_revoke(self, http, token): """Revokes this credential and deletes the stored copy (if it exists). Args: http: an object to be used to make HTTP requests. token: A string used as the token to be revoked. Can be either an access_token or refresh_token. Raises: TokenRevokeError: If the revoke request does not return with a 200 OK. """ logger.info('Revoking token') query_params = {'token': token} token_revoke_uri = _helpers.update_query_params( self.revoke_uri, query_params) resp, content = transport.request(http, token_revoke_uri) if resp.status == http_client.METHOD_NOT_ALLOWED: body = urllib.parse.urlencode(query_params) resp, content = transport.request(http, token_revoke_uri, method='POST', body=body) if resp.status == http_client.OK: self.invalid = True else: error_msg = 'Invalid response {0}.'.format(resp.status) try: d = json.loads(_helpers._from_bytes(content)) if 'error' in d: error_msg = d['error'] except (TypeError, ValueError): pass raise TokenRevokeError(error_msg) if self.store: self.store.delete()
[ "def", "_do_revoke", "(", "self", ",", "http", ",", "token", ")", ":", "logger", ".", "info", "(", "'Revoking token'", ")", "query_params", "=", "{", "'token'", ":", "token", "}", "token_revoke_uri", "=", "_helpers", ".", "update_query_params", "(", "self", ".", "revoke_uri", ",", "query_params", ")", "resp", ",", "content", "=", "transport", ".", "request", "(", "http", ",", "token_revoke_uri", ")", "if", "resp", ".", "status", "==", "http_client", ".", "METHOD_NOT_ALLOWED", ":", "body", "=", "urllib", ".", "parse", ".", "urlencode", "(", "query_params", ")", "resp", ",", "content", "=", "transport", ".", "request", "(", "http", ",", "token_revoke_uri", ",", "method", "=", "'POST'", ",", "body", "=", "body", ")", "if", "resp", ".", "status", "==", "http_client", ".", "OK", ":", "self", ".", "invalid", "=", "True", "else", ":", "error_msg", "=", "'Invalid response {0}.'", ".", "format", "(", "resp", ".", "status", ")", "try", ":", "d", "=", "json", ".", "loads", "(", "_helpers", ".", "_from_bytes", "(", "content", ")", ")", "if", "'error'", "in", "d", ":", "error_msg", "=", "d", "[", "'error'", "]", "except", "(", "TypeError", ",", "ValueError", ")", ":", "pass", "raise", "TokenRevokeError", "(", "error_msg", ")", "if", "self", ".", "store", ":", "self", ".", "store", ".", "delete", "(", ")" ]
[ 828, 4 ]
[ 862, 31 ]
python
en
['en', 'en', 'en']
True
OAuth2Credentials._retrieve_scopes
(self, http)
Retrieves the list of authorized scopes from the OAuth2 provider. Args: http: an object to be used to make HTTP requests.
Retrieves the list of authorized scopes from the OAuth2 provider.
def _retrieve_scopes(self, http): """Retrieves the list of authorized scopes from the OAuth2 provider. Args: http: an object to be used to make HTTP requests. """ self._do_retrieve_scopes(http, self.access_token)
[ "def", "_retrieve_scopes", "(", "self", ",", "http", ")", ":", "self", ".", "_do_retrieve_scopes", "(", "http", ",", "self", ".", "access_token", ")" ]
[ 864, 4 ]
[ 870, 57 ]
python
en
['en', 'en', 'en']
True
OAuth2Credentials._do_retrieve_scopes
(self, http, token)
Retrieves the list of authorized scopes from the OAuth2 provider. Args: http: an object to be used to make HTTP requests. token: A string used as the token to identify the credentials to the provider. Raises: Error: When refresh fails, indicating the the access token is invalid.
Retrieves the list of authorized scopes from the OAuth2 provider.
def _do_retrieve_scopes(self, http, token): """Retrieves the list of authorized scopes from the OAuth2 provider. Args: http: an object to be used to make HTTP requests. token: A string used as the token to identify the credentials to the provider. Raises: Error: When refresh fails, indicating the the access token is invalid. """ logger.info('Refreshing scopes') query_params = {'access_token': token, 'fields': 'scope'} token_info_uri = _helpers.update_query_params( self.token_info_uri, query_params) resp, content = transport.request(http, token_info_uri) content = _helpers._from_bytes(content) if resp.status == http_client.OK: d = json.loads(content) self.scopes = set(_helpers.string_to_scopes(d.get('scope', ''))) else: error_msg = 'Invalid response {0}.'.format(resp.status) try: d = json.loads(content) if 'error_description' in d: error_msg = d['error_description'] except (TypeError, ValueError): pass raise Error(error_msg)
[ "def", "_do_retrieve_scopes", "(", "self", ",", "http", ",", "token", ")", ":", "logger", ".", "info", "(", "'Refreshing scopes'", ")", "query_params", "=", "{", "'access_token'", ":", "token", ",", "'fields'", ":", "'scope'", "}", "token_info_uri", "=", "_helpers", ".", "update_query_params", "(", "self", ".", "token_info_uri", ",", "query_params", ")", "resp", ",", "content", "=", "transport", ".", "request", "(", "http", ",", "token_info_uri", ")", "content", "=", "_helpers", ".", "_from_bytes", "(", "content", ")", "if", "resp", ".", "status", "==", "http_client", ".", "OK", ":", "d", "=", "json", ".", "loads", "(", "content", ")", "self", ".", "scopes", "=", "set", "(", "_helpers", ".", "string_to_scopes", "(", "d", ".", "get", "(", "'scope'", ",", "''", ")", ")", ")", "else", ":", "error_msg", "=", "'Invalid response {0}.'", ".", "format", "(", "resp", ".", "status", ")", "try", ":", "d", "=", "json", ".", "loads", "(", "content", ")", "if", "'error_description'", "in", "d", ":", "error_msg", "=", "d", "[", "'error_description'", "]", "except", "(", "TypeError", ",", "ValueError", ")", ":", "pass", "raise", "Error", "(", "error_msg", ")" ]
[ 872, 4 ]
[ 901, 34 ]
python
en
['en', 'en', 'en']
True
AccessTokenCredentials.__init__
(self, access_token, user_agent, revoke_uri=None)
Create an instance of OAuth2Credentials This is one of the few types if Credentials that you should contrust, Credentials objects are usually instantiated by a Flow. Args: access_token: string, access token. user_agent: string, The HTTP User-Agent to provide for this application. revoke_uri: string, URI for revoke endpoint. Defaults to None; a token can't be revoked if this is None.
Create an instance of OAuth2Credentials
def __init__(self, access_token, user_agent, revoke_uri=None): """Create an instance of OAuth2Credentials This is one of the few types if Credentials that you should contrust, Credentials objects are usually instantiated by a Flow. Args: access_token: string, access token. user_agent: string, The HTTP User-Agent to provide for this application. revoke_uri: string, URI for revoke endpoint. Defaults to None; a token can't be revoked if this is None. """ super(AccessTokenCredentials, self).__init__( access_token, None, None, None, None, None, user_agent, revoke_uri=revoke_uri)
[ "def", "__init__", "(", "self", ",", "access_token", ",", "user_agent", ",", "revoke_uri", "=", "None", ")", ":", "super", "(", "AccessTokenCredentials", ",", "self", ")", ".", "__init__", "(", "access_token", ",", "None", ",", "None", ",", "None", ",", "None", ",", "None", ",", "user_agent", ",", "revoke_uri", "=", "revoke_uri", ")" ]
[ 930, 4 ]
[ 951, 34 ]
python
en
['en', 'en', 'en']
True
AccessTokenCredentials._refresh
(self, http)
Refreshes the access token. Args: http: unused HTTP object. Raises: AccessTokenCredentialsError: always
Refreshes the access token.
def _refresh(self, http): """Refreshes the access token. Args: http: unused HTTP object. Raises: AccessTokenCredentialsError: always """ raise AccessTokenCredentialsError( 'The access_token is expired or invalid and can\'t be refreshed.')
[ "def", "_refresh", "(", "self", ",", "http", ")", ":", "raise", "AccessTokenCredentialsError", "(", "'The access_token is expired or invalid and can\\'t be refreshed.'", ")" ]
[ 961, 4 ]
[ 971, 78 ]
python
en
['en', 'en', 'en']
True
AccessTokenCredentials._revoke
(self, http)
Revokes the access_token and deletes the store if available. Args: http: an object to be used to make HTTP requests.
Revokes the access_token and deletes the store if available.
def _revoke(self, http): """Revokes the access_token and deletes the store if available. Args: http: an object to be used to make HTTP requests. """ self._do_revoke(http, self.access_token)
[ "def", "_revoke", "(", "self", ",", "http", ")", ":", "self", ".", "_do_revoke", "(", "http", ",", "self", ".", "access_token", ")" ]
[ 973, 4 ]
[ 979, 48 ]
python
en
['en', 'en', 'en']
True
GoogleCredentials.__init__
(self, access_token, client_id, client_secret, refresh_token, token_expiry, token_uri, user_agent, revoke_uri=oauth2client.GOOGLE_REVOKE_URI)
Create an instance of GoogleCredentials. This constructor is not usually called by the user, instead GoogleCredentials objects are instantiated by GoogleCredentials.from_stream() or GoogleCredentials.get_application_default(). Args: access_token: string, access token. client_id: string, client identifier. client_secret: string, client secret. refresh_token: string, refresh token. token_expiry: datetime, when the access_token expires. token_uri: string, URI of token endpoint. user_agent: string, The HTTP User-Agent to provide for this application. revoke_uri: string, URI for revoke endpoint. Defaults to oauth2client.GOOGLE_REVOKE_URI; a token can't be revoked if this is None.
Create an instance of GoogleCredentials.
def __init__(self, access_token, client_id, client_secret, refresh_token, token_expiry, token_uri, user_agent, revoke_uri=oauth2client.GOOGLE_REVOKE_URI): """Create an instance of GoogleCredentials. This constructor is not usually called by the user, instead GoogleCredentials objects are instantiated by GoogleCredentials.from_stream() or GoogleCredentials.get_application_default(). Args: access_token: string, access token. client_id: string, client identifier. client_secret: string, client secret. refresh_token: string, refresh token. token_expiry: datetime, when the access_token expires. token_uri: string, URI of token endpoint. user_agent: string, The HTTP User-Agent to provide for this application. revoke_uri: string, URI for revoke endpoint. Defaults to oauth2client.GOOGLE_REVOKE_URI; a token can't be revoked if this is None. """ super(GoogleCredentials, self).__init__( access_token, client_id, client_secret, refresh_token, token_expiry, token_uri, user_agent, revoke_uri=revoke_uri)
[ "def", "__init__", "(", "self", ",", "access_token", ",", "client_id", ",", "client_secret", ",", "refresh_token", ",", "token_expiry", ",", "token_uri", ",", "user_agent", ",", "revoke_uri", "=", "oauth2client", ".", "GOOGLE_REVOKE_URI", ")", ":", "super", "(", "GoogleCredentials", ",", "self", ")", ".", "__init__", "(", "access_token", ",", "client_id", ",", "client_secret", ",", "refresh_token", ",", "token_expiry", ",", "token_uri", ",", "user_agent", ",", "revoke_uri", "=", "revoke_uri", ")" ]
[ 1077, 4 ]
[ 1102, 71 ]
python
en
['en', 'de', 'en']
True
GoogleCredentials.create_scoped_required
(self)
Whether this Credentials object is scopeless. create_scoped(scopes) method needs to be called in order to create a Credentials object for API calls.
Whether this Credentials object is scopeless.
def create_scoped_required(self): """Whether this Credentials object is scopeless. create_scoped(scopes) method needs to be called in order to create a Credentials object for API calls. """ return False
[ "def", "create_scoped_required", "(", "self", ")", ":", "return", "False" ]
[ 1104, 4 ]
[ 1110, 20 ]
python
en
['en', 'en', 'en']
True
GoogleCredentials.create_scoped
(self, scopes)
Create a Credentials object for the given scopes. The Credentials type is preserved.
Create a Credentials object for the given scopes.
def create_scoped(self, scopes): """Create a Credentials object for the given scopes. The Credentials type is preserved. """ return self
[ "def", "create_scoped", "(", "self", ",", "scopes", ")", ":", "return", "self" ]
[ 1112, 4 ]
[ 1117, 19 ]
python
en
['en', 'en', 'en']
True
GoogleCredentials.serialization_data
(self)
Get the fields and values identifying the current credentials.
Get the fields and values identifying the current credentials.
def serialization_data(self): """Get the fields and values identifying the current credentials.""" return { 'type': 'authorized_user', 'client_id': self.client_id, 'client_secret': self.client_secret, 'refresh_token': self.refresh_token }
[ "def", "serialization_data", "(", "self", ")", ":", "return", "{", "'type'", ":", "'authorized_user'", ",", "'client_id'", ":", "self", ".", "client_id", ",", "'client_secret'", ":", "self", ".", "client_secret", ",", "'refresh_token'", ":", "self", ".", "refresh_token", "}" ]
[ 1149, 4 ]
[ 1156, 9 ]
python
en
['en', 'en', 'en']
True
GoogleCredentials._implicit_credentials_from_gae
()
Attempts to get implicit credentials in Google App Engine env. If the current environment is not detected as App Engine, returns None, indicating no Google App Engine credentials can be detected from the current environment. Returns: None, if not in GAE, else an appengine.AppAssertionCredentials object.
Attempts to get implicit credentials in Google App Engine env.
def _implicit_credentials_from_gae(): """Attempts to get implicit credentials in Google App Engine env. If the current environment is not detected as App Engine, returns None, indicating no Google App Engine credentials can be detected from the current environment. Returns: None, if not in GAE, else an appengine.AppAssertionCredentials object. """ if not _in_gae_environment(): return None return _get_application_default_credential_GAE()
[ "def", "_implicit_credentials_from_gae", "(", ")", ":", "if", "not", "_in_gae_environment", "(", ")", ":", "return", "None", "return", "_get_application_default_credential_GAE", "(", ")" ]
[ 1159, 4 ]
[ 1173, 56 ]
python
en
['en', 'en', 'en']
True
GoogleCredentials._implicit_credentials_from_gce
()
Attempts to get implicit credentials in Google Compute Engine env. If the current environment is not detected as Compute Engine, returns None, indicating no Google Compute Engine credentials can be detected from the current environment. Returns: None, if not in GCE, else a gce.AppAssertionCredentials object.
Attempts to get implicit credentials in Google Compute Engine env.
def _implicit_credentials_from_gce(): """Attempts to get implicit credentials in Google Compute Engine env. If the current environment is not detected as Compute Engine, returns None, indicating no Google Compute Engine credentials can be detected from the current environment. Returns: None, if not in GCE, else a gce.AppAssertionCredentials object. """ if not _in_gce_environment(): return None return _get_application_default_credential_GCE()
[ "def", "_implicit_credentials_from_gce", "(", ")", ":", "if", "not", "_in_gce_environment", "(", ")", ":", "return", "None", "return", "_get_application_default_credential_GCE", "(", ")" ]
[ 1176, 4 ]
[ 1189, 56 ]
python
en
['en', 'en', 'en']
True
GoogleCredentials._implicit_credentials_from_files
()
Attempts to get implicit credentials from local credential files. First checks if the environment variable GOOGLE_APPLICATION_CREDENTIALS is set with a filename and then falls back to a configuration file (the "well known" file) associated with the 'gcloud' command line tool. Returns: Credentials object associated with the GOOGLE_APPLICATION_CREDENTIALS file or the "well known" file if either exist. If neither file is define, returns None, indicating no credentials from a file can detected from the current environment.
Attempts to get implicit credentials from local credential files.
def _implicit_credentials_from_files(): """Attempts to get implicit credentials from local credential files. First checks if the environment variable GOOGLE_APPLICATION_CREDENTIALS is set with a filename and then falls back to a configuration file (the "well known" file) associated with the 'gcloud' command line tool. Returns: Credentials object associated with the GOOGLE_APPLICATION_CREDENTIALS file or the "well known" file if either exist. If neither file is define, returns None, indicating no credentials from a file can detected from the current environment. """ credentials_filename = _get_environment_variable_file() if not credentials_filename: credentials_filename = _get_well_known_file() if os.path.isfile(credentials_filename): extra_help = (' (produced automatically when running' ' "gcloud auth login" command)') else: credentials_filename = None else: extra_help = (' (pointed to by ' + GOOGLE_APPLICATION_CREDENTIALS + ' environment variable)') if not credentials_filename: return # If we can read the credentials from a file, we don't need to know # what environment we are in. SETTINGS.env_name = DEFAULT_ENV_NAME try: return _get_application_default_credential_from_file( credentials_filename) except (ApplicationDefaultCredentialsError, ValueError) as error: _raise_exception_for_reading_json(credentials_filename, extra_help, error)
[ "def", "_implicit_credentials_from_files", "(", ")", ":", "credentials_filename", "=", "_get_environment_variable_file", "(", ")", "if", "not", "credentials_filename", ":", "credentials_filename", "=", "_get_well_known_file", "(", ")", "if", "os", ".", "path", ".", "isfile", "(", "credentials_filename", ")", ":", "extra_help", "=", "(", "' (produced automatically when running'", "' \"gcloud auth login\" command)'", ")", "else", ":", "credentials_filename", "=", "None", "else", ":", "extra_help", "=", "(", "' (pointed to by '", "+", "GOOGLE_APPLICATION_CREDENTIALS", "+", "' environment variable)'", ")", "if", "not", "credentials_filename", ":", "return", "# If we can read the credentials from a file, we don't need to know", "# what environment we are in.", "SETTINGS", ".", "env_name", "=", "DEFAULT_ENV_NAME", "try", ":", "return", "_get_application_default_credential_from_file", "(", "credentials_filename", ")", "except", "(", "ApplicationDefaultCredentialsError", ",", "ValueError", ")", "as", "error", ":", "_raise_exception_for_reading_json", "(", "credentials_filename", ",", "extra_help", ",", "error", ")" ]
[ 1192, 4 ]
[ 1230, 64 ]
python
en
['en', 'en', 'en']
True
GoogleCredentials._get_implicit_credentials
(cls)
Gets credentials implicitly from the environment. Checks environment in order of precedence: - Environment variable GOOGLE_APPLICATION_CREDENTIALS pointing to a file with stored credentials information. - Stored "well known" file associated with `gcloud` command line tool. - Google App Engine (production and testing) - Google Compute Engine production environment. Raises: ApplicationDefaultCredentialsError: raised when the credentials fail to be retrieved.
Gets credentials implicitly from the environment.
def _get_implicit_credentials(cls): """Gets credentials implicitly from the environment. Checks environment in order of precedence: - Environment variable GOOGLE_APPLICATION_CREDENTIALS pointing to a file with stored credentials information. - Stored "well known" file associated with `gcloud` command line tool. - Google App Engine (production and testing) - Google Compute Engine production environment. Raises: ApplicationDefaultCredentialsError: raised when the credentials fail to be retrieved. """ # Environ checks (in order). environ_checkers = [ cls._implicit_credentials_from_files, cls._implicit_credentials_from_gae, cls._implicit_credentials_from_gce, ] for checker in environ_checkers: credentials = checker() if credentials is not None: return credentials # If no credentials, fail. raise ApplicationDefaultCredentialsError(ADC_HELP_MSG)
[ "def", "_get_implicit_credentials", "(", "cls", ")", ":", "# Environ checks (in order).", "environ_checkers", "=", "[", "cls", ".", "_implicit_credentials_from_files", ",", "cls", ".", "_implicit_credentials_from_gae", ",", "cls", ".", "_implicit_credentials_from_gce", ",", "]", "for", "checker", "in", "environ_checkers", ":", "credentials", "=", "checker", "(", ")", "if", "credentials", "is", "not", "None", ":", "return", "credentials", "# If no credentials, fail.", "raise", "ApplicationDefaultCredentialsError", "(", "ADC_HELP_MSG", ")" ]
[ 1233, 4 ]
[ 1260, 62 ]
python
en
['en', 'en', 'en']
True
GoogleCredentials.get_application_default
()
Get the Application Default Credentials for the current environment. Raises: ApplicationDefaultCredentialsError: raised when the credentials fail to be retrieved.
Get the Application Default Credentials for the current environment.
def get_application_default(): """Get the Application Default Credentials for the current environment. Raises: ApplicationDefaultCredentialsError: raised when the credentials fail to be retrieved. """ return GoogleCredentials._get_implicit_credentials()
[ "def", "get_application_default", "(", ")", ":", "return", "GoogleCredentials", ".", "_get_implicit_credentials", "(", ")" ]
[ 1263, 4 ]
[ 1270, 60 ]
python
en
['en', 'en', 'en']
True
GoogleCredentials.from_stream
(credential_filename)
Create a Credentials object by reading information from a file. It returns an object of type GoogleCredentials. Args: credential_filename: the path to the file from where the credentials are to be read Raises: ApplicationDefaultCredentialsError: raised when the credentials fail to be retrieved.
Create a Credentials object by reading information from a file.
def from_stream(credential_filename): """Create a Credentials object by reading information from a file. It returns an object of type GoogleCredentials. Args: credential_filename: the path to the file from where the credentials are to be read Raises: ApplicationDefaultCredentialsError: raised when the credentials fail to be retrieved. """ if credential_filename and os.path.isfile(credential_filename): try: return _get_application_default_credential_from_file( credential_filename) except (ApplicationDefaultCredentialsError, ValueError) as error: extra_help = (' (provided as parameter to the ' 'from_stream() method)') _raise_exception_for_reading_json(credential_filename, extra_help, error) else: raise ApplicationDefaultCredentialsError( 'The parameter passed to the from_stream() ' 'method should point to a file.')
[ "def", "from_stream", "(", "credential_filename", ")", ":", "if", "credential_filename", "and", "os", ".", "path", ".", "isfile", "(", "credential_filename", ")", ":", "try", ":", "return", "_get_application_default_credential_from_file", "(", "credential_filename", ")", "except", "(", "ApplicationDefaultCredentialsError", ",", "ValueError", ")", "as", "error", ":", "extra_help", "=", "(", "' (provided as parameter to the '", "'from_stream() method)'", ")", "_raise_exception_for_reading_json", "(", "credential_filename", ",", "extra_help", ",", "error", ")", "else", ":", "raise", "ApplicationDefaultCredentialsError", "(", "'The parameter passed to the from_stream() '", "'method should point to a file.'", ")" ]
[ 1273, 4 ]
[ 1299, 49 ]
python
en
['en', 'en', 'en']
True
AssertionCredentials.__init__
(self, assertion_type, user_agent=None, token_uri=oauth2client.GOOGLE_TOKEN_URI, revoke_uri=oauth2client.GOOGLE_REVOKE_URI, **unused_kwargs)
Constructor for AssertionFlowCredentials. Args: assertion_type: string, assertion type that will be declared to the auth server user_agent: string, The HTTP User-Agent to provide for this application. token_uri: string, URI for token endpoint. For convenience defaults to Google's endpoints but any OAuth 2.0 provider can be used. revoke_uri: string, URI for revoke endpoint.
Constructor for AssertionFlowCredentials.
def __init__(self, assertion_type, user_agent=None, token_uri=oauth2client.GOOGLE_TOKEN_URI, revoke_uri=oauth2client.GOOGLE_REVOKE_URI, **unused_kwargs): """Constructor for AssertionFlowCredentials. Args: assertion_type: string, assertion type that will be declared to the auth server user_agent: string, The HTTP User-Agent to provide for this application. token_uri: string, URI for token endpoint. For convenience defaults to Google's endpoints but any OAuth 2.0 provider can be used. revoke_uri: string, URI for revoke endpoint. """ super(AssertionCredentials, self).__init__( None, None, None, None, None, token_uri, user_agent, revoke_uri=revoke_uri) self.assertion_type = assertion_type
[ "def", "__init__", "(", "self", ",", "assertion_type", ",", "user_agent", "=", "None", ",", "token_uri", "=", "oauth2client", ".", "GOOGLE_TOKEN_URI", ",", "revoke_uri", "=", "oauth2client", ".", "GOOGLE_REVOKE_URI", ",", "*", "*", "unused_kwargs", ")", ":", "super", "(", "AssertionCredentials", ",", "self", ")", ".", "__init__", "(", "None", ",", "None", ",", "None", ",", "None", ",", "None", ",", "token_uri", ",", "user_agent", ",", "revoke_uri", "=", "revoke_uri", ")", "self", ".", "assertion_type", "=", "assertion_type" ]
[ 1455, 4 ]
[ 1480, 44 ]
python
en
['da', 'en', 'en']
True
AssertionCredentials._generate_assertion
(self)
Generate assertion string to be used in the access token request.
Generate assertion string to be used in the access token request.
def _generate_assertion(self): """Generate assertion string to be used in the access token request.""" raise NotImplementedError
[ "def", "_generate_assertion", "(", "self", ")", ":", "raise", "NotImplementedError" ]
[ 1492, 4 ]
[ 1494, 33 ]
python
en
['en', 'en', 'en']
True
AssertionCredentials._revoke
(self, http)
Revokes the access_token and deletes the store if available. Args: http: an object to be used to make HTTP requests.
Revokes the access_token and deletes the store if available.
def _revoke(self, http): """Revokes the access_token and deletes the store if available. Args: http: an object to be used to make HTTP requests. """ self._do_revoke(http, self.access_token)
[ "def", "_revoke", "(", "self", ",", "http", ")", ":", "self", ".", "_do_revoke", "(", "http", ",", "self", ".", "access_token", ")" ]
[ 1496, 4 ]
[ 1502, 48 ]
python
en
['en', 'en', 'en']
True
AssertionCredentials.sign_blob
(self, blob)
Cryptographically sign a blob (of bytes). Args: blob: bytes, Message to be signed. Returns: tuple, A pair of the private key ID used to sign the blob and the signed contents.
Cryptographically sign a blob (of bytes).
def sign_blob(self, blob): """Cryptographically sign a blob (of bytes). Args: blob: bytes, Message to be signed. Returns: tuple, A pair of the private key ID used to sign the blob and the signed contents. """ raise NotImplementedError('This method is abstract.')
[ "def", "sign_blob", "(", "self", ",", "blob", ")", ":", "raise", "NotImplementedError", "(", "'This method is abstract.'", ")" ]
[ 1504, 4 ]
[ 1514, 61 ]
python
en
['en', 'en', 'en']
True
DeviceFlowInfo.FromResponse
(cls, response)
Create a DeviceFlowInfo from a server response. The response should be a dict containing entries as described here: http://tools.ietf.org/html/draft-ietf-oauth-v2-05#section-3.7.1
Create a DeviceFlowInfo from a server response.
def FromResponse(cls, response): """Create a DeviceFlowInfo from a server response. The response should be a dict containing entries as described here: http://tools.ietf.org/html/draft-ietf-oauth-v2-05#section-3.7.1 """ # device_code, user_code, and verification_url are required. kwargs = { 'device_code': response['device_code'], 'user_code': response['user_code'], } # The response may list the verification address as either # verification_url or verification_uri, so we check for both. verification_url = response.get( 'verification_url', response.get('verification_uri')) if verification_url is None: raise OAuth2DeviceCodeError( 'No verification_url provided in server response') kwargs['verification_url'] = verification_url # expires_in and interval are optional. kwargs.update({ 'interval': response.get('interval'), 'user_code_expiry': None, }) if 'expires_in' in response: kwargs['user_code_expiry'] = ( _UTCNOW() + datetime.timedelta(seconds=int(response['expires_in']))) return cls(**kwargs)
[ "def", "FromResponse", "(", "cls", ",", "response", ")", ":", "# device_code, user_code, and verification_url are required.", "kwargs", "=", "{", "'device_code'", ":", "response", "[", "'device_code'", "]", ",", "'user_code'", ":", "response", "[", "'user_code'", "]", ",", "}", "# The response may list the verification address as either", "# verification_url or verification_uri, so we check for both.", "verification_url", "=", "response", ".", "get", "(", "'verification_url'", ",", "response", ".", "get", "(", "'verification_uri'", ")", ")", "if", "verification_url", "is", "None", ":", "raise", "OAuth2DeviceCodeError", "(", "'No verification_url provided in server response'", ")", "kwargs", "[", "'verification_url'", "]", "=", "verification_url", "# expires_in and interval are optional.", "kwargs", ".", "update", "(", "{", "'interval'", ":", "response", ".", "get", "(", "'interval'", ")", ",", "'user_code_expiry'", ":", "None", ",", "}", ")", "if", "'expires_in'", "in", "response", ":", "kwargs", "[", "'user_code_expiry'", "]", "=", "(", "_UTCNOW", "(", ")", "+", "datetime", ".", "timedelta", "(", "seconds", "=", "int", "(", "response", "[", "'expires_in'", "]", ")", ")", ")", "return", "cls", "(", "*", "*", "kwargs", ")" ]
[ 1745, 4 ]
[ 1774, 28 ]
python
en
['en', 'en', 'en']
True
OAuth2WebServerFlow.__init__
(self, client_id, client_secret=None, scope=None, redirect_uri=None, user_agent=None, auth_uri=oauth2client.GOOGLE_AUTH_URI, token_uri=oauth2client.GOOGLE_TOKEN_URI, revoke_uri=oauth2client.GOOGLE_REVOKE_URI, login_hint=None, device_uri=oauth2client.GOOGLE_DEVICE_URI, token_info_uri=oauth2client.GOOGLE_TOKEN_INFO_URI, authorization_header=None, pkce=False, code_verifier=None, **kwargs)
Constructor for OAuth2WebServerFlow. The kwargs argument is used to set extra query parameters on the auth_uri. For example, the access_type and prompt query parameters can be set via kwargs. Args: client_id: string, client identifier. client_secret: string client secret. scope: string or iterable of strings, scope(s) of the credentials being requested. redirect_uri: string, Either the string 'urn:ietf:wg:oauth:2.0:oob' for a non-web-based application, or a URI that handles the callback from the authorization server. user_agent: string, HTTP User-Agent to provide for this application. auth_uri: string, URI for authorization endpoint. For convenience defaults to Google's endpoints but any OAuth 2.0 provider can be used. token_uri: string, URI for token endpoint. For convenience defaults to Google's endpoints but any OAuth 2.0 provider can be used. revoke_uri: string, URI for revoke endpoint. For convenience defaults to Google's endpoints but any OAuth 2.0 provider can be used. login_hint: string, Either an email address or domain. Passing this hint will either pre-fill the email box on the sign-in form or select the proper multi-login session, thereby simplifying the login flow. device_uri: string, URI for device authorization endpoint. For convenience defaults to Google's endpoints but any OAuth 2.0 provider can be used. authorization_header: string, For use with OAuth 2.0 providers that require a client to authenticate using a header value instead of passing client_secret in the POST body. pkce: boolean, default: False, Generate and include a "Proof Key for Code Exchange" (PKCE) with your authorization and token requests. This adds security for installed applications that cannot protect a client_secret. See RFC 7636 for details. code_verifier: bytestring or None, default: None, parameter passed as part of the code exchange when pkce=True. If None, a code_verifier will automatically be generated as part of step1_get_authorize_url(). See RFC 7636 for details. **kwargs: dict, The keyword arguments are all optional and required parameters for the OAuth calls.
Constructor for OAuth2WebServerFlow.
def __init__(self, client_id, client_secret=None, scope=None, redirect_uri=None, user_agent=None, auth_uri=oauth2client.GOOGLE_AUTH_URI, token_uri=oauth2client.GOOGLE_TOKEN_URI, revoke_uri=oauth2client.GOOGLE_REVOKE_URI, login_hint=None, device_uri=oauth2client.GOOGLE_DEVICE_URI, token_info_uri=oauth2client.GOOGLE_TOKEN_INFO_URI, authorization_header=None, pkce=False, code_verifier=None, **kwargs): """Constructor for OAuth2WebServerFlow. The kwargs argument is used to set extra query parameters on the auth_uri. For example, the access_type and prompt query parameters can be set via kwargs. Args: client_id: string, client identifier. client_secret: string client secret. scope: string or iterable of strings, scope(s) of the credentials being requested. redirect_uri: string, Either the string 'urn:ietf:wg:oauth:2.0:oob' for a non-web-based application, or a URI that handles the callback from the authorization server. user_agent: string, HTTP User-Agent to provide for this application. auth_uri: string, URI for authorization endpoint. For convenience defaults to Google's endpoints but any OAuth 2.0 provider can be used. token_uri: string, URI for token endpoint. For convenience defaults to Google's endpoints but any OAuth 2.0 provider can be used. revoke_uri: string, URI for revoke endpoint. For convenience defaults to Google's endpoints but any OAuth 2.0 provider can be used. login_hint: string, Either an email address or domain. Passing this hint will either pre-fill the email box on the sign-in form or select the proper multi-login session, thereby simplifying the login flow. device_uri: string, URI for device authorization endpoint. For convenience defaults to Google's endpoints but any OAuth 2.0 provider can be used. authorization_header: string, For use with OAuth 2.0 providers that require a client to authenticate using a header value instead of passing client_secret in the POST body. pkce: boolean, default: False, Generate and include a "Proof Key for Code Exchange" (PKCE) with your authorization and token requests. This adds security for installed applications that cannot protect a client_secret. See RFC 7636 for details. code_verifier: bytestring or None, default: None, parameter passed as part of the code exchange when pkce=True. If None, a code_verifier will automatically be generated as part of step1_get_authorize_url(). See RFC 7636 for details. **kwargs: dict, The keyword arguments are all optional and required parameters for the OAuth calls. """ # scope is a required argument, but to preserve backwards-compatibility # we don't want to rearrange the positional arguments if scope is None: raise TypeError("The value of scope must not be None") self.client_id = client_id self.client_secret = client_secret self.scope = _helpers.scopes_to_string(scope) self.redirect_uri = redirect_uri self.login_hint = login_hint self.user_agent = user_agent self.auth_uri = auth_uri self.token_uri = token_uri self.revoke_uri = revoke_uri self.device_uri = device_uri self.token_info_uri = token_info_uri self.authorization_header = authorization_header self._pkce = pkce self.code_verifier = code_verifier self.params = _oauth2_web_server_flow_params(kwargs)
[ "def", "__init__", "(", "self", ",", "client_id", ",", "client_secret", "=", "None", ",", "scope", "=", "None", ",", "redirect_uri", "=", "None", ",", "user_agent", "=", "None", ",", "auth_uri", "=", "oauth2client", ".", "GOOGLE_AUTH_URI", ",", "token_uri", "=", "oauth2client", ".", "GOOGLE_TOKEN_URI", ",", "revoke_uri", "=", "oauth2client", ".", "GOOGLE_REVOKE_URI", ",", "login_hint", "=", "None", ",", "device_uri", "=", "oauth2client", ".", "GOOGLE_DEVICE_URI", ",", "token_info_uri", "=", "oauth2client", ".", "GOOGLE_TOKEN_INFO_URI", ",", "authorization_header", "=", "None", ",", "pkce", "=", "False", ",", "code_verifier", "=", "None", ",", "*", "*", "kwargs", ")", ":", "# scope is a required argument, but to preserve backwards-compatibility", "# we don't want to rearrange the positional arguments", "if", "scope", "is", "None", ":", "raise", "TypeError", "(", "\"The value of scope must not be None\"", ")", "self", ".", "client_id", "=", "client_id", "self", ".", "client_secret", "=", "client_secret", "self", ".", "scope", "=", "_helpers", ".", "scopes_to_string", "(", "scope", ")", "self", ".", "redirect_uri", "=", "redirect_uri", "self", ".", "login_hint", "=", "login_hint", "self", ".", "user_agent", "=", "user_agent", "self", ".", "auth_uri", "=", "auth_uri", "self", ".", "token_uri", "=", "token_uri", "self", ".", "revoke_uri", "=", "revoke_uri", "self", ".", "device_uri", "=", "device_uri", "self", ".", "token_info_uri", "=", "token_info_uri", "self", ".", "authorization_header", "=", "authorization_header", "self", ".", "_pkce", "=", "pkce", "self", ".", "code_verifier", "=", "code_verifier", "self", ".", "params", "=", "_oauth2_web_server_flow_params", "(", "kwargs", ")" ]
[ 1811, 4 ]
[ 1892, 60 ]
python
en
['da', 'en', 'en']
True
OAuth2WebServerFlow.step1_get_authorize_url
(self, redirect_uri=None, state=None)
Returns a URI to redirect to the provider. Args: redirect_uri: string, Either the string 'urn:ietf:wg:oauth:2.0:oob' for a non-web-based application, or a URI that handles the callback from the authorization server. This parameter is deprecated, please move to passing the redirect_uri in via the constructor. state: string, Opaque state string which is passed through the OAuth2 flow and returned to the client as a query parameter in the callback. Returns: A URI as a string to redirect the user to begin the authorization flow.
Returns a URI to redirect to the provider.
def step1_get_authorize_url(self, redirect_uri=None, state=None): """Returns a URI to redirect to the provider. Args: redirect_uri: string, Either the string 'urn:ietf:wg:oauth:2.0:oob' for a non-web-based application, or a URI that handles the callback from the authorization server. This parameter is deprecated, please move to passing the redirect_uri in via the constructor. state: string, Opaque state string which is passed through the OAuth2 flow and returned to the client as a query parameter in the callback. Returns: A URI as a string to redirect the user to begin the authorization flow. """ if redirect_uri is not None: logger.warning(( 'The redirect_uri parameter for ' 'OAuth2WebServerFlow.step1_get_authorize_url is deprecated. ' 'Please move to passing the redirect_uri in via the ' 'constructor.')) self.redirect_uri = redirect_uri if self.redirect_uri is None: raise ValueError('The value of redirect_uri must not be None.') query_params = { 'client_id': self.client_id, 'redirect_uri': self.redirect_uri, 'scope': self.scope, } if state is not None: query_params['state'] = state if self.login_hint is not None: query_params['login_hint'] = self.login_hint if self._pkce: if not self.code_verifier: self.code_verifier = _pkce.code_verifier() challenge = _pkce.code_challenge(self.code_verifier) query_params['code_challenge'] = challenge query_params['code_challenge_method'] = 'S256' query_params.update(self.params) return _helpers.update_query_params(self.auth_uri, query_params)
[ "def", "step1_get_authorize_url", "(", "self", ",", "redirect_uri", "=", "None", ",", "state", "=", "None", ")", ":", "if", "redirect_uri", "is", "not", "None", ":", "logger", ".", "warning", "(", "(", "'The redirect_uri parameter for '", "'OAuth2WebServerFlow.step1_get_authorize_url is deprecated. '", "'Please move to passing the redirect_uri in via the '", "'constructor.'", ")", ")", "self", ".", "redirect_uri", "=", "redirect_uri", "if", "self", ".", "redirect_uri", "is", "None", ":", "raise", "ValueError", "(", "'The value of redirect_uri must not be None.'", ")", "query_params", "=", "{", "'client_id'", ":", "self", ".", "client_id", ",", "'redirect_uri'", ":", "self", ".", "redirect_uri", ",", "'scope'", ":", "self", ".", "scope", ",", "}", "if", "state", "is", "not", "None", ":", "query_params", "[", "'state'", "]", "=", "state", "if", "self", ".", "login_hint", "is", "not", "None", ":", "query_params", "[", "'login_hint'", "]", "=", "self", ".", "login_hint", "if", "self", ".", "_pkce", ":", "if", "not", "self", ".", "code_verifier", ":", "self", ".", "code_verifier", "=", "_pkce", ".", "code_verifier", "(", ")", "challenge", "=", "_pkce", ".", "code_challenge", "(", "self", ".", "code_verifier", ")", "query_params", "[", "'code_challenge'", "]", "=", "challenge", "query_params", "[", "'code_challenge_method'", "]", "=", "'S256'", "query_params", ".", "update", "(", "self", ".", "params", ")", "return", "_helpers", ".", "update_query_params", "(", "self", ".", "auth_uri", ",", "query_params", ")" ]
[ 1895, 4 ]
[ 1940, 72 ]
python
en
['en', 'en', 'en']
True
OAuth2WebServerFlow.step1_get_device_and_user_codes
(self, http=None)
Returns a user code and the verification URL where to enter it Returns: A user code as a string for the user to authorize the application An URL as a string where the user has to enter the code
Returns a user code and the verification URL where to enter it
def step1_get_device_and_user_codes(self, http=None): """Returns a user code and the verification URL where to enter it Returns: A user code as a string for the user to authorize the application An URL as a string where the user has to enter the code """ if self.device_uri is None: raise ValueError('The value of device_uri must not be None.') body = urllib.parse.urlencode({ 'client_id': self.client_id, 'scope': self.scope, }) headers = { 'content-type': 'application/x-www-form-urlencoded', } if self.user_agent is not None: headers['user-agent'] = self.user_agent if http is None: http = transport.get_http_object() resp, content = transport.request( http, self.device_uri, method='POST', body=body, headers=headers) content = _helpers._from_bytes(content) if resp.status == http_client.OK: try: flow_info = json.loads(content) except ValueError as exc: raise OAuth2DeviceCodeError( 'Could not parse server response as JSON: "{0}", ' 'error: "{1}"'.format(content, exc)) return DeviceFlowInfo.FromResponse(flow_info) else: error_msg = 'Invalid response {0}.'.format(resp.status) try: error_dict = json.loads(content) if 'error' in error_dict: error_msg += ' Error: {0}'.format(error_dict['error']) except ValueError: # Couldn't decode a JSON response, stick with the # default message. pass raise OAuth2DeviceCodeError(error_msg)
[ "def", "step1_get_device_and_user_codes", "(", "self", ",", "http", "=", "None", ")", ":", "if", "self", ".", "device_uri", "is", "None", ":", "raise", "ValueError", "(", "'The value of device_uri must not be None.'", ")", "body", "=", "urllib", ".", "parse", ".", "urlencode", "(", "{", "'client_id'", ":", "self", ".", "client_id", ",", "'scope'", ":", "self", ".", "scope", ",", "}", ")", "headers", "=", "{", "'content-type'", ":", "'application/x-www-form-urlencoded'", ",", "}", "if", "self", ".", "user_agent", "is", "not", "None", ":", "headers", "[", "'user-agent'", "]", "=", "self", ".", "user_agent", "if", "http", "is", "None", ":", "http", "=", "transport", ".", "get_http_object", "(", ")", "resp", ",", "content", "=", "transport", ".", "request", "(", "http", ",", "self", ".", "device_uri", ",", "method", "=", "'POST'", ",", "body", "=", "body", ",", "headers", "=", "headers", ")", "content", "=", "_helpers", ".", "_from_bytes", "(", "content", ")", "if", "resp", ".", "status", "==", "http_client", ".", "OK", ":", "try", ":", "flow_info", "=", "json", ".", "loads", "(", "content", ")", "except", "ValueError", "as", "exc", ":", "raise", "OAuth2DeviceCodeError", "(", "'Could not parse server response as JSON: \"{0}\", '", "'error: \"{1}\"'", ".", "format", "(", "content", ",", "exc", ")", ")", "return", "DeviceFlowInfo", ".", "FromResponse", "(", "flow_info", ")", "else", ":", "error_msg", "=", "'Invalid response {0}.'", ".", "format", "(", "resp", ".", "status", ")", "try", ":", "error_dict", "=", "json", ".", "loads", "(", "content", ")", "if", "'error'", "in", "error_dict", ":", "error_msg", "+=", "' Error: {0}'", ".", "format", "(", "error_dict", "[", "'error'", "]", ")", "except", "ValueError", ":", "# Couldn't decode a JSON response, stick with the", "# default message.", "pass", "raise", "OAuth2DeviceCodeError", "(", "error_msg", ")" ]
[ 1943, 4 ]
[ 1988, 50 ]
python
en
['en', 'en', 'en']
True
OAuth2WebServerFlow.step2_exchange
(self, code=None, http=None, device_flow_info=None)
Exchanges a code for OAuth2Credentials. Args: code: string, a dict-like object, or None. For a non-device flow, this is either the response code as a string, or a dictionary of query parameters to the redirect_uri. For a device flow, this should be None. http: httplib2.Http, optional http instance to use when fetching credentials. device_flow_info: DeviceFlowInfo, return value from step1 in the case of a device flow. Returns: An OAuth2Credentials object that can be used to authorize requests. Raises: FlowExchangeError: if a problem occurred exchanging the code for a refresh_token. ValueError: if code and device_flow_info are both provided or both missing.
Exchanges a code for OAuth2Credentials.
def step2_exchange(self, code=None, http=None, device_flow_info=None): """Exchanges a code for OAuth2Credentials. Args: code: string, a dict-like object, or None. For a non-device flow, this is either the response code as a string, or a dictionary of query parameters to the redirect_uri. For a device flow, this should be None. http: httplib2.Http, optional http instance to use when fetching credentials. device_flow_info: DeviceFlowInfo, return value from step1 in the case of a device flow. Returns: An OAuth2Credentials object that can be used to authorize requests. Raises: FlowExchangeError: if a problem occurred exchanging the code for a refresh_token. ValueError: if code and device_flow_info are both provided or both missing. """ if code is None and device_flow_info is None: raise ValueError('No code or device_flow_info provided.') if code is not None and device_flow_info is not None: raise ValueError('Cannot provide both code and device_flow_info.') if code is None: code = device_flow_info.device_code elif not isinstance(code, (six.string_types, six.binary_type)): if 'code' not in code: raise FlowExchangeError(code.get( 'error', 'No code was supplied in the query parameters.')) code = code['code'] post_data = { 'client_id': self.client_id, 'code': code, 'scope': self.scope, } if self.client_secret is not None: post_data['client_secret'] = self.client_secret if self._pkce: post_data['code_verifier'] = self.code_verifier if device_flow_info is not None: post_data['grant_type'] = 'http://oauth.net/grant_type/device/1.0' else: post_data['grant_type'] = 'authorization_code' post_data['redirect_uri'] = self.redirect_uri body = urllib.parse.urlencode(post_data) headers = { 'content-type': 'application/x-www-form-urlencoded', } if self.authorization_header is not None: headers['Authorization'] = self.authorization_header if self.user_agent is not None: headers['user-agent'] = self.user_agent if http is None: http = transport.get_http_object() resp, content = transport.request( http, self.token_uri, method='POST', body=body, headers=headers) d = _parse_exchange_token_response(content) if resp.status == http_client.OK and 'access_token' in d: access_token = d['access_token'] refresh_token = d.get('refresh_token', None) if not refresh_token: logger.info( 'Received token response with no refresh_token. Consider ' "reauthenticating with prompt='consent'.") token_expiry = None if 'expires_in' in d: delta = datetime.timedelta(seconds=int(d['expires_in'])) token_expiry = delta + _UTCNOW() extracted_id_token = None id_token_jwt = None if 'id_token' in d: extracted_id_token = _extract_id_token(d['id_token']) id_token_jwt = d['id_token'] logger.info('Successfully retrieved access token') return OAuth2Credentials( access_token, self.client_id, self.client_secret, refresh_token, token_expiry, self.token_uri, self.user_agent, revoke_uri=self.revoke_uri, id_token=extracted_id_token, id_token_jwt=id_token_jwt, token_response=d, scopes=self.scope, token_info_uri=self.token_info_uri) else: logger.info('Failed to retrieve access token: %s', content) if 'error' in d: # you never know what those providers got to say error_msg = (str(d['error']) + str(d.get('error_description', ''))) else: error_msg = 'Invalid response: {0}.'.format(str(resp.status)) raise FlowExchangeError(error_msg)
[ "def", "step2_exchange", "(", "self", ",", "code", "=", "None", ",", "http", "=", "None", ",", "device_flow_info", "=", "None", ")", ":", "if", "code", "is", "None", "and", "device_flow_info", "is", "None", ":", "raise", "ValueError", "(", "'No code or device_flow_info provided.'", ")", "if", "code", "is", "not", "None", "and", "device_flow_info", "is", "not", "None", ":", "raise", "ValueError", "(", "'Cannot provide both code and device_flow_info.'", ")", "if", "code", "is", "None", ":", "code", "=", "device_flow_info", ".", "device_code", "elif", "not", "isinstance", "(", "code", ",", "(", "six", ".", "string_types", ",", "six", ".", "binary_type", ")", ")", ":", "if", "'code'", "not", "in", "code", ":", "raise", "FlowExchangeError", "(", "code", ".", "get", "(", "'error'", ",", "'No code was supplied in the query parameters.'", ")", ")", "code", "=", "code", "[", "'code'", "]", "post_data", "=", "{", "'client_id'", ":", "self", ".", "client_id", ",", "'code'", ":", "code", ",", "'scope'", ":", "self", ".", "scope", ",", "}", "if", "self", ".", "client_secret", "is", "not", "None", ":", "post_data", "[", "'client_secret'", "]", "=", "self", ".", "client_secret", "if", "self", ".", "_pkce", ":", "post_data", "[", "'code_verifier'", "]", "=", "self", ".", "code_verifier", "if", "device_flow_info", "is", "not", "None", ":", "post_data", "[", "'grant_type'", "]", "=", "'http://oauth.net/grant_type/device/1.0'", "else", ":", "post_data", "[", "'grant_type'", "]", "=", "'authorization_code'", "post_data", "[", "'redirect_uri'", "]", "=", "self", ".", "redirect_uri", "body", "=", "urllib", ".", "parse", ".", "urlencode", "(", "post_data", ")", "headers", "=", "{", "'content-type'", ":", "'application/x-www-form-urlencoded'", ",", "}", "if", "self", ".", "authorization_header", "is", "not", "None", ":", "headers", "[", "'Authorization'", "]", "=", "self", ".", "authorization_header", "if", "self", ".", "user_agent", "is", "not", "None", ":", "headers", "[", "'user-agent'", "]", "=", "self", ".", "user_agent", "if", "http", "is", "None", ":", "http", "=", "transport", ".", "get_http_object", "(", ")", "resp", ",", "content", "=", "transport", ".", "request", "(", "http", ",", "self", ".", "token_uri", ",", "method", "=", "'POST'", ",", "body", "=", "body", ",", "headers", "=", "headers", ")", "d", "=", "_parse_exchange_token_response", "(", "content", ")", "if", "resp", ".", "status", "==", "http_client", ".", "OK", "and", "'access_token'", "in", "d", ":", "access_token", "=", "d", "[", "'access_token'", "]", "refresh_token", "=", "d", ".", "get", "(", "'refresh_token'", ",", "None", ")", "if", "not", "refresh_token", ":", "logger", ".", "info", "(", "'Received token response with no refresh_token. Consider '", "\"reauthenticating with prompt='consent'.\"", ")", "token_expiry", "=", "None", "if", "'expires_in'", "in", "d", ":", "delta", "=", "datetime", ".", "timedelta", "(", "seconds", "=", "int", "(", "d", "[", "'expires_in'", "]", ")", ")", "token_expiry", "=", "delta", "+", "_UTCNOW", "(", ")", "extracted_id_token", "=", "None", "id_token_jwt", "=", "None", "if", "'id_token'", "in", "d", ":", "extracted_id_token", "=", "_extract_id_token", "(", "d", "[", "'id_token'", "]", ")", "id_token_jwt", "=", "d", "[", "'id_token'", "]", "logger", ".", "info", "(", "'Successfully retrieved access token'", ")", "return", "OAuth2Credentials", "(", "access_token", ",", "self", ".", "client_id", ",", "self", ".", "client_secret", ",", "refresh_token", ",", "token_expiry", ",", "self", ".", "token_uri", ",", "self", ".", "user_agent", ",", "revoke_uri", "=", "self", ".", "revoke_uri", ",", "id_token", "=", "extracted_id_token", ",", "id_token_jwt", "=", "id_token_jwt", ",", "token_response", "=", "d", ",", "scopes", "=", "self", ".", "scope", ",", "token_info_uri", "=", "self", ".", "token_info_uri", ")", "else", ":", "logger", ".", "info", "(", "'Failed to retrieve access token: %s'", ",", "content", ")", "if", "'error'", "in", "d", ":", "# you never know what those providers got to say", "error_msg", "=", "(", "str", "(", "d", "[", "'error'", "]", ")", "+", "str", "(", "d", ".", "get", "(", "'error_description'", ",", "''", ")", ")", ")", "else", ":", "error_msg", "=", "'Invalid response: {0}.'", ".", "format", "(", "str", "(", "resp", ".", "status", ")", ")", "raise", "FlowExchangeError", "(", "error_msg", ")" ]
[ 1991, 4 ]
[ 2088, 46 ]
python
en
['en', 'en', 'en']
True
parse_html
(html)
Take a string that contains HTML and turn it into a Python object structure that can be easily compared against other HTML on semantic equivalence. Syntactical differences like which quotation is used on arguments will be ignored.
Take a string that contains HTML and turn it into a Python object structure that can be easily compared against other HTML on semantic equivalence. Syntactical differences like which quotation is used on arguments will be ignored.
def parse_html(html): """ Take a string that contains HTML and turn it into a Python object structure that can be easily compared against other HTML on semantic equivalence. Syntactical differences like which quotation is used on arguments will be ignored. """ parser = Parser() parser.feed(html) parser.close() document = parser.root document.finalize() # Removing ROOT element if it's not necessary if len(document.children) == 1 and not isinstance(document.children[0], str): document = document.children[0] return document
[ "def", "parse_html", "(", "html", ")", ":", "parser", "=", "Parser", "(", ")", "parser", ".", "feed", "(", "html", ")", "parser", ".", "close", "(", ")", "document", "=", "parser", ".", "root", "document", ".", "finalize", "(", ")", "# Removing ROOT element if it's not necessary", "if", "len", "(", "document", ".", "children", ")", "==", "1", "and", "not", "isinstance", "(", "document", ".", "children", "[", "0", "]", ",", "str", ")", ":", "document", "=", "document", ".", "children", "[", "0", "]", "return", "document" ]
[ 225, 0 ]
[ 240, 19 ]
python
en
['en', 'error', 'th']
False
cache_page
(timeout, *, cache=None, key_prefix=None)
Decorator for views that tries getting the page from the cache and populates the cache if the page isn't in the cache yet. The cache is keyed by the URL and some data from the headers. Additionally there is the key prefix that is used to distinguish different cache areas in a multi-site setup. You could use the get_current_site().domain, for example, as that is unique across a Django project. Additionally, all headers from the response's Vary header will be taken into account on caching -- just like the middleware does.
Decorator for views that tries getting the page from the cache and populates the cache if the page isn't in the cache yet.
def cache_page(timeout, *, cache=None, key_prefix=None): """ Decorator for views that tries getting the page from the cache and populates the cache if the page isn't in the cache yet. The cache is keyed by the URL and some data from the headers. Additionally there is the key prefix that is used to distinguish different cache areas in a multi-site setup. You could use the get_current_site().domain, for example, as that is unique across a Django project. Additionally, all headers from the response's Vary header will be taken into account on caching -- just like the middleware does. """ return decorator_from_middleware_with_args(CacheMiddleware)( page_timeout=timeout, cache_alias=cache, key_prefix=key_prefix, )
[ "def", "cache_page", "(", "timeout", ",", "*", ",", "cache", "=", "None", ",", "key_prefix", "=", "None", ")", ":", "return", "decorator_from_middleware_with_args", "(", "CacheMiddleware", ")", "(", "page_timeout", "=", "timeout", ",", "cache_alias", "=", "cache", ",", "key_prefix", "=", "key_prefix", ",", ")" ]
[ 7, 0 ]
[ 23, 5 ]
python
en
['en', 'error', 'th']
False
never_cache
(view_func)
Decorator that adds headers to a response so that it will never be cached.
Decorator that adds headers to a response so that it will never be cached.
def never_cache(view_func): """ Decorator that adds headers to a response so that it will never be cached. """ @wraps(view_func) def _wrapped_view_func(request, *args, **kwargs): response = view_func(request, *args, **kwargs) add_never_cache_headers(response) return response return _wrapped_view_func
[ "def", "never_cache", "(", "view_func", ")", ":", "@", "wraps", "(", "view_func", ")", "def", "_wrapped_view_func", "(", "request", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "response", "=", "view_func", "(", "request", ",", "*", "args", ",", "*", "*", "kwargs", ")", "add_never_cache_headers", "(", "response", ")", "return", "response", "return", "_wrapped_view_func" ]
[ 37, 0 ]
[ 46, 29 ]
python
en
['en', 'error', 'th']
False
blankout
(src, char)
Change every non-whitespace character to the given char. Used in the templatize function.
Change every non-whitespace character to the given char. Used in the templatize function.
def blankout(src, char): """ Change every non-whitespace character to the given char. Used in the templatize function. """ return dot_re.sub(char, src)
[ "def", "blankout", "(", "src", ",", "char", ")", ":", "return", "dot_re", ".", "sub", "(", "char", ",", "src", ")" ]
[ 11, 0 ]
[ 16, 32 ]
python
en
['en', 'error', 'th']
False
templatize
(src, origin=None)
Turn a Django template into something that is understood by xgettext. It does so by translating the Django translation tags into standard gettext function invocations.
Turn a Django template into something that is understood by xgettext. It does so by translating the Django translation tags into standard gettext function invocations.
def templatize(src, origin=None): """ Turn a Django template into something that is understood by xgettext. It does so by translating the Django translation tags into standard gettext function invocations. """ out = StringIO('') message_context = None intrans = False inplural = False trimmed = False singular = [] plural = [] incomment = False comment = [] lineno_comment_map = {} comment_lineno_cache = None # Adding the u prefix allows gettext to recognize the string (#26093). raw_prefix = 'u' def join_tokens(tokens, trim=False): message = ''.join(tokens) if trim: message = trim_whitespace(message) return message for t in Lexer(src).tokenize(): if incomment: if t.token_type == TokenType.BLOCK and t.contents == 'endcomment': content = ''.join(comment) translators_comment_start = None for lineno, line in enumerate(content.splitlines(True)): if line.lstrip().startswith(TRANSLATOR_COMMENT_MARK): translators_comment_start = lineno for lineno, line in enumerate(content.splitlines(True)): if translators_comment_start is not None and lineno >= translators_comment_start: out.write(' # %s' % line) else: out.write(' #\n') incomment = False comment = [] else: comment.append(t.contents) elif intrans: if t.token_type == TokenType.BLOCK: endbmatch = endblock_re.match(t.contents) pluralmatch = plural_re.match(t.contents) if endbmatch: if inplural: if message_context: out.write(' npgettext({p}{!r}, {p}{!r}, {p}{!r},count) '.format( message_context, join_tokens(singular, trimmed), join_tokens(plural, trimmed), p=raw_prefix, )) else: out.write(' ngettext({p}{!r}, {p}{!r}, count) '.format( join_tokens(singular, trimmed), join_tokens(plural, trimmed), p=raw_prefix, )) for part in singular: out.write(blankout(part, 'S')) for part in plural: out.write(blankout(part, 'P')) else: if message_context: out.write(' pgettext({p}{!r}, {p}{!r}) '.format( message_context, join_tokens(singular, trimmed), p=raw_prefix, )) else: out.write(' gettext({p}{!r}) '.format( join_tokens(singular, trimmed), p=raw_prefix, )) for part in singular: out.write(blankout(part, 'S')) message_context = None intrans = False inplural = False singular = [] plural = [] elif pluralmatch: inplural = True else: filemsg = '' if origin: filemsg = 'file %s, ' % origin raise SyntaxError( "Translation blocks must not include other block tags: " "%s (%sline %d)" % (t.contents, filemsg, t.lineno) ) elif t.token_type == TokenType.VAR: if inplural: plural.append('%%(%s)s' % t.contents) else: singular.append('%%(%s)s' % t.contents) elif t.token_type == TokenType.TEXT: contents = t.contents.replace('%', '%%') if inplural: plural.append(contents) else: singular.append(contents) else: # Handle comment tokens (`{# ... #}`) plus other constructs on # the same line: if comment_lineno_cache is not None: cur_lineno = t.lineno + t.contents.count('\n') if comment_lineno_cache == cur_lineno: if t.token_type != TokenType.COMMENT: for c in lineno_comment_map[comment_lineno_cache]: filemsg = '' if origin: filemsg = 'file %s, ' % origin warn_msg = ( "The translator-targeted comment '%s' " "(%sline %d) was ignored, because it wasn't " "the last item on the line." ) % (c, filemsg, comment_lineno_cache) warnings.warn(warn_msg, TranslatorCommentWarning) lineno_comment_map[comment_lineno_cache] = [] else: out.write('# %s' % ' | '.join(lineno_comment_map[comment_lineno_cache])) comment_lineno_cache = None if t.token_type == TokenType.BLOCK: imatch = inline_re.match(t.contents) bmatch = block_re.match(t.contents) cmatches = constant_re.findall(t.contents) if imatch: g = imatch[1] if g[0] == '"': g = g.strip('"') elif g[0] == "'": g = g.strip("'") g = g.replace('%', '%%') if imatch[2]: # A context is provided context_match = context_re.match(imatch[2]) message_context = context_match[1] if message_context[0] == '"': message_context = message_context.strip('"') elif message_context[0] == "'": message_context = message_context.strip("'") out.write(' pgettext({p}{!r}, {p}{!r}) '.format( message_context, g, p=raw_prefix )) message_context = None else: out.write(' gettext({p}{!r}) '.format(g, p=raw_prefix)) elif bmatch: for fmatch in constant_re.findall(t.contents): out.write(' _(%s) ' % fmatch) if bmatch[1]: # A context is provided context_match = context_re.match(bmatch[1]) message_context = context_match[1] if message_context[0] == '"': message_context = message_context.strip('"') elif message_context[0] == "'": message_context = message_context.strip("'") intrans = True inplural = False trimmed = 'trimmed' in t.split_contents() singular = [] plural = [] elif cmatches: for cmatch in cmatches: out.write(' _(%s) ' % cmatch) elif t.contents == 'comment': incomment = True else: out.write(blankout(t.contents, 'B')) elif t.token_type == TokenType.VAR: parts = t.contents.split('|') cmatch = constant_re.match(parts[0]) if cmatch: out.write(' _(%s) ' % cmatch[1]) for p in parts[1:]: if p.find(':_(') >= 0: out.write(' %s ' % p.split(':', 1)[1]) else: out.write(blankout(p, 'F')) elif t.token_type == TokenType.COMMENT: if t.contents.lstrip().startswith(TRANSLATOR_COMMENT_MARK): lineno_comment_map.setdefault(t.lineno, []).append(t.contents) comment_lineno_cache = t.lineno else: out.write(blankout(t.contents, 'X')) return out.getvalue()
[ "def", "templatize", "(", "src", ",", "origin", "=", "None", ")", ":", "out", "=", "StringIO", "(", "''", ")", "message_context", "=", "None", "intrans", "=", "False", "inplural", "=", "False", "trimmed", "=", "False", "singular", "=", "[", "]", "plural", "=", "[", "]", "incomment", "=", "False", "comment", "=", "[", "]", "lineno_comment_map", "=", "{", "}", "comment_lineno_cache", "=", "None", "# Adding the u prefix allows gettext to recognize the string (#26093).", "raw_prefix", "=", "'u'", "def", "join_tokens", "(", "tokens", ",", "trim", "=", "False", ")", ":", "message", "=", "''", ".", "join", "(", "tokens", ")", "if", "trim", ":", "message", "=", "trim_whitespace", "(", "message", ")", "return", "message", "for", "t", "in", "Lexer", "(", "src", ")", ".", "tokenize", "(", ")", ":", "if", "incomment", ":", "if", "t", ".", "token_type", "==", "TokenType", ".", "BLOCK", "and", "t", ".", "contents", "==", "'endcomment'", ":", "content", "=", "''", ".", "join", "(", "comment", ")", "translators_comment_start", "=", "None", "for", "lineno", ",", "line", "in", "enumerate", "(", "content", ".", "splitlines", "(", "True", ")", ")", ":", "if", "line", ".", "lstrip", "(", ")", ".", "startswith", "(", "TRANSLATOR_COMMENT_MARK", ")", ":", "translators_comment_start", "=", "lineno", "for", "lineno", ",", "line", "in", "enumerate", "(", "content", ".", "splitlines", "(", "True", ")", ")", ":", "if", "translators_comment_start", "is", "not", "None", "and", "lineno", ">=", "translators_comment_start", ":", "out", ".", "write", "(", "' # %s'", "%", "line", ")", "else", ":", "out", ".", "write", "(", "' #\\n'", ")", "incomment", "=", "False", "comment", "=", "[", "]", "else", ":", "comment", ".", "append", "(", "t", ".", "contents", ")", "elif", "intrans", ":", "if", "t", ".", "token_type", "==", "TokenType", ".", "BLOCK", ":", "endbmatch", "=", "endblock_re", ".", "match", "(", "t", ".", "contents", ")", "pluralmatch", "=", "plural_re", ".", "match", "(", "t", ".", "contents", ")", "if", "endbmatch", ":", "if", "inplural", ":", "if", "message_context", ":", "out", ".", "write", "(", "' npgettext({p}{!r}, {p}{!r}, {p}{!r},count) '", ".", "format", "(", "message_context", ",", "join_tokens", "(", "singular", ",", "trimmed", ")", ",", "join_tokens", "(", "plural", ",", "trimmed", ")", ",", "p", "=", "raw_prefix", ",", ")", ")", "else", ":", "out", ".", "write", "(", "' ngettext({p}{!r}, {p}{!r}, count) '", ".", "format", "(", "join_tokens", "(", "singular", ",", "trimmed", ")", ",", "join_tokens", "(", "plural", ",", "trimmed", ")", ",", "p", "=", "raw_prefix", ",", ")", ")", "for", "part", "in", "singular", ":", "out", ".", "write", "(", "blankout", "(", "part", ",", "'S'", ")", ")", "for", "part", "in", "plural", ":", "out", ".", "write", "(", "blankout", "(", "part", ",", "'P'", ")", ")", "else", ":", "if", "message_context", ":", "out", ".", "write", "(", "' pgettext({p}{!r}, {p}{!r}) '", ".", "format", "(", "message_context", ",", "join_tokens", "(", "singular", ",", "trimmed", ")", ",", "p", "=", "raw_prefix", ",", ")", ")", "else", ":", "out", ".", "write", "(", "' gettext({p}{!r}) '", ".", "format", "(", "join_tokens", "(", "singular", ",", "trimmed", ")", ",", "p", "=", "raw_prefix", ",", ")", ")", "for", "part", "in", "singular", ":", "out", ".", "write", "(", "blankout", "(", "part", ",", "'S'", ")", ")", "message_context", "=", "None", "intrans", "=", "False", "inplural", "=", "False", "singular", "=", "[", "]", "plural", "=", "[", "]", "elif", "pluralmatch", ":", "inplural", "=", "True", "else", ":", "filemsg", "=", "''", "if", "origin", ":", "filemsg", "=", "'file %s, '", "%", "origin", "raise", "SyntaxError", "(", "\"Translation blocks must not include other block tags: \"", "\"%s (%sline %d)\"", "%", "(", "t", ".", "contents", ",", "filemsg", ",", "t", ".", "lineno", ")", ")", "elif", "t", ".", "token_type", "==", "TokenType", ".", "VAR", ":", "if", "inplural", ":", "plural", ".", "append", "(", "'%%(%s)s'", "%", "t", ".", "contents", ")", "else", ":", "singular", ".", "append", "(", "'%%(%s)s'", "%", "t", ".", "contents", ")", "elif", "t", ".", "token_type", "==", "TokenType", ".", "TEXT", ":", "contents", "=", "t", ".", "contents", ".", "replace", "(", "'%'", ",", "'%%'", ")", "if", "inplural", ":", "plural", ".", "append", "(", "contents", ")", "else", ":", "singular", ".", "append", "(", "contents", ")", "else", ":", "# Handle comment tokens (`{# ... #}`) plus other constructs on", "# the same line:", "if", "comment_lineno_cache", "is", "not", "None", ":", "cur_lineno", "=", "t", ".", "lineno", "+", "t", ".", "contents", ".", "count", "(", "'\\n'", ")", "if", "comment_lineno_cache", "==", "cur_lineno", ":", "if", "t", ".", "token_type", "!=", "TokenType", ".", "COMMENT", ":", "for", "c", "in", "lineno_comment_map", "[", "comment_lineno_cache", "]", ":", "filemsg", "=", "''", "if", "origin", ":", "filemsg", "=", "'file %s, '", "%", "origin", "warn_msg", "=", "(", "\"The translator-targeted comment '%s' \"", "\"(%sline %d) was ignored, because it wasn't \"", "\"the last item on the line.\"", ")", "%", "(", "c", ",", "filemsg", ",", "comment_lineno_cache", ")", "warnings", ".", "warn", "(", "warn_msg", ",", "TranslatorCommentWarning", ")", "lineno_comment_map", "[", "comment_lineno_cache", "]", "=", "[", "]", "else", ":", "out", ".", "write", "(", "'# %s'", "%", "' | '", ".", "join", "(", "lineno_comment_map", "[", "comment_lineno_cache", "]", ")", ")", "comment_lineno_cache", "=", "None", "if", "t", ".", "token_type", "==", "TokenType", ".", "BLOCK", ":", "imatch", "=", "inline_re", ".", "match", "(", "t", ".", "contents", ")", "bmatch", "=", "block_re", ".", "match", "(", "t", ".", "contents", ")", "cmatches", "=", "constant_re", ".", "findall", "(", "t", ".", "contents", ")", "if", "imatch", ":", "g", "=", "imatch", "[", "1", "]", "if", "g", "[", "0", "]", "==", "'\"'", ":", "g", "=", "g", ".", "strip", "(", "'\"'", ")", "elif", "g", "[", "0", "]", "==", "\"'\"", ":", "g", "=", "g", ".", "strip", "(", "\"'\"", ")", "g", "=", "g", ".", "replace", "(", "'%'", ",", "'%%'", ")", "if", "imatch", "[", "2", "]", ":", "# A context is provided", "context_match", "=", "context_re", ".", "match", "(", "imatch", "[", "2", "]", ")", "message_context", "=", "context_match", "[", "1", "]", "if", "message_context", "[", "0", "]", "==", "'\"'", ":", "message_context", "=", "message_context", ".", "strip", "(", "'\"'", ")", "elif", "message_context", "[", "0", "]", "==", "\"'\"", ":", "message_context", "=", "message_context", ".", "strip", "(", "\"'\"", ")", "out", ".", "write", "(", "' pgettext({p}{!r}, {p}{!r}) '", ".", "format", "(", "message_context", ",", "g", ",", "p", "=", "raw_prefix", ")", ")", "message_context", "=", "None", "else", ":", "out", ".", "write", "(", "' gettext({p}{!r}) '", ".", "format", "(", "g", ",", "p", "=", "raw_prefix", ")", ")", "elif", "bmatch", ":", "for", "fmatch", "in", "constant_re", ".", "findall", "(", "t", ".", "contents", ")", ":", "out", ".", "write", "(", "' _(%s) '", "%", "fmatch", ")", "if", "bmatch", "[", "1", "]", ":", "# A context is provided", "context_match", "=", "context_re", ".", "match", "(", "bmatch", "[", "1", "]", ")", "message_context", "=", "context_match", "[", "1", "]", "if", "message_context", "[", "0", "]", "==", "'\"'", ":", "message_context", "=", "message_context", ".", "strip", "(", "'\"'", ")", "elif", "message_context", "[", "0", "]", "==", "\"'\"", ":", "message_context", "=", "message_context", ".", "strip", "(", "\"'\"", ")", "intrans", "=", "True", "inplural", "=", "False", "trimmed", "=", "'trimmed'", "in", "t", ".", "split_contents", "(", ")", "singular", "=", "[", "]", "plural", "=", "[", "]", "elif", "cmatches", ":", "for", "cmatch", "in", "cmatches", ":", "out", ".", "write", "(", "' _(%s) '", "%", "cmatch", ")", "elif", "t", ".", "contents", "==", "'comment'", ":", "incomment", "=", "True", "else", ":", "out", ".", "write", "(", "blankout", "(", "t", ".", "contents", ",", "'B'", ")", ")", "elif", "t", ".", "token_type", "==", "TokenType", ".", "VAR", ":", "parts", "=", "t", ".", "contents", ".", "split", "(", "'|'", ")", "cmatch", "=", "constant_re", ".", "match", "(", "parts", "[", "0", "]", ")", "if", "cmatch", ":", "out", ".", "write", "(", "' _(%s) '", "%", "cmatch", "[", "1", "]", ")", "for", "p", "in", "parts", "[", "1", ":", "]", ":", "if", "p", ".", "find", "(", "':_('", ")", ">=", "0", ":", "out", ".", "write", "(", "' %s '", "%", "p", ".", "split", "(", "':'", ",", "1", ")", "[", "1", "]", ")", "else", ":", "out", ".", "write", "(", "blankout", "(", "p", ",", "'F'", ")", ")", "elif", "t", ".", "token_type", "==", "TokenType", ".", "COMMENT", ":", "if", "t", ".", "contents", ".", "lstrip", "(", ")", ".", "startswith", "(", "TRANSLATOR_COMMENT_MARK", ")", ":", "lineno_comment_map", ".", "setdefault", "(", "t", ".", "lineno", ",", "[", "]", ")", ".", "append", "(", "t", ".", "contents", ")", "comment_lineno_cache", "=", "t", ".", "lineno", "else", ":", "out", ".", "write", "(", "blankout", "(", "t", ".", "contents", ",", "'X'", ")", ")", "return", "out", ".", "getvalue", "(", ")" ]
[ 34, 0 ]
[ 226, 25 ]
python
en
['en', 'error', 'th']
False
get_fixed_timezone
(offset)
Return a tzinfo instance with a fixed offset from UTC.
Return a tzinfo instance with a fixed offset from UTC.
def get_fixed_timezone(offset): """Return a tzinfo instance with a fixed offset from UTC.""" if isinstance(offset, timedelta): offset = offset.total_seconds() // 60 sign = '-' if offset < 0 else '+' hhmm = '%02d%02d' % divmod(abs(offset), 60) name = sign + hhmm return timezone(timedelta(minutes=offset), name)
[ "def", "get_fixed_timezone", "(", "offset", ")", ":", "if", "isinstance", "(", "offset", ",", "timedelta", ")", ":", "offset", "=", "offset", ".", "total_seconds", "(", ")", "//", "60", "sign", "=", "'-'", "if", "offset", "<", "0", "else", "'+'", "hhmm", "=", "'%02d%02d'", "%", "divmod", "(", "abs", "(", "offset", ")", ",", "60", ")", "name", "=", "sign", "+", "hhmm", "return", "timezone", "(", "timedelta", "(", "minutes", "=", "offset", ")", ",", "name", ")" ]
[ 32, 0 ]
[ 39, 52 ]
python
en
['en', 'en', 'en']
True
get_default_timezone
()
Return the default time zone as a tzinfo instance. This is the time zone defined by settings.TIME_ZONE.
Return the default time zone as a tzinfo instance.
def get_default_timezone(): """ Return the default time zone as a tzinfo instance. This is the time zone defined by settings.TIME_ZONE. """ return pytz.timezone(settings.TIME_ZONE)
[ "def", "get_default_timezone", "(", ")", ":", "return", "pytz", ".", "timezone", "(", "settings", ".", "TIME_ZONE", ")" ]
[ 45, 0 ]
[ 51, 44 ]
python
en
['en', 'error', 'th']
False
get_default_timezone_name
()
Return the name of the default time zone.
Return the name of the default time zone.
def get_default_timezone_name(): """Return the name of the default time zone.""" return _get_timezone_name(get_default_timezone())
[ "def", "get_default_timezone_name", "(", ")", ":", "return", "_get_timezone_name", "(", "get_default_timezone", "(", ")", ")" ]
[ 55, 0 ]
[ 57, 53 ]
python
en
['en', 'en', 'en']
True
get_current_timezone
()
Return the currently active time zone as a tzinfo instance.
Return the currently active time zone as a tzinfo instance.
def get_current_timezone(): """Return the currently active time zone as a tzinfo instance.""" return getattr(_active, "value", get_default_timezone())
[ "def", "get_current_timezone", "(", ")", ":", "return", "getattr", "(", "_active", ",", "\"value\"", ",", "get_default_timezone", "(", ")", ")" ]
[ 63, 0 ]
[ 65, 60 ]
python
en
['en', 'en', 'en']
True
get_current_timezone_name
()
Return the name of the currently active time zone.
Return the name of the currently active time zone.
def get_current_timezone_name(): """Return the name of the currently active time zone.""" return _get_timezone_name(get_current_timezone())
[ "def", "get_current_timezone_name", "(", ")", ":", "return", "_get_timezone_name", "(", "get_current_timezone", "(", ")", ")" ]
[ 68, 0 ]
[ 70, 53 ]
python
en
['en', 'en', 'en']
True
_get_timezone_name
(timezone)
Return the offset for fixed offset timezones, or the name of timezone if not set.
Return the offset for fixed offset timezones, or the name of timezone if not set.
def _get_timezone_name(timezone): """ Return the offset for fixed offset timezones, or the name of timezone if not set. """ return timezone.tzname(None) or str(timezone)
[ "def", "_get_timezone_name", "(", "timezone", ")", ":", "return", "timezone", ".", "tzname", "(", "None", ")", "or", "str", "(", "timezone", ")" ]
[ 73, 0 ]
[ 78, 49 ]
python
en
['en', 'error', 'th']
False
activate
(timezone)
Set the time zone for the current thread. The ``timezone`` argument must be an instance of a tzinfo subclass or a time zone name.
Set the time zone for the current thread.
def activate(timezone): """ Set the time zone for the current thread. The ``timezone`` argument must be an instance of a tzinfo subclass or a time zone name. """ if isinstance(timezone, tzinfo): _active.value = timezone elif isinstance(timezone, str): _active.value = pytz.timezone(timezone) else: raise ValueError("Invalid timezone: %r" % timezone)
[ "def", "activate", "(", "timezone", ")", ":", "if", "isinstance", "(", "timezone", ",", "tzinfo", ")", ":", "_active", ".", "value", "=", "timezone", "elif", "isinstance", "(", "timezone", ",", "str", ")", ":", "_active", ".", "value", "=", "pytz", ".", "timezone", "(", "timezone", ")", "else", ":", "raise", "ValueError", "(", "\"Invalid timezone: %r\"", "%", "timezone", ")" ]
[ 86, 0 ]
[ 98, 59 ]
python
en
['en', 'error', 'th']
False
deactivate
()
Unset the time zone for the current thread. Django will then use the time zone defined by settings.TIME_ZONE.
Unset the time zone for the current thread.
def deactivate(): """ Unset the time zone for the current thread. Django will then use the time zone defined by settings.TIME_ZONE. """ if hasattr(_active, "value"): del _active.value
[ "def", "deactivate", "(", ")", ":", "if", "hasattr", "(", "_active", ",", "\"value\"", ")", ":", "del", "_active", ".", "value" ]
[ 101, 0 ]
[ 108, 25 ]
python
en
['en', 'error', 'th']
False
template_localtime
(value, use_tz=None)
Check if value is a datetime and converts it to local time if necessary. If use_tz is provided and is not None, that will force the value to be converted (or not), overriding the value of settings.USE_TZ. This function is designed for use by the template engine.
Check if value is a datetime and converts it to local time if necessary.
def template_localtime(value, use_tz=None): """ Check if value is a datetime and converts it to local time if necessary. If use_tz is provided and is not None, that will force the value to be converted (or not), overriding the value of settings.USE_TZ. This function is designed for use by the template engine. """ should_convert = ( isinstance(value, datetime) and (settings.USE_TZ if use_tz is None else use_tz) and not is_naive(value) and getattr(value, 'convert_to_local_time', True) ) return localtime(value) if should_convert else value
[ "def", "template_localtime", "(", "value", ",", "use_tz", "=", "None", ")", ":", "should_convert", "=", "(", "isinstance", "(", "value", ",", "datetime", ")", "and", "(", "settings", ".", "USE_TZ", "if", "use_tz", "is", "None", "else", "use_tz", ")", "and", "not", "is_naive", "(", "value", ")", "and", "getattr", "(", "value", ",", "'convert_to_local_time'", ",", "True", ")", ")", "return", "localtime", "(", "value", ")", "if", "should_convert", "else", "value" ]
[ 142, 0 ]
[ 157, 56 ]
python
en
['en', 'error', 'th']
False
localtime
(value=None, timezone=None)
Convert an aware datetime.datetime to local time. Only aware datetimes are allowed. When value is omitted, it defaults to now(). Local time is defined by the current time zone, unless another time zone is specified.
Convert an aware datetime.datetime to local time.
def localtime(value=None, timezone=None): """ Convert an aware datetime.datetime to local time. Only aware datetimes are allowed. When value is omitted, it defaults to now(). Local time is defined by the current time zone, unless another time zone is specified. """ if value is None: value = now() if timezone is None: timezone = get_current_timezone() # Emulate the behavior of astimezone() on Python < 3.6. if is_naive(value): raise ValueError("localtime() cannot be applied to a naive datetime") return value.astimezone(timezone)
[ "def", "localtime", "(", "value", "=", "None", ",", "timezone", "=", "None", ")", ":", "if", "value", "is", "None", ":", "value", "=", "now", "(", ")", "if", "timezone", "is", "None", ":", "timezone", "=", "get_current_timezone", "(", ")", "# Emulate the behavior of astimezone() on Python < 3.6.", "if", "is_naive", "(", "value", ")", ":", "raise", "ValueError", "(", "\"localtime() cannot be applied to a naive datetime\"", ")", "return", "value", ".", "astimezone", "(", "timezone", ")" ]
[ 162, 0 ]
[ 179, 37 ]
python
en
['en', 'error', 'th']
False
localdate
(value=None, timezone=None)
Convert an aware datetime to local time and return the value's date. Only aware datetimes are allowed. When value is omitted, it defaults to now(). Local time is defined by the current time zone, unless another time zone is specified.
Convert an aware datetime to local time and return the value's date.
def localdate(value=None, timezone=None): """ Convert an aware datetime to local time and return the value's date. Only aware datetimes are allowed. When value is omitted, it defaults to now(). Local time is defined by the current time zone, unless another time zone is specified. """ return localtime(value, timezone).date()
[ "def", "localdate", "(", "value", "=", "None", ",", "timezone", "=", "None", ")", ":", "return", "localtime", "(", "value", ",", "timezone", ")", ".", "date", "(", ")" ]
[ 182, 0 ]
[ 192, 44 ]
python
en
['en', 'error', 'th']
False
now
()
Return an aware or naive datetime.datetime, depending on settings.USE_TZ.
Return an aware or naive datetime.datetime, depending on settings.USE_TZ.
def now(): """ Return an aware or naive datetime.datetime, depending on settings.USE_TZ. """ if settings.USE_TZ: # timeit shows that datetime.now(tz=utc) is 24% slower return datetime.utcnow().replace(tzinfo=utc) else: return datetime.now()
[ "def", "now", "(", ")", ":", "if", "settings", ".", "USE_TZ", ":", "# timeit shows that datetime.now(tz=utc) is 24% slower", "return", "datetime", ".", "utcnow", "(", ")", ".", "replace", "(", "tzinfo", "=", "utc", ")", "else", ":", "return", "datetime", ".", "now", "(", ")" ]
[ 195, 0 ]
[ 203, 29 ]
python
en
['en', 'error', 'th']
False
is_aware
(value)
Determine if a given datetime.datetime is aware. The concept is defined in Python's docs: https://docs.python.org/library/datetime.html#datetime.tzinfo Assuming value.tzinfo is either None or a proper datetime.tzinfo, value.utcoffset() implements the appropriate logic.
Determine if a given datetime.datetime is aware.
def is_aware(value): """ Determine if a given datetime.datetime is aware. The concept is defined in Python's docs: https://docs.python.org/library/datetime.html#datetime.tzinfo Assuming value.tzinfo is either None or a proper datetime.tzinfo, value.utcoffset() implements the appropriate logic. """ return value.utcoffset() is not None
[ "def", "is_aware", "(", "value", ")", ":", "return", "value", ".", "utcoffset", "(", ")", "is", "not", "None" ]
[ 209, 0 ]
[ 219, 40 ]
python
en
['en', 'error', 'th']
False
is_naive
(value)
Determine if a given datetime.datetime is naive. The concept is defined in Python's docs: https://docs.python.org/library/datetime.html#datetime.tzinfo Assuming value.tzinfo is either None or a proper datetime.tzinfo, value.utcoffset() implements the appropriate logic.
Determine if a given datetime.datetime is naive.
def is_naive(value): """ Determine if a given datetime.datetime is naive. The concept is defined in Python's docs: https://docs.python.org/library/datetime.html#datetime.tzinfo Assuming value.tzinfo is either None or a proper datetime.tzinfo, value.utcoffset() implements the appropriate logic. """ return value.utcoffset() is None
[ "def", "is_naive", "(", "value", ")", ":", "return", "value", ".", "utcoffset", "(", ")", "is", "None" ]
[ 222, 0 ]
[ 232, 36 ]
python
en
['en', 'error', 'th']
False
make_aware
(value, timezone=None, is_dst=None)
Make a naive datetime.datetime in a given time zone aware.
Make a naive datetime.datetime in a given time zone aware.
def make_aware(value, timezone=None, is_dst=None): """Make a naive datetime.datetime in a given time zone aware.""" if timezone is None: timezone = get_current_timezone() if _is_pytz_zone(timezone): # This method is available for pytz time zones. return timezone.localize(value, is_dst=is_dst) else: # Check that we won't overwrite the timezone of an aware datetime. if is_aware(value): raise ValueError( "make_aware expects a naive datetime, got %s" % value) # This may be wrong around DST changes! return value.replace(tzinfo=timezone)
[ "def", "make_aware", "(", "value", ",", "timezone", "=", "None", ",", "is_dst", "=", "None", ")", ":", "if", "timezone", "is", "None", ":", "timezone", "=", "get_current_timezone", "(", ")", "if", "_is_pytz_zone", "(", "timezone", ")", ":", "# This method is available for pytz time zones.", "return", "timezone", ".", "localize", "(", "value", ",", "is_dst", "=", "is_dst", ")", "else", ":", "# Check that we won't overwrite the timezone of an aware datetime.", "if", "is_aware", "(", "value", ")", ":", "raise", "ValueError", "(", "\"make_aware expects a naive datetime, got %s\"", "%", "value", ")", "# This may be wrong around DST changes!", "return", "value", ".", "replace", "(", "tzinfo", "=", "timezone", ")" ]
[ 235, 0 ]
[ 248, 45 ]
python
en
['en', 'en', 'en']
True
make_naive
(value, timezone=None)
Make an aware datetime.datetime naive in a given time zone.
Make an aware datetime.datetime naive in a given time zone.
def make_naive(value, timezone=None): """Make an aware datetime.datetime naive in a given time zone.""" if timezone is None: timezone = get_current_timezone() # Emulate the behavior of astimezone() on Python < 3.6. if is_naive(value): raise ValueError("make_naive() cannot be applied to a naive datetime") return value.astimezone(timezone).replace(tzinfo=None)
[ "def", "make_naive", "(", "value", ",", "timezone", "=", "None", ")", ":", "if", "timezone", "is", "None", ":", "timezone", "=", "get_current_timezone", "(", ")", "# Emulate the behavior of astimezone() on Python < 3.6.", "if", "is_naive", "(", "value", ")", ":", "raise", "ValueError", "(", "\"make_naive() cannot be applied to a naive datetime\"", ")", "return", "value", ".", "astimezone", "(", "timezone", ")", ".", "replace", "(", "tzinfo", "=", "None", ")" ]
[ 251, 0 ]
[ 258, 58 ]
python
en
['en', 'en', 'en']
True
_is_pytz_zone
(tz)
Checks if a zone is a pytz zone.
Checks if a zone is a pytz zone.
def _is_pytz_zone(tz): """Checks if a zone is a pytz zone.""" return isinstance(tz, _PYTZ_BASE_CLASSES)
[ "def", "_is_pytz_zone", "(", "tz", ")", ":", "return", "isinstance", "(", "tz", ",", "_PYTZ_BASE_CLASSES", ")" ]
[ 261, 0 ]
[ 263, 45 ]
python
en
['en', 'en', 'en']
True
pkcs12_key_as_pem
(private_key_bytes, private_key_password)
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``.
Convert the contents of a PKCS#12 key to PEM using pyOpenSSL.
def pkcs12_key_as_pem(private_key_bytes, private_key_password): """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``. """ 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())
[ "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", "(", ")", ")" ]
[ 122, 0 ]
[ 135, 58 ]
python
en
['en', 'fr', 'en']
True
OpenSSLVerifier.__init__
(self, pubkey)
Constructor. Args: pubkey: OpenSSL.crypto.PKey, The public key to verify with.
Constructor.
def __init__(self, pubkey): """Constructor. Args: pubkey: OpenSSL.crypto.PKey, The public key to verify with. """ self._pubkey = pubkey
[ "def", "__init__", "(", "self", ",", "pubkey", ")", ":", "self", ".", "_pubkey", "=", "pubkey" ]
[ 23, 4 ]
[ 29, 29 ]
python
en
['en', 'en', 'en']
False
OpenSSLVerifier.verify
(self, message, signature)
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.
Verifies a message against a signature.
def verify(self, message, signature): """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. """ 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
[ "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" ]
[ 31, 4 ]
[ 50, 24 ]
python
en
['en', 'fr', 'en']
True
OpenSSLVerifier.from_string
(key_pem, is_x509_cert)
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.
Construct a Verified instance from a string.
def from_string(key_pem, is_x509_cert): """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. """ 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)
[ "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", ")" ]
[ 53, 4 ]
[ 72, 38 ]
python
en
['en', 'en', 'en']
True
OpenSSLSigner.__init__
(self, pkey)
Constructor. Args: pkey: OpenSSL.crypto.PKey (or equiv), The private key to sign with.
Constructor.
def __init__(self, pkey): """Constructor. Args: pkey: OpenSSL.crypto.PKey (or equiv), The private key to sign with. """ self._key = pkey
[ "def", "__init__", "(", "self", ",", "pkey", ")", ":", "self", ".", "_key", "=", "pkey" ]
[ 78, 4 ]
[ 84, 24 ]
python
en
['en', 'en', 'en']
False
OpenSSLSigner.sign
(self, message)
Signs a message. Args: message: bytes, Message to be signed. Returns: string, The signature of the message for the given key.
Signs a message.
def sign(self, message): """Signs a message. Args: message: bytes, Message to be signed. Returns: string, The signature of the message for the given key. """ message = _helpers._to_bytes(message, encoding='utf-8') return crypto.sign(self._key, message, 'sha256')
[ "def", "sign", "(", "self", ",", "message", ")", ":", "message", "=", "_helpers", ".", "_to_bytes", "(", "message", ",", "encoding", "=", "'utf-8'", ")", "return", "crypto", ".", "sign", "(", "self", ".", "_key", ",", "message", ",", "'sha256'", ")" ]
[ 86, 4 ]
[ 96, 56 ]
python
en
['en', 'en', 'en']
True
OpenSSLSigner.from_string
(key, password=b'notasecret')
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.
Construct a Signer instance from a string.
def from_string(key, password=b'notasecret'): """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. """ 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)
[ "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", ")" ]
[ 99, 4 ]
[ 119, 34 ]
python
en
['en', 'en', 'en']
True
uninstall_if_needed
(setting, value, enter, **kwargs)
Undo the effects of PostgresConfig.ready() when django.contrib.postgres is "uninstalled" by override_settings().
Undo the effects of PostgresConfig.ready() when django.contrib.postgres is "uninstalled" by override_settings().
def uninstall_if_needed(setting, value, enter, **kwargs): """ Undo the effects of PostgresConfig.ready() when django.contrib.postgres is "uninstalled" by override_settings(). """ if not enter and setting == 'INSTALLED_APPS' and 'django.contrib.postgres' not in set(value): connection_created.disconnect(register_type_handlers) CharField._unregister_lookup(Unaccent) TextField._unregister_lookup(Unaccent) CharField._unregister_lookup(SearchLookup) TextField._unregister_lookup(SearchLookup) CharField._unregister_lookup(TrigramSimilar) TextField._unregister_lookup(TrigramSimilar) # Disconnect this receiver until the next time this app is installed # and ready() connects it again to prevent unnecessary processing on # each setting change. setting_changed.disconnect(uninstall_if_needed) MigrationWriter.unregister_serializer(RANGE_TYPES)
[ "def", "uninstall_if_needed", "(", "setting", ",", "value", ",", "enter", ",", "*", "*", "kwargs", ")", ":", "if", "not", "enter", "and", "setting", "==", "'INSTALLED_APPS'", "and", "'django.contrib.postgres'", "not", "in", "set", "(", "value", ")", ":", "connection_created", ".", "disconnect", "(", "register_type_handlers", ")", "CharField", ".", "_unregister_lookup", "(", "Unaccent", ")", "TextField", ".", "_unregister_lookup", "(", "Unaccent", ")", "CharField", ".", "_unregister_lookup", "(", "SearchLookup", ")", "TextField", ".", "_unregister_lookup", "(", "SearchLookup", ")", "CharField", ".", "_unregister_lookup", "(", "TrigramSimilar", ")", "TextField", ".", "_unregister_lookup", "(", "TrigramSimilar", ")", "# Disconnect this receiver until the next time this app is installed", "# and ready() connects it again to prevent unnecessary processing on", "# each setting change.", "setting_changed", ".", "disconnect", "(", "uninstall_if_needed", ")", "MigrationWriter", ".", "unregister_serializer", "(", "RANGE_TYPES", ")" ]
[ 22, 0 ]
[ 39, 58 ]
python
en
['en', 'error', 'th']
False
CommandQueue.flush
(self)
Flushes out the queue by setting the property to an empty list :return:
Flushes out the queue by setting the property to an empty list :return:
def flush(self) -> None: """ Flushes out the queue by setting the property to an empty list :return: """ self.queue = list()
[ "def", "flush", "(", "self", ")", "->", "None", ":", "self", ".", "queue", "=", "list", "(", ")" ]
[ 62, 4 ]
[ 67, 27 ]
python
en
['en', 'error', 'th']
False
CommandQueue.__len__
(self)
:return: int length of self.queue
:return: int length of self.queue
def __len__(self) -> int: """ :return: int length of self.queue """ return len(self.queue)
[ "def", "__len__", "(", "self", ")", "->", "int", ":", "return", "len", "(", "self", ".", "queue", ")" ]
[ 69, 4 ]
[ 73, 30 ]
python
en
['en', 'error', 'th']
False
register_serializer
(format, serializer_module, serializers=None)
Register a new serializer. ``serializer_module`` should be the fully qualified module name for the serializer. If ``serializers`` is provided, the registration will be added to the provided dictionary. If ``serializers`` is not provided, the registration will be made directly into the global register of serializers. Adding serializers directly is not a thread-safe operation.
Register a new serializer.
def register_serializer(format, serializer_module, serializers=None): """Register a new serializer. ``serializer_module`` should be the fully qualified module name for the serializer. If ``serializers`` is provided, the registration will be added to the provided dictionary. If ``serializers`` is not provided, the registration will be made directly into the global register of serializers. Adding serializers directly is not a thread-safe operation. """ if serializers is None and not _serializers: _load_serializers() try: module = importlib.import_module(serializer_module) except ImportError as exc: bad_serializer = BadSerializer(exc) module = type('BadSerializerModule', (), { 'Deserializer': bad_serializer, 'Serializer': bad_serializer, }) if serializers is None: _serializers[format] = module else: serializers[format] = module
[ "def", "register_serializer", "(", "format", ",", "serializer_module", ",", "serializers", "=", "None", ")", ":", "if", "serializers", "is", "None", "and", "not", "_serializers", ":", "_load_serializers", "(", ")", "try", ":", "module", "=", "importlib", ".", "import_module", "(", "serializer_module", ")", "except", "ImportError", "as", "exc", ":", "bad_serializer", "=", "BadSerializer", "(", "exc", ")", "module", "=", "type", "(", "'BadSerializerModule'", ",", "(", ")", ",", "{", "'Deserializer'", ":", "bad_serializer", ",", "'Serializer'", ":", "bad_serializer", ",", "}", ")", "if", "serializers", "is", "None", ":", "_serializers", "[", "format", "]", "=", "module", "else", ":", "serializers", "[", "format", "]", "=", "module" ]
[ 53, 0 ]
[ 82, 36 ]
python
en
['en', 'en', 'en']
True
unregister_serializer
(format)
Unregister a given serializer. This is not a thread-safe operation.
Unregister a given serializer. This is not a thread-safe operation.
def unregister_serializer(format): "Unregister a given serializer. This is not a thread-safe operation." if not _serializers: _load_serializers() if format not in _serializers: raise SerializerDoesNotExist(format) del _serializers[format]
[ "def", "unregister_serializer", "(", "format", ")", ":", "if", "not", "_serializers", ":", "_load_serializers", "(", ")", "if", "format", "not", "in", "_serializers", ":", "raise", "SerializerDoesNotExist", "(", "format", ")", "del", "_serializers", "[", "format", "]" ]
[ 85, 0 ]
[ 91, 28 ]
python
en
['en', 'en', 'en']
True
serialize
(format, queryset, **options)
Serialize a queryset (or any iterator that returns database objects) using a certain serializer.
Serialize a queryset (or any iterator that returns database objects) using a certain serializer.
def serialize(format, queryset, **options): """ Serialize a queryset (or any iterator that returns database objects) using a certain serializer. """ s = get_serializer(format)() s.serialize(queryset, **options) return s.getvalue()
[ "def", "serialize", "(", "format", ",", "queryset", ",", "*", "*", "options", ")", ":", "s", "=", "get_serializer", "(", "format", ")", "(", ")", "s", ".", "serialize", "(", "queryset", ",", "*", "*", "options", ")", "return", "s", ".", "getvalue", "(", ")" ]
[ 122, 0 ]
[ 129, 23 ]
python
en
['en', 'error', 'th']
False
deserialize
(format, stream_or_string, **options)
Deserialize a stream or a string. Return an iterator that yields ``(obj, m2m_relation_dict)``, where ``obj`` is an instantiated -- but *unsaved* -- object, and ``m2m_relation_dict`` is a dictionary of ``{m2m_field_name : list_of_related_objects}``.
Deserialize a stream or a string. Return an iterator that yields ``(obj, m2m_relation_dict)``, where ``obj`` is an instantiated -- but *unsaved* -- object, and ``m2m_relation_dict`` is a dictionary of ``{m2m_field_name : list_of_related_objects}``.
def deserialize(format, stream_or_string, **options): """ Deserialize a stream or a string. Return an iterator that yields ``(obj, m2m_relation_dict)``, where ``obj`` is an instantiated -- but *unsaved* -- object, and ``m2m_relation_dict`` is a dictionary of ``{m2m_field_name : list_of_related_objects}``. """ d = get_deserializer(format) return d(stream_or_string, **options)
[ "def", "deserialize", "(", "format", ",", "stream_or_string", ",", "*", "*", "options", ")", ":", "d", "=", "get_deserializer", "(", "format", ")", "return", "d", "(", "stream_or_string", ",", "*", "*", "options", ")" ]
[ 132, 0 ]
[ 140, 41 ]
python
en
['en', 'error', 'th']
False
_load_serializers
()
Register built-in and settings-defined serializers. This is done lazily so that user code has a chance to (e.g.) set up custom settings without needing to be careful of import order.
Register built-in and settings-defined serializers. This is done lazily so that user code has a chance to (e.g.) set up custom settings without needing to be careful of import order.
def _load_serializers(): """ Register built-in and settings-defined serializers. This is done lazily so that user code has a chance to (e.g.) set up custom settings without needing to be careful of import order. """ global _serializers serializers = {} for format in BUILTIN_SERIALIZERS: register_serializer(format, BUILTIN_SERIALIZERS[format], serializers) if hasattr(settings, "SERIALIZATION_MODULES"): for format in settings.SERIALIZATION_MODULES: register_serializer(format, settings.SERIALIZATION_MODULES[format], serializers) _serializers = serializers
[ "def", "_load_serializers", "(", ")", ":", "global", "_serializers", "serializers", "=", "{", "}", "for", "format", "in", "BUILTIN_SERIALIZERS", ":", "register_serializer", "(", "format", ",", "BUILTIN_SERIALIZERS", "[", "format", "]", ",", "serializers", ")", "if", "hasattr", "(", "settings", ",", "\"SERIALIZATION_MODULES\"", ")", ":", "for", "format", "in", "settings", ".", "SERIALIZATION_MODULES", ":", "register_serializer", "(", "format", ",", "settings", ".", "SERIALIZATION_MODULES", "[", "format", "]", ",", "serializers", ")", "_serializers", "=", "serializers" ]
[ 143, 0 ]
[ 156, 30 ]
python
en
['en', 'error', 'th']
False
sort_dependencies
(app_list, allow_cycles=False)
Sort a list of (app_config, models) pairs into a single list of models. The single list of models is sorted so that any model with a natural key is serialized before a normal model, and any model with a natural key dependency has it's dependencies serialized first. If allow_cycles is True, return the best-effort ordering that will respect most of dependencies but ignore some of them to break the cycles.
Sort a list of (app_config, models) pairs into a single list of models.
def sort_dependencies(app_list, allow_cycles=False): """Sort a list of (app_config, models) pairs into a single list of models. The single list of models is sorted so that any model with a natural key is serialized before a normal model, and any model with a natural key dependency has it's dependencies serialized first. If allow_cycles is True, return the best-effort ordering that will respect most of dependencies but ignore some of them to break the cycles. """ # Process the list of models, and get the list of dependencies model_dependencies = [] models = set() for app_config, model_list in app_list: if model_list is None: model_list = app_config.get_models() for model in model_list: models.add(model) # Add any explicitly defined dependencies if hasattr(model, 'natural_key'): deps = getattr(model.natural_key, 'dependencies', []) if deps: deps = [apps.get_model(dep) for dep in deps] else: deps = [] # Now add a dependency for any FK relation with a model that # defines a natural key for field in model._meta.fields: if field.remote_field: rel_model = field.remote_field.model if hasattr(rel_model, 'natural_key') and rel_model != model: deps.append(rel_model) # Also add a dependency for any simple M2M relation with a model # that defines a natural key. M2M relations with explicit through # models don't count as dependencies. for field in model._meta.many_to_many: if field.remote_field.through._meta.auto_created: rel_model = field.remote_field.model if hasattr(rel_model, 'natural_key') and rel_model != model: deps.append(rel_model) model_dependencies.append((model, deps)) model_dependencies.reverse() # Now sort the models to ensure that dependencies are met. This # is done by repeatedly iterating over the input list of models. # If all the dependencies of a given model are in the final list, # that model is promoted to the end of the final list. This process # continues until the input list is empty, or we do a full iteration # over the input models without promoting a model to the final list. # If we do a full iteration without a promotion, that means there are # circular dependencies in the list. model_list = [] while model_dependencies: skipped = [] changed = False while model_dependencies: model, deps = model_dependencies.pop() # If all of the models in the dependency list are either already # on the final model list, or not on the original serialization list, # then we've found another model with all it's dependencies satisfied. if all(d not in models or d in model_list for d in deps): model_list.append(model) changed = True else: skipped.append((model, deps)) if not changed: if allow_cycles: # If cycles are allowed, add the last skipped model and ignore # its dependencies. This could be improved by some graph # analysis to ignore as few dependencies as possible. model, _ = skipped.pop() model_list.append(model) else: raise RuntimeError( "Can't resolve dependencies for %s in serialized app list." % ', '.join( model._meta.label for model, deps in sorted(skipped, key=lambda obj: obj[0].__name__) ), ) model_dependencies = skipped return model_list
[ "def", "sort_dependencies", "(", "app_list", ",", "allow_cycles", "=", "False", ")", ":", "# Process the list of models, and get the list of dependencies", "model_dependencies", "=", "[", "]", "models", "=", "set", "(", ")", "for", "app_config", ",", "model_list", "in", "app_list", ":", "if", "model_list", "is", "None", ":", "model_list", "=", "app_config", ".", "get_models", "(", ")", "for", "model", "in", "model_list", ":", "models", ".", "add", "(", "model", ")", "# Add any explicitly defined dependencies", "if", "hasattr", "(", "model", ",", "'natural_key'", ")", ":", "deps", "=", "getattr", "(", "model", ".", "natural_key", ",", "'dependencies'", ",", "[", "]", ")", "if", "deps", ":", "deps", "=", "[", "apps", ".", "get_model", "(", "dep", ")", "for", "dep", "in", "deps", "]", "else", ":", "deps", "=", "[", "]", "# Now add a dependency for any FK relation with a model that", "# defines a natural key", "for", "field", "in", "model", ".", "_meta", ".", "fields", ":", "if", "field", ".", "remote_field", ":", "rel_model", "=", "field", ".", "remote_field", ".", "model", "if", "hasattr", "(", "rel_model", ",", "'natural_key'", ")", "and", "rel_model", "!=", "model", ":", "deps", ".", "append", "(", "rel_model", ")", "# Also add a dependency for any simple M2M relation with a model", "# that defines a natural key. M2M relations with explicit through", "# models don't count as dependencies.", "for", "field", "in", "model", ".", "_meta", ".", "many_to_many", ":", "if", "field", ".", "remote_field", ".", "through", ".", "_meta", ".", "auto_created", ":", "rel_model", "=", "field", ".", "remote_field", ".", "model", "if", "hasattr", "(", "rel_model", ",", "'natural_key'", ")", "and", "rel_model", "!=", "model", ":", "deps", ".", "append", "(", "rel_model", ")", "model_dependencies", ".", "append", "(", "(", "model", ",", "deps", ")", ")", "model_dependencies", ".", "reverse", "(", ")", "# Now sort the models to ensure that dependencies are met. This", "# is done by repeatedly iterating over the input list of models.", "# If all the dependencies of a given model are in the final list,", "# that model is promoted to the end of the final list. This process", "# continues until the input list is empty, or we do a full iteration", "# over the input models without promoting a model to the final list.", "# If we do a full iteration without a promotion, that means there are", "# circular dependencies in the list.", "model_list", "=", "[", "]", "while", "model_dependencies", ":", "skipped", "=", "[", "]", "changed", "=", "False", "while", "model_dependencies", ":", "model", ",", "deps", "=", "model_dependencies", ".", "pop", "(", ")", "# If all of the models in the dependency list are either already", "# on the final model list, or not on the original serialization list,", "# then we've found another model with all it's dependencies satisfied.", "if", "all", "(", "d", "not", "in", "models", "or", "d", "in", "model_list", "for", "d", "in", "deps", ")", ":", "model_list", ".", "append", "(", "model", ")", "changed", "=", "True", "else", ":", "skipped", ".", "append", "(", "(", "model", ",", "deps", ")", ")", "if", "not", "changed", ":", "if", "allow_cycles", ":", "# If cycles are allowed, add the last skipped model and ignore", "# its dependencies. This could be improved by some graph", "# analysis to ignore as few dependencies as possible.", "model", ",", "_", "=", "skipped", ".", "pop", "(", ")", "model_list", ".", "append", "(", "model", ")", "else", ":", "raise", "RuntimeError", "(", "\"Can't resolve dependencies for %s in serialized app list.\"", "%", "', '", ".", "join", "(", "model", ".", "_meta", ".", "label", "for", "model", ",", "deps", "in", "sorted", "(", "skipped", ",", "key", "=", "lambda", "obj", ":", "obj", "[", "0", "]", ".", "__name__", ")", ")", ",", ")", "model_dependencies", "=", "skipped", "return", "model_list" ]
[ 159, 0 ]
[ 244, 21 ]
python
en
['en', 'en', 'en']
True
WhereNode.split_having
(self, negated=False)
Return two possibly None nodes: one for those parts of self that should be included in the WHERE clause and one for those parts of self that must be included in the HAVING clause.
Return two possibly None nodes: one for those parts of self that should be included in the WHERE clause and one for those parts of self that must be included in the HAVING clause.
def split_having(self, negated=False): """ Return two possibly None nodes: one for those parts of self that should be included in the WHERE clause and one for those parts of self that must be included in the HAVING clause. """ if not self.contains_aggregate: return self, None in_negated = negated ^ self.negated # If the effective connector is OR and this node contains an aggregate, # then we need to push the whole branch to HAVING clause. may_need_split = ( (in_negated and self.connector == AND) or (not in_negated and self.connector == OR)) if may_need_split and self.contains_aggregate: return None, self where_parts = [] having_parts = [] for c in self.children: if hasattr(c, 'split_having'): where_part, having_part = c.split_having(in_negated) if where_part is not None: where_parts.append(where_part) if having_part is not None: having_parts.append(having_part) elif c.contains_aggregate: having_parts.append(c) else: where_parts.append(c) having_node = self.__class__(having_parts, self.connector, self.negated) if having_parts else None where_node = self.__class__(where_parts, self.connector, self.negated) if where_parts else None return where_node, having_node
[ "def", "split_having", "(", "self", ",", "negated", "=", "False", ")", ":", "if", "not", "self", ".", "contains_aggregate", ":", "return", "self", ",", "None", "in_negated", "=", "negated", "^", "self", ".", "negated", "# If the effective connector is OR and this node contains an aggregate,", "# then we need to push the whole branch to HAVING clause.", "may_need_split", "=", "(", "(", "in_negated", "and", "self", ".", "connector", "==", "AND", ")", "or", "(", "not", "in_negated", "and", "self", ".", "connector", "==", "OR", ")", ")", "if", "may_need_split", "and", "self", ".", "contains_aggregate", ":", "return", "None", ",", "self", "where_parts", "=", "[", "]", "having_parts", "=", "[", "]", "for", "c", "in", "self", ".", "children", ":", "if", "hasattr", "(", "c", ",", "'split_having'", ")", ":", "where_part", ",", "having_part", "=", "c", ".", "split_having", "(", "in_negated", ")", "if", "where_part", "is", "not", "None", ":", "where_parts", ".", "append", "(", "where_part", ")", "if", "having_part", "is", "not", "None", ":", "having_parts", ".", "append", "(", "having_part", ")", "elif", "c", ".", "contains_aggregate", ":", "having_parts", ".", "append", "(", "c", ")", "else", ":", "where_parts", ".", "append", "(", "c", ")", "having_node", "=", "self", ".", "__class__", "(", "having_parts", ",", "self", ".", "connector", ",", "self", ".", "negated", ")", "if", "having_parts", "else", "None", "where_node", "=", "self", ".", "__class__", "(", "where_parts", ",", "self", ".", "connector", ",", "self", ".", "negated", ")", "if", "where_parts", "else", "None", "return", "where_node", ",", "having_node" ]
[ 31, 4 ]
[ 62, 38 ]
python
en
['en', 'error', 'th']
False
WhereNode.as_sql
(self, compiler, connection)
Return the SQL version of the where clause and the value to be substituted in. Return '', [] if this node matches everything, None, [] if this node is empty, and raise EmptyResultSet if this node can't match anything.
Return the SQL version of the where clause and the value to be substituted in. Return '', [] if this node matches everything, None, [] if this node is empty, and raise EmptyResultSet if this node can't match anything.
def as_sql(self, compiler, connection): """ Return the SQL version of the where clause and the value to be substituted in. Return '', [] if this node matches everything, None, [] if this node is empty, and raise EmptyResultSet if this node can't match anything. """ result = [] result_params = [] if self.connector == AND: full_needed, empty_needed = len(self.children), 1 else: full_needed, empty_needed = 1, len(self.children) for child in self.children: try: sql, params = compiler.compile(child) except EmptyResultSet: empty_needed -= 1 else: if sql: result.append(sql) result_params.extend(params) else: full_needed -= 1 # Check if this node matches nothing or everything. # First check the amount of full nodes and empty nodes # to make this node empty/full. # Now, check if this node is full/empty using the # counts. if empty_needed == 0: if self.negated: return '', [] else: raise EmptyResultSet if full_needed == 0: if self.negated: raise EmptyResultSet else: return '', [] conn = ' %s ' % self.connector sql_string = conn.join(result) if sql_string: if self.negated: # Some backends (Oracle at least) need parentheses # around the inner SQL in the negated case, even if the # inner SQL contains just a single expression. sql_string = 'NOT (%s)' % sql_string elif len(result) > 1 or self.resolved: sql_string = '(%s)' % sql_string return sql_string, result_params
[ "def", "as_sql", "(", "self", ",", "compiler", ",", "connection", ")", ":", "result", "=", "[", "]", "result_params", "=", "[", "]", "if", "self", ".", "connector", "==", "AND", ":", "full_needed", ",", "empty_needed", "=", "len", "(", "self", ".", "children", ")", ",", "1", "else", ":", "full_needed", ",", "empty_needed", "=", "1", ",", "len", "(", "self", ".", "children", ")", "for", "child", "in", "self", ".", "children", ":", "try", ":", "sql", ",", "params", "=", "compiler", ".", "compile", "(", "child", ")", "except", "EmptyResultSet", ":", "empty_needed", "-=", "1", "else", ":", "if", "sql", ":", "result", ".", "append", "(", "sql", ")", "result_params", ".", "extend", "(", "params", ")", "else", ":", "full_needed", "-=", "1", "# Check if this node matches nothing or everything.", "# First check the amount of full nodes and empty nodes", "# to make this node empty/full.", "# Now, check if this node is full/empty using the", "# counts.", "if", "empty_needed", "==", "0", ":", "if", "self", ".", "negated", ":", "return", "''", ",", "[", "]", "else", ":", "raise", "EmptyResultSet", "if", "full_needed", "==", "0", ":", "if", "self", ".", "negated", ":", "raise", "EmptyResultSet", "else", ":", "return", "''", ",", "[", "]", "conn", "=", "' %s '", "%", "self", ".", "connector", "sql_string", "=", "conn", ".", "join", "(", "result", ")", "if", "sql_string", ":", "if", "self", ".", "negated", ":", "# Some backends (Oracle at least) need parentheses", "# around the inner SQL in the negated case, even if the", "# inner SQL contains just a single expression.", "sql_string", "=", "'NOT (%s)'", "%", "sql_string", "elif", "len", "(", "result", ")", ">", "1", "or", "self", ".", "resolved", ":", "sql_string", "=", "'(%s)'", "%", "sql_string", "return", "sql_string", ",", "result_params" ]
[ 64, 4 ]
[ 114, 40 ]
python
en
['en', 'error', 'th']
False
WhereNode.relabel_aliases
(self, change_map)
Relabel the alias values of any children. 'change_map' is a dictionary mapping old (current) alias values to the new values.
Relabel the alias values of any children. 'change_map' is a dictionary mapping old (current) alias values to the new values.
def relabel_aliases(self, change_map): """ Relabel the alias values of any children. 'change_map' is a dictionary mapping old (current) alias values to the new values. """ for pos, child in enumerate(self.children): if hasattr(child, 'relabel_aliases'): # For example another WhereNode child.relabel_aliases(change_map) elif hasattr(child, 'relabeled_clone'): self.children[pos] = child.relabeled_clone(change_map)
[ "def", "relabel_aliases", "(", "self", ",", "change_map", ")", ":", "for", "pos", ",", "child", "in", "enumerate", "(", "self", ".", "children", ")", ":", "if", "hasattr", "(", "child", ",", "'relabel_aliases'", ")", ":", "# For example another WhereNode", "child", ".", "relabel_aliases", "(", "change_map", ")", "elif", "hasattr", "(", "child", ",", "'relabeled_clone'", ")", ":", "self", ".", "children", "[", "pos", "]", "=", "child", ".", "relabeled_clone", "(", "change_map", ")" ]
[ 129, 4 ]
[ 139, 70 ]
python
en
['en', 'error', 'th']
False
WhereNode.clone
(self)
Create a clone of the tree. Must only be called on root nodes (nodes with empty subtree_parents). Childs must be either (Constraint, lookup, value) tuples, or objects supporting .clone().
Create a clone of the tree. Must only be called on root nodes (nodes with empty subtree_parents). Childs must be either (Constraint, lookup, value) tuples, or objects supporting .clone().
def clone(self): """ Create a clone of the tree. Must only be called on root nodes (nodes with empty subtree_parents). Childs must be either (Constraint, lookup, value) tuples, or objects supporting .clone(). """ clone = self.__class__._new_instance( children=[], connector=self.connector, negated=self.negated) for child in self.children: if hasattr(child, 'clone'): clone.children.append(child.clone()) else: clone.children.append(child) return clone
[ "def", "clone", "(", "self", ")", ":", "clone", "=", "self", ".", "__class__", ".", "_new_instance", "(", "children", "=", "[", "]", ",", "connector", "=", "self", ".", "connector", ",", "negated", "=", "self", ".", "negated", ")", "for", "child", "in", "self", ".", "children", ":", "if", "hasattr", "(", "child", ",", "'clone'", ")", ":", "clone", ".", "children", ".", "append", "(", "child", ".", "clone", "(", ")", ")", "else", ":", "clone", ".", "children", ".", "append", "(", "child", ")", "return", "clone" ]
[ 141, 4 ]
[ 154, 20 ]
python
en
['en', 'error', 'th']
False
_get_related_models
(m)
Return all models that have a direct relationship to the given model.
Return all models that have a direct relationship to the given model.
def _get_related_models(m): """Return all models that have a direct relationship to the given model.""" related_models = [ subclass for subclass in m.__subclasses__() if issubclass(subclass, models.Model) ] related_fields_models = set() for f in m._meta.get_fields(include_parents=True, include_hidden=True): if f.is_relation and f.related_model is not None and not isinstance(f.related_model, str): related_fields_models.add(f.model) related_models.append(f.related_model) # Reverse accessors of foreign keys to proxy models are attached to their # concrete proxied model. opts = m._meta if opts.proxy and m in related_fields_models: related_models.append(opts.concrete_model) return related_models
[ "def", "_get_related_models", "(", "m", ")", ":", "related_models", "=", "[", "subclass", "for", "subclass", "in", "m", ".", "__subclasses__", "(", ")", "if", "issubclass", "(", "subclass", ",", "models", ".", "Model", ")", "]", "related_fields_models", "=", "set", "(", ")", "for", "f", "in", "m", ".", "_meta", ".", "get_fields", "(", "include_parents", "=", "True", ",", "include_hidden", "=", "True", ")", ":", "if", "f", ".", "is_relation", "and", "f", ".", "related_model", "is", "not", "None", "and", "not", "isinstance", "(", "f", ".", "related_model", ",", "str", ")", ":", "related_fields_models", ".", "add", "(", "f", ".", "model", ")", "related_models", ".", "append", "(", "f", ".", "related_model", ")", "# Reverse accessors of foreign keys to proxy models are attached to their", "# concrete proxied model.", "opts", "=", "m", ".", "_meta", "if", "opts", ".", "proxy", "and", "m", "in", "related_fields_models", ":", "related_models", ".", "append", "(", "opts", ".", "concrete_model", ")", "return", "related_models" ]
[ 25, 0 ]
[ 41, 25 ]
python
en
['en', 'en', 'en']
True
get_related_models_tuples
(model)
Return a list of typical (app_label, model_name) tuples for all related models for the given model.
Return a list of typical (app_label, model_name) tuples for all related models for the given model.
def get_related_models_tuples(model): """ Return a list of typical (app_label, model_name) tuples for all related models for the given model. """ return { (rel_mod._meta.app_label, rel_mod._meta.model_name) for rel_mod in _get_related_models(model) }
[ "def", "get_related_models_tuples", "(", "model", ")", ":", "return", "{", "(", "rel_mod", ".", "_meta", ".", "app_label", ",", "rel_mod", ".", "_meta", ".", "model_name", ")", "for", "rel_mod", "in", "_get_related_models", "(", "model", ")", "}" ]
[ 44, 0 ]
[ 52, 5 ]
python
en
['en', 'error', 'th']
False
get_related_models_recursive
(model)
Return all models that have a direct or indirect relationship to the given model. Relationships are either defined by explicit relational fields, like ForeignKey, ManyToManyField or OneToOneField, or by inheriting from another model (a superclass is related to its subclasses, but not vice versa). Note, however, that a model inheriting from a concrete model is also related to its superclass through the implicit *_ptr OneToOneField on the subclass.
Return all models that have a direct or indirect relationship to the given model.
def get_related_models_recursive(model): """ Return all models that have a direct or indirect relationship to the given model. Relationships are either defined by explicit relational fields, like ForeignKey, ManyToManyField or OneToOneField, or by inheriting from another model (a superclass is related to its subclasses, but not vice versa). Note, however, that a model inheriting from a concrete model is also related to its superclass through the implicit *_ptr OneToOneField on the subclass. """ seen = set() queue = _get_related_models(model) for rel_mod in queue: rel_app_label, rel_model_name = rel_mod._meta.app_label, rel_mod._meta.model_name if (rel_app_label, rel_model_name) in seen: continue seen.add((rel_app_label, rel_model_name)) queue.extend(_get_related_models(rel_mod)) return seen - {(model._meta.app_label, model._meta.model_name)}
[ "def", "get_related_models_recursive", "(", "model", ")", ":", "seen", "=", "set", "(", ")", "queue", "=", "_get_related_models", "(", "model", ")", "for", "rel_mod", "in", "queue", ":", "rel_app_label", ",", "rel_model_name", "=", "rel_mod", ".", "_meta", ".", "app_label", ",", "rel_mod", ".", "_meta", ".", "model_name", "if", "(", "rel_app_label", ",", "rel_model_name", ")", "in", "seen", ":", "continue", "seen", ".", "add", "(", "(", "rel_app_label", ",", "rel_model_name", ")", ")", "queue", ".", "extend", "(", "_get_related_models", "(", "rel_mod", ")", ")", "return", "seen", "-", "{", "(", "model", ".", "_meta", ".", "app_label", ",", "model", ".", "_meta", ".", "model_name", ")", "}" ]
[ 55, 0 ]
[ 74, 67 ]
python
en
['en', 'error', 'th']
False
ProjectState.clone
(self)
Return an exact copy of this ProjectState.
Return an exact copy of this ProjectState.
def clone(self): """Return an exact copy of this ProjectState.""" new_state = ProjectState( models={k: v.clone() for k, v in self.models.items()}, real_apps=self.real_apps, ) if 'apps' in self.__dict__: new_state.apps = self.apps.clone() new_state.is_delayed = self.is_delayed return new_state
[ "def", "clone", "(", "self", ")", ":", "new_state", "=", "ProjectState", "(", "models", "=", "{", "k", ":", "v", ".", "clone", "(", ")", "for", "k", ",", "v", "in", "self", ".", "models", ".", "items", "(", ")", "}", ",", "real_apps", "=", "self", ".", "real_apps", ",", ")", "if", "'apps'", "in", "self", ".", "__dict__", ":", "new_state", ".", "apps", "=", "self", ".", "apps", ".", "clone", "(", ")", "new_state", ".", "is_delayed", "=", "self", ".", "is_delayed", "return", "new_state" ]
[ 190, 4 ]
[ 199, 24 ]
python
en
['en', 'en', 'en']
True
ProjectState.from_apps
(cls, apps)
Take an Apps and return a ProjectState matching it.
Take an Apps and return a ProjectState matching it.
def from_apps(cls, apps): """Take an Apps and return a ProjectState matching it.""" app_models = {} for model in apps.get_models(include_swapped=True): model_state = ModelState.from_model(model) app_models[(model_state.app_label, model_state.name_lower)] = model_state return cls(app_models)
[ "def", "from_apps", "(", "cls", ",", "apps", ")", ":", "app_models", "=", "{", "}", "for", "model", "in", "apps", ".", "get_models", "(", "include_swapped", "=", "True", ")", ":", "model_state", "=", "ModelState", ".", "from_model", "(", "model", ")", "app_models", "[", "(", "model_state", ".", "app_label", ",", "model_state", ".", "name_lower", ")", "]", "=", "model_state", "return", "cls", "(", "app_models", ")" ]
[ 215, 4 ]
[ 221, 30 ]
python
en
['en', 'en', 'en']
True
StateApps.clone
(self)
Return a clone of this registry.
Return a clone of this registry.
def clone(self): """Return a clone of this registry.""" clone = StateApps([], {}) clone.all_models = copy.deepcopy(self.all_models) clone.app_configs = copy.deepcopy(self.app_configs) # Set the pointer to the correct app registry. for app_config in clone.app_configs.values(): app_config.apps = clone # No need to actually clone them, they'll never change clone.real_models = self.real_models return clone
[ "def", "clone", "(", "self", ")", ":", "clone", "=", "StateApps", "(", "[", "]", ",", "{", "}", ")", "clone", ".", "all_models", "=", "copy", ".", "deepcopy", "(", "self", ".", "all_models", ")", "clone", ".", "app_configs", "=", "copy", ".", "deepcopy", "(", "self", ".", "app_configs", ")", "# Set the pointer to the correct app registry.", "for", "app_config", "in", "clone", ".", "app_configs", ".", "values", "(", ")", ":", "app_config", ".", "apps", "=", "clone", "# No need to actually clone them, they'll never change", "clone", ".", "real_models", "=", "self", ".", "real_models", "return", "clone" ]
[ 316, 4 ]
[ 326, 20 ]
python
en
['en', 'en', 'en']
True
ModelState.from_model
(cls, model, exclude_rels=False)
Given a model, return a ModelState representing it.
Given a model, return a ModelState representing it.
def from_model(cls, model, exclude_rels=False): """Given a model, return a ModelState representing it.""" # Deconstruct the fields fields = [] for field in model._meta.local_fields: if getattr(field, "remote_field", None) and exclude_rels: continue if isinstance(field, models.OrderWrt): continue name = field.name try: fields.append((name, field.clone())) except TypeError as e: raise TypeError("Couldn't reconstruct field %s on %s: %s" % ( name, model._meta.label, e, )) if not exclude_rels: for field in model._meta.local_many_to_many: name = field.name try: fields.append((name, field.clone())) except TypeError as e: raise TypeError("Couldn't reconstruct m2m field %s on %s: %s" % ( name, model._meta.object_name, e, )) # Extract the options options = {} for name in DEFAULT_NAMES: # Ignore some special options if name in ["apps", "app_label"]: continue elif name in model._meta.original_attrs: if name == "unique_together": ut = model._meta.original_attrs["unique_together"] options[name] = set(normalize_together(ut)) elif name == "index_together": it = model._meta.original_attrs["index_together"] options[name] = set(normalize_together(it)) elif name == "indexes": indexes = [idx.clone() for idx in model._meta.indexes] for index in indexes: if not index.name: index.set_name_with_model(model) options['indexes'] = indexes elif name == 'constraints': options['constraints'] = [con.clone() for con in model._meta.constraints] else: options[name] = model._meta.original_attrs[name] # If we're ignoring relationships, remove all field-listing model # options (that option basically just means "make a stub model") if exclude_rels: for key in ["unique_together", "index_together", "order_with_respect_to"]: if key in options: del options[key] # Private fields are ignored, so remove options that refer to them. elif options.get('order_with_respect_to') in {field.name for field in model._meta.private_fields}: del options['order_with_respect_to'] def flatten_bases(model): bases = [] for base in model.__bases__: if hasattr(base, "_meta") and base._meta.abstract: bases.extend(flatten_bases(base)) else: bases.append(base) return bases # We can't rely on __mro__ directly because we only want to flatten # abstract models and not the whole tree. However by recursing on # __bases__ we may end up with duplicates and ordering issues, we # therefore discard any duplicates and reorder the bases according # to their index in the MRO. flattened_bases = sorted(set(flatten_bases(model)), key=lambda x: model.__mro__.index(x)) # Make our record bases = tuple( ( base._meta.label_lower if hasattr(base, "_meta") else base ) for base in flattened_bases ) # Ensure at least one base inherits from models.Model if not any((isinstance(base, str) or issubclass(base, models.Model)) for base in bases): bases = (models.Model,) managers = [] manager_names = set() default_manager_shim = None for manager in model._meta.managers: if manager.name in manager_names: # Skip overridden managers. continue elif manager.use_in_migrations: # Copy managers usable in migrations. new_manager = copy.copy(manager) new_manager._set_creation_counter() elif manager is model._base_manager or manager is model._default_manager: # Shim custom managers used as default and base managers. new_manager = models.Manager() new_manager.model = manager.model new_manager.name = manager.name if manager is model._default_manager: default_manager_shim = new_manager else: continue manager_names.add(manager.name) managers.append((manager.name, new_manager)) # Ignore a shimmed default manager called objects if it's the only one. if managers == [('objects', default_manager_shim)]: managers = [] # Construct the new ModelState return cls( model._meta.app_label, model._meta.object_name, fields, options, bases, managers, )
[ "def", "from_model", "(", "cls", ",", "model", ",", "exclude_rels", "=", "False", ")", ":", "# Deconstruct the fields", "fields", "=", "[", "]", "for", "field", "in", "model", ".", "_meta", ".", "local_fields", ":", "if", "getattr", "(", "field", ",", "\"remote_field\"", ",", "None", ")", "and", "exclude_rels", ":", "continue", "if", "isinstance", "(", "field", ",", "models", ".", "OrderWrt", ")", ":", "continue", "name", "=", "field", ".", "name", "try", ":", "fields", ".", "append", "(", "(", "name", ",", "field", ".", "clone", "(", ")", ")", ")", "except", "TypeError", "as", "e", ":", "raise", "TypeError", "(", "\"Couldn't reconstruct field %s on %s: %s\"", "%", "(", "name", ",", "model", ".", "_meta", ".", "label", ",", "e", ",", ")", ")", "if", "not", "exclude_rels", ":", "for", "field", "in", "model", ".", "_meta", ".", "local_many_to_many", ":", "name", "=", "field", ".", "name", "try", ":", "fields", ".", "append", "(", "(", "name", ",", "field", ".", "clone", "(", ")", ")", ")", "except", "TypeError", "as", "e", ":", "raise", "TypeError", "(", "\"Couldn't reconstruct m2m field %s on %s: %s\"", "%", "(", "name", ",", "model", ".", "_meta", ".", "object_name", ",", "e", ",", ")", ")", "# Extract the options", "options", "=", "{", "}", "for", "name", "in", "DEFAULT_NAMES", ":", "# Ignore some special options", "if", "name", "in", "[", "\"apps\"", ",", "\"app_label\"", "]", ":", "continue", "elif", "name", "in", "model", ".", "_meta", ".", "original_attrs", ":", "if", "name", "==", "\"unique_together\"", ":", "ut", "=", "model", ".", "_meta", ".", "original_attrs", "[", "\"unique_together\"", "]", "options", "[", "name", "]", "=", "set", "(", "normalize_together", "(", "ut", ")", ")", "elif", "name", "==", "\"index_together\"", ":", "it", "=", "model", ".", "_meta", ".", "original_attrs", "[", "\"index_together\"", "]", "options", "[", "name", "]", "=", "set", "(", "normalize_together", "(", "it", ")", ")", "elif", "name", "==", "\"indexes\"", ":", "indexes", "=", "[", "idx", ".", "clone", "(", ")", "for", "idx", "in", "model", ".", "_meta", ".", "indexes", "]", "for", "index", "in", "indexes", ":", "if", "not", "index", ".", "name", ":", "index", ".", "set_name_with_model", "(", "model", ")", "options", "[", "'indexes'", "]", "=", "indexes", "elif", "name", "==", "'constraints'", ":", "options", "[", "'constraints'", "]", "=", "[", "con", ".", "clone", "(", ")", "for", "con", "in", "model", ".", "_meta", ".", "constraints", "]", "else", ":", "options", "[", "name", "]", "=", "model", ".", "_meta", ".", "original_attrs", "[", "name", "]", "# If we're ignoring relationships, remove all field-listing model", "# options (that option basically just means \"make a stub model\")", "if", "exclude_rels", ":", "for", "key", "in", "[", "\"unique_together\"", ",", "\"index_together\"", ",", "\"order_with_respect_to\"", "]", ":", "if", "key", "in", "options", ":", "del", "options", "[", "key", "]", "# Private fields are ignored, so remove options that refer to them.", "elif", "options", ".", "get", "(", "'order_with_respect_to'", ")", "in", "{", "field", ".", "name", "for", "field", "in", "model", ".", "_meta", ".", "private_fields", "}", ":", "del", "options", "[", "'order_with_respect_to'", "]", "def", "flatten_bases", "(", "model", ")", ":", "bases", "=", "[", "]", "for", "base", "in", "model", ".", "__bases__", ":", "if", "hasattr", "(", "base", ",", "\"_meta\"", ")", "and", "base", ".", "_meta", ".", "abstract", ":", "bases", ".", "extend", "(", "flatten_bases", "(", "base", ")", ")", "else", ":", "bases", ".", "append", "(", "base", ")", "return", "bases", "# We can't rely on __mro__ directly because we only want to flatten", "# abstract models and not the whole tree. However by recursing on", "# __bases__ we may end up with duplicates and ordering issues, we", "# therefore discard any duplicates and reorder the bases according", "# to their index in the MRO.", "flattened_bases", "=", "sorted", "(", "set", "(", "flatten_bases", "(", "model", ")", ")", ",", "key", "=", "lambda", "x", ":", "model", ".", "__mro__", ".", "index", "(", "x", ")", ")", "# Make our record", "bases", "=", "tuple", "(", "(", "base", ".", "_meta", ".", "label_lower", "if", "hasattr", "(", "base", ",", "\"_meta\"", ")", "else", "base", ")", "for", "base", "in", "flattened_bases", ")", "# Ensure at least one base inherits from models.Model", "if", "not", "any", "(", "(", "isinstance", "(", "base", ",", "str", ")", "or", "issubclass", "(", "base", ",", "models", ".", "Model", ")", ")", "for", "base", "in", "bases", ")", ":", "bases", "=", "(", "models", ".", "Model", ",", ")", "managers", "=", "[", "]", "manager_names", "=", "set", "(", ")", "default_manager_shim", "=", "None", "for", "manager", "in", "model", ".", "_meta", ".", "managers", ":", "if", "manager", ".", "name", "in", "manager_names", ":", "# Skip overridden managers.", "continue", "elif", "manager", ".", "use_in_migrations", ":", "# Copy managers usable in migrations.", "new_manager", "=", "copy", ".", "copy", "(", "manager", ")", "new_manager", ".", "_set_creation_counter", "(", ")", "elif", "manager", "is", "model", ".", "_base_manager", "or", "manager", "is", "model", ".", "_default_manager", ":", "# Shim custom managers used as default and base managers.", "new_manager", "=", "models", ".", "Manager", "(", ")", "new_manager", ".", "model", "=", "manager", ".", "model", "new_manager", ".", "name", "=", "manager", ".", "name", "if", "manager", "is", "model", ".", "_default_manager", ":", "default_manager_shim", "=", "new_manager", "else", ":", "continue", "manager_names", ".", "add", "(", "manager", ".", "name", ")", "managers", ".", "append", "(", "(", "manager", ".", "name", ",", "new_manager", ")", ")", "# Ignore a shimmed default manager called objects if it's the only one.", "if", "managers", "==", "[", "(", "'objects'", ",", "default_manager_shim", ")", "]", ":", "managers", "=", "[", "]", "# Construct the new ModelState", "return", "cls", "(", "model", ".", "_meta", ".", "app_label", ",", "model", ".", "_meta", ".", "object_name", ",", "fields", ",", "options", ",", "bases", ",", "managers", ",", ")" ]
[ 395, 4 ]
[ 521, 9 ]
python
en
['en', 'en', 'en']
True
ModelState.construct_managers
(self)
Deep-clone the managers using deconstruction.
Deep-clone the managers using deconstruction.
def construct_managers(self): """Deep-clone the managers using deconstruction.""" # Sort all managers by their creation counter sorted_managers = sorted(self.managers, key=lambda v: v[1].creation_counter) for mgr_name, manager in sorted_managers: as_manager, manager_path, qs_path, args, kwargs = manager.deconstruct() if as_manager: qs_class = import_string(qs_path) yield mgr_name, qs_class.as_manager() else: manager_class = import_string(manager_path) yield mgr_name, manager_class(*args, **kwargs)
[ "def", "construct_managers", "(", "self", ")", ":", "# Sort all managers by their creation counter", "sorted_managers", "=", "sorted", "(", "self", ".", "managers", ",", "key", "=", "lambda", "v", ":", "v", "[", "1", "]", ".", "creation_counter", ")", "for", "mgr_name", ",", "manager", "in", "sorted_managers", ":", "as_manager", ",", "manager_path", ",", "qs_path", ",", "args", ",", "kwargs", "=", "manager", ".", "deconstruct", "(", ")", "if", "as_manager", ":", "qs_class", "=", "import_string", "(", "qs_path", ")", "yield", "mgr_name", ",", "qs_class", ".", "as_manager", "(", ")", "else", ":", "manager_class", "=", "import_string", "(", "manager_path", ")", "yield", "mgr_name", ",", "manager_class", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
[ 523, 4 ]
[ 534, 62 ]
python
en
['en', 'en', 'en']
True
ModelState.clone
(self)
Return an exact copy of this ModelState.
Return an exact copy of this ModelState.
def clone(self): """Return an exact copy of this ModelState.""" return self.__class__( app_label=self.app_label, name=self.name, fields=dict(self.fields), # Since options are shallow-copied here, operations such as # AddIndex must replace their option (e.g 'indexes') rather # than mutating it. options=dict(self.options), bases=self.bases, managers=list(self.managers), )
[ "def", "clone", "(", "self", ")", ":", "return", "self", ".", "__class__", "(", "app_label", "=", "self", ".", "app_label", ",", "name", "=", "self", ".", "name", ",", "fields", "=", "dict", "(", "self", ".", "fields", ")", ",", "# Since options are shallow-copied here, operations such as", "# AddIndex must replace their option (e.g 'indexes') rather", "# than mutating it.", "options", "=", "dict", "(", "self", ".", "options", ")", ",", "bases", "=", "self", ".", "bases", ",", "managers", "=", "list", "(", "self", ".", "managers", ")", ",", ")" ]
[ 536, 4 ]
[ 548, 9 ]
python
en
['en', 'en', 'en']
True
ModelState.render
(self, apps)
Create a Model object from our current state into the given apps.
Create a Model object from our current state into the given apps.
def render(self, apps): """Create a Model object from our current state into the given apps.""" # First, make a Meta object meta_contents = {'app_label': self.app_label, 'apps': apps, **self.options} meta = type("Meta", (), meta_contents) # Then, work out our bases try: bases = tuple( (apps.get_model(base) if isinstance(base, str) else base) for base in self.bases ) except LookupError: raise InvalidBasesError("Cannot resolve one or more bases from %r" % (self.bases,)) # Clone fields for the body, add other bits. body = {name: field.clone() for name, field in self.fields.items()} body['Meta'] = meta body['__module__'] = "__fake__" # Restore managers body.update(self.construct_managers()) # Then, make a Model object (apps.register_model is called in __new__) return type(self.name, bases, body)
[ "def", "render", "(", "self", ",", "apps", ")", ":", "# First, make a Meta object", "meta_contents", "=", "{", "'app_label'", ":", "self", ".", "app_label", ",", "'apps'", ":", "apps", ",", "*", "*", "self", ".", "options", "}", "meta", "=", "type", "(", "\"Meta\"", ",", "(", ")", ",", "meta_contents", ")", "# Then, work out our bases", "try", ":", "bases", "=", "tuple", "(", "(", "apps", ".", "get_model", "(", "base", ")", "if", "isinstance", "(", "base", ",", "str", ")", "else", "base", ")", "for", "base", "in", "self", ".", "bases", ")", "except", "LookupError", ":", "raise", "InvalidBasesError", "(", "\"Cannot resolve one or more bases from %r\"", "%", "(", "self", ".", "bases", ",", ")", ")", "# Clone fields for the body, add other bits.", "body", "=", "{", "name", ":", "field", ".", "clone", "(", ")", "for", "name", ",", "field", "in", "self", ".", "fields", ".", "items", "(", ")", "}", "body", "[", "'Meta'", "]", "=", "meta", "body", "[", "'__module__'", "]", "=", "\"__fake__\"", "# Restore managers", "body", ".", "update", "(", "self", ".", "construct_managers", "(", ")", ")", "# Then, make a Model object (apps.register_model is called in __new__)", "return", "type", "(", "self", ".", "name", ",", "bases", ",", "body", ")" ]
[ 550, 4 ]
[ 571, 43 ]
python
en
['en', 'en', 'en']
True