_id stringlengths 2 7 | title stringlengths 1 88 | partition stringclasses 3
values | text stringlengths 31 13.1k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q254800 | cmd_logs | validation | def cmd_logs(opts):
"""Fetch the logs of a container
"""
config = load_config(opts.config) | python | {
"resource": ""
} |
q254801 | cmd_daemon | validation | def cmd_daemon(opts):
"""Start the Blockade REST API
"""
if opts.data_dir is None:
raise BlockadeError("You must supply a data directory for the daemon")
| python | {
"resource": ""
} |
q254802 | cmd_add | validation | def cmd_add(opts):
"""Add one or more existing Docker containers to a Blockade group
"""
config = load_config(opts.config)
b | python | {
"resource": ""
} |
q254803 | cmd_events | validation | def cmd_events(opts):
"""Get the event log for a given blockade
"""
config = load_config(opts.config)
b = get_blockade(config, opts)
if opts.json:
outf = None
_write = puts
if opts.output is not None:
outf = open(opts.output, "w")
_write = outf.write
try:
delim = ""
logs = b.get_audit().read_logs(as_json=False)
_write('{"events": [')
_write(os.linesep)
for l in logs:
_write(delim + l)
delim = "," + os.linesep
_write(os.linesep)
| python | {
"resource": ""
} |
q254804 | set_cors_headers | validation | def set_cors_headers(resp, options):
"""
Performs the actual evaluation of Flas-CORS options and actually
modifies the response object.
This function is used both in the decorator and the after_request
callback
"""
# If CORS has already been evaluated via the decorator, skip
if hasattr(resp, FLASK_CORS_EVALUATED):
LOG.debug('CORS have been already evaluated, skipping')
| python | {
"resource": ""
} |
q254805 | try_match | validation | def try_match(request_origin, maybe_regex):
"""Safely attempts to match a pattern or string to a request origin."""
if isinstance(maybe_regex, RegexObject):
return re.match(maybe_regex, request_origin)
| python | {
"resource": ""
} |
q254806 | get_cors_options | validation | def get_cors_options(appInstance, *dicts):
"""
Compute CORS options for an application by combining the DEFAULT_OPTIONS,
the app's configuration-specified options and any dictionaries passed. The
last specified option wins.
"""
| python | {
"resource": ""
} |
q254807 | get_app_kwarg_dict | validation | def get_app_kwarg_dict(appInstance=None):
"""Returns the dictionary of CORS specific app configurations."""
app = (appInstance or current_app)
# In order to support blueprints | python | {
"resource": ""
} |
q254808 | ensure_iterable | validation | def ensure_iterable(inst):
"""
Wraps scalars or string types as a list, or returns the iterable instance.
"""
if isinstance(inst, string_types):
| python | {
"resource": ""
} |
q254809 | serialize_options | validation | def serialize_options(opts):
"""
A helper method to serialize and processes the options dictionary.
"""
options = (opts or {}).copy()
for key in opts.keys():
if key not in DEFAULT_OPTIONS:
LOG.warning("Unknown option passed to Flask-CORS: %s", key)
# Ensure origins is a list of allowed origins with at least one entry.
options['origins'] = sanitize_regex_param(options.get('origins'))
options['allow_headers'] = sanitize_regex_param(options.get('allow_headers'))
# This is expressly forbidden by the spec. Raise a value error so people
# don't get burned in production.
if r'.*' in options['origins'] and options['supports_credentials'] and options['send_wildcard']:
raise ValueError("Cannot use supports_credentials in conjunction with"
| python | {
"resource": ""
} |
q254810 | cross_origin | validation | def cross_origin(*args, **kwargs):
"""
This function is the decorator which is used to wrap a Flask route with.
In the simplest case, simply use the default parameters to allow all
origins in what is the most permissive configuration. If this method
modifies state or performs authentication which may be brute-forced, you
should add some degree of protection, such as Cross Site Forgery
Request protection.
:param origins:
The origin, or list of origins to allow requests from.
The origin(s) may be regular expressions, case-sensitive strings,
or else an asterisk
Default : '*'
:type origins: list, string or regex
:param methods:
The method or list of methods which the allowed origins are allowed to
access for non-simple requests.
Default : [GET, HEAD, POST, OPTIONS, PUT, PATCH, DELETE]
:type methods: list or string
:param expose_headers:
The header or list which are safe to expose to the API of a CORS API
specification.
Default : None
:type expose_headers: list or string
:param allow_headers:
The header or list of header field names which can be used when this
resource is accessed by allowed origins. The header(s) may be regular
expressions, case-sensitive strings, or else an asterisk.
Default : '*', allow all headers
:type allow_headers: list, string or regex
:param supports_credentials:
Allows users to make authenticated requests. If true, injects the
`Access-Control-Allow-Credentials` header in responses. This allows
cookies and credentials to be submitted across domains.
:note: This option cannot be used in conjuction with a '*' origin
Default : False
:type supports_credentials: bool
:param max_age:
The maximum time for which this CORS request maybe cached. This value
is set as the `Access-Control-Max-Age` header.
Default : None
:type max_age: timedelta, integer, string or None
:param send_wildcard: If True, and the origins parameter is `*`, a wildcard
`Access-Control-Allow-Origin` header is sent, rather than the
request's `Origin` header.
Default : False
:type send_wildcard: bool
:param vary_header:
If True, the header Vary: Origin will be returned as per the W3
implementation guidelines.
Setting this header when the `Access-Control-Allow-Origin` is
dynamically generated (e.g. when there is more than one allowed
origin, and an Origin than '*' is returned) informs CDNs and other
caches that the CORS headers are dynamic, and cannot be cached.
If False, the Vary header will never be injected or altered.
Default : True
:type vary_header: bool
:param automatic_options: | python | {
"resource": ""
} |
q254811 | symbolsDF | validation | def symbolsDF(token='', version=''):
'''This call returns an array of symbols that IEX Cloud supports for API calls.
https://iexcloud.io/docs/api/#symbols
8am, 9am, 12pm, 1pm UTC daily
Args:
token (string); Access token
version (string); API version
| python | {
"resource": ""
} |
q254812 | mutualFundSymbolsDF | validation | def mutualFundSymbolsDF(token='', version=''):
'''This call returns an array of mutual fund symbols that IEX Cloud supports for API calls.
https://iexcloud.io/docs/api/#mutual-fund-symbols
8am, 9am, 12pm, 1pm UTC daily
Args:
token (string); Access token
| python | {
"resource": ""
} |
q254813 | otcSymbolsDF | validation | def otcSymbolsDF(token='', version=''):
'''This call returns an array of OTC symbols that IEX Cloud supports for API calls.
https://iexcloud.io/docs/api/#otc-symbols
8am, 9am, 12pm, 1pm UTC daily
Args:
token (string); Access token
version (string); API version
| python | {
"resource": ""
} |
q254814 | _getJson | validation | def _getJson(url, token='', version=''):
'''for backwards compat, accepting token and version but ignoring'''
if token:
| python | {
"resource": ""
} |
q254815 | _getJsonIEXCloud | validation | def _getJsonIEXCloud(url, token='', version='beta'):
'''for iex cloud'''
url = _URL_PREFIX2.format(version=version) + url
resp = requests.get(urlparse(url).geturl(), | python | {
"resource": ""
} |
q254816 | marketNewsDF | validation | def marketNewsDF(count=10, token='', version=''):
'''News about market
https://iexcloud.io/docs/api/#news
Continuous
Args:
count (int): limit number of results
token (string); Access token
version (string); API version
Returns:
| python | {
"resource": ""
} |
q254817 | marketOhlcDF | validation | def marketOhlcDF(token='', version=''):
'''Returns the official open and close for whole market.
https://iexcloud.io/docs/api/#news
9:30am-5pm ET Mon-Fri
Args:
token (string); Access token
version (string); API version
Returns:
DataFrame: result
'''
| python | {
"resource": ""
} |
q254818 | marketYesterdayDF | validation | def marketYesterdayDF(token='', version=''):
'''This returns previous day adjusted price data for whole market
https://iexcloud.io/docs/api/#previous-day-prices
Available after 4am ET Tue-Sat
Args:
symbol (string); Ticker to request
token (string); Access token
version (string); API version
Returns:
| python | {
"resource": ""
} |
q254819 | sectorPerformanceDF | validation | def sectorPerformanceDF(token='', version=''):
'''This returns an array of each sector and performance for the current trading day. Performance is based on each sector ETF.
https://iexcloud.io/docs/api/#sector-performance
8am-5pm ET Mon-Fri
Args:
token (string); Access token
version (string); API | python | {
"resource": ""
} |
q254820 | splitsDF | validation | def splitsDF(symbol, timeframe='ytd', token='', version=''):
'''Stock split history
https://iexcloud.io/docs/api/#splits
Updated at 9am UTC every day
Args:
symbol (string); Ticker to request
token (string); Access token
version (string); API | python | {
"resource": ""
} |
q254821 | cryptoDF | validation | def cryptoDF(token='', version=''):
'''This will return an array of quotes for all Cryptocurrencies supported by the IEX API. Each element is a standard quote object with four additional keys.
https://iexcloud.io/docs/api/#crypto
Args:
token (string); Access token
version (string); API version | python | {
"resource": ""
} |
q254822 | ToggleJupyterTensorboardApp.start | validation | def start(self):
"""Perform the App's actions as configured."""
if self.extra_args:
sys.exit('{} takes no extra arguments'.format(self.name))
else:
if self._toggle_value:
nbextensions.install_nbextension_python(
_pkg_name, overwrite=True, symlink=False,
user=self.user, sys_prefix=self.sys_prefix, prefix=None,
nbextensions_dir=None, logger=None)
else:
| python | {
"resource": ""
} |
q254823 | JupyterTensorboardApp.start | validation | def start(self):
"""Perform the App's actions as configured"""
super(JupyterTensorboardApp, self).start()
# The above should have called a subcommand | python | {
"resource": ""
} |
q254824 | _get_oauth2_client_id_and_secret | validation | def _get_oauth2_client_id_and_secret(settings_instance):
"""Initializes client id and client secret based on the settings.
Args:
settings_instance: An instance of ``django.conf.settings``.
Returns:
A 2-tuple, the first item is the client id and the second
item is the client secret.
"""
secret_json = getattr(settings_instance,
'GOOGLE_OAUTH2_CLIENT_SECRETS_JSON', None)
if secret_json is not None:
return _load_client_secrets(secret_json)
else:
client_id = getattr(settings_instance, "GOOGLE_OAUTH2_CLIENT_ID",
None)
client_secret = getattr(settings_instance,
| python | {
"resource": ""
} |
q254825 | _get_storage_model | validation | def _get_storage_model():
"""This configures whether the credentials will be stored in the session
or the Django ORM based on the settings. By default, the credentials
will be stored in the session, unless `GOOGLE_OAUTH2_STORAGE_MODEL`
is found in the settings. Usually, the ORM storage is used to integrate
credentials into an existing Django user system.
Returns:
A tuple containing three strings, or None. If
``GOOGLE_OAUTH2_STORAGE_MODEL`` is configured, the tuple
will contain the fully qualifed path of the `django.db.model`,
the name of the ``django.contrib.auth.models.User`` field on the
model, and the name of the
:class:`oauth2client.contrib.django_util.models.CredentialsField`
field on the model. If Django ORM storage is | python | {
"resource": ""
} |
q254826 | get_storage | validation | def get_storage(request):
""" Gets a Credentials storage object provided by the Django OAuth2 Helper
object.
Args:
request: Reference to the current request object.
Returns:
An :class:`oauth2.client.Storage` object.
"""
storage_model = oauth2_settings.storage_model
user_property = oauth2_settings.storage_model_user_property
credentials_property = oauth2_settings.storage_model_credentials_property
if storage_model:
module_name, class_name = storage_model.rsplit('.', 1)
module = importlib.import_module(module_name)
| python | {
"resource": ""
} |
q254827 | _redirect_with_params | validation | def _redirect_with_params(url_name, *args, **kwargs):
"""Helper method to create a redirect response with URL params.
This builds a redirect string that converts kwargs into a
query string.
Args:
url_name: The name of the url to redirect to.
kwargs: the query string param and their values to build.
| python | {
"resource": ""
} |
q254828 | _credentials_from_request | validation | def _credentials_from_request(request):
"""Gets the authorized credentials for this flow, if they exist."""
# ORM storage requires a logged in user
if (oauth2_settings.storage_model is None or
| python | {
"resource": ""
} |
q254829 | UserOAuth2.has_credentials | validation | def has_credentials(self):
"""Returns True if there are valid credentials for the current user
and required scopes."""
credentials = _credentials_from_request(self.request)
| python | {
"resource": ""
} |
q254830 | UserOAuth2._get_scopes | validation | def _get_scopes(self):
"""Returns the scopes associated with this object, kept up to
date for incremental auth."""
if _credentials_from_request(self.request):
return (self._scopes |
| python | {
"resource": ""
} |
q254831 | Storage.locked_get | validation | def locked_get(self):
"""Retrieve stored credential.
Returns:
A :class:`oauth2client.Credentials` instance or `None`.
"""
filters = {self.key_name: self.key_value}
query = self.session.query(self.model_class).filter_by(**filters)
entity = query.first()
if entity:
credential = | python | {
"resource": ""
} |
q254832 | Storage.locked_put | validation | def locked_put(self, credentials):
"""Write a credentials to the SQLAlchemy datastore.
Args:
credentials: :class:`oauth2client.Credentials`
"""
filters = {self.key_name: self.key_value}
| python | {
"resource": ""
} |
q254833 | Storage.locked_delete | validation | def locked_delete(self):
"""Delete credentials from the SQLAlchemy datastore."""
filters = {self.key_name: self.key_value}
| python | {
"resource": ""
} |
q254834 | ServiceAccountCredentials._to_json | validation | def _to_json(self, strip, to_serialize=None):
"""Utility function that creates JSON repr. of a credentials object.
Over-ride is needed since PKCS#12 keys will not in general be JSON
serializable.
Args:
strip: array, An array of names of members to exclude from the
JSON.
to_serialize: dict, (Optional) The properties for this object
| python | {
"resource": ""
} |
q254835 | ServiceAccountCredentials._from_parsed_json_keyfile | validation | def _from_parsed_json_keyfile(cls, keyfile_dict, scopes,
token_uri=None, revoke_uri=None):
"""Helper for factory constructors from JSON keyfile.
Args:
keyfile_dict: dict-like object, The parsed dictionary-like object
containing the contents of the JSON keyfile.
scopes: List or string, Scopes to use when acquiring an
access token.
token_uri: string, URI for OAuth 2.0 provider token endpoint.
If unset and not present in keyfile_dict, defaults
to Google's endpoints.
revoke_uri: string, URI for OAuth 2.0 provider revoke endpoint.
If unset and not present in keyfile_dict, defaults
to Google's endpoints.
Returns:
ServiceAccountCredentials, a credentials object created from
the keyfile contents.
Raises:
ValueError, if the credential type is not :data:`SERVICE_ACCOUNT`.
KeyError, if one of the expected keys is not present in
the keyfile.
"""
creds_type = keyfile_dict.get('type')
if creds_type != client.SERVICE_ACCOUNT:
raise ValueError('Unexpected credentials type', creds_type,
| python | {
"resource": ""
} |
q254836 | ServiceAccountCredentials.from_json_keyfile_name | validation | def from_json_keyfile_name(cls, filename, scopes='',
token_uri=None, revoke_uri=None):
"""Factory constructor from JSON keyfile by name.
Args:
filename: string, The location of the keyfile.
scopes: List or string, (Optional) Scopes to use when acquiring an
access token.
token_uri: string, URI for OAuth 2.0 provider token endpoint.
If unset and not present in the key file, defaults
to Google's endpoints.
revoke_uri: string, URI for OAuth 2.0 provider revoke endpoint.
If unset and not present in the key file, defaults
to Google's endpoints.
Returns:
ServiceAccountCredentials, a credentials object created from
the keyfile.
Raises:
ValueError, if | python | {
"resource": ""
} |
q254837 | ServiceAccountCredentials.from_json_keyfile_dict | validation | def from_json_keyfile_dict(cls, keyfile_dict, scopes='',
token_uri=None, revoke_uri=None):
"""Factory constructor from parsed JSON keyfile.
Args:
keyfile_dict: dict-like object, The parsed dictionary-like object
containing the contents of the JSON keyfile.
scopes: List or string, (Optional) Scopes to use when acquiring an
access token.
token_uri: string, URI for OAuth 2.0 provider token endpoint.
If unset and not present in keyfile_dict, defaults
to Google's endpoints.
revoke_uri: string, URI for OAuth 2.0 provider revoke endpoint.
If unset and not present in keyfile_dict, defaults
to Google's endpoints.
Returns:
ServiceAccountCredentials, a credentials object created from | python | {
"resource": ""
} |
q254838 | ServiceAccountCredentials._generate_assertion | validation | def _generate_assertion(self):
"""Generate the assertion that will be used in the request."""
now = int(time.time())
payload = {
'aud': self.token_uri,
'scope': self._scopes,
'iat': now,
'exp': now + self.MAX_TOKEN_LIFETIME_SECS,
| python | {
"resource": ""
} |
q254839 | ServiceAccountCredentials.from_json | validation | def from_json(cls, json_data):
"""Deserialize a JSON-serialized instance.
Inverse to :meth:`to_json`.
Args:
json_data: dict or string, Serialized JSON (as a string or an
already parsed dictionary) representing a credential.
Returns:
ServiceAccountCredentials from the serialized data.
"""
if not isinstance(json_data, dict):
json_data = json.loads(_helpers._from_bytes(json_data))
private_key_pkcs8_pem = None
pkcs12_val = json_data.get(_PKCS12_KEY)
password = None
if pkcs12_val is None:
private_key_pkcs8_pem = json_data['_private_key_pkcs8_pem']
signer = crypt.Signer.from_string(private_key_pkcs8_pem)
else:
# NOTE: This assumes that private_key_pkcs8_pem is not also
# in the serialized data. This would be very incorrect
# state.
pkcs12_val = base64.b64decode(pkcs12_val)
password = json_data['_private_key_password']
signer = crypt.Signer.from_string(pkcs12_val, password)
credentials = cls(
json_data['_service_account_email'],
signer,
scopes=json_data['_scopes'],
private_key_id=json_data['_private_key_id'],
| python | {
"resource": ""
} |
q254840 | ServiceAccountCredentials.create_with_claims | validation | def create_with_claims(self, claims):
"""Create credentials that specify additional claims.
Args:
claims: dict, key-value pairs for claims.
Returns:
ServiceAccountCredentials, a copy of the current service account
credentials with updated claims to use when obtaining access
tokens.
"""
new_kwargs = dict(self._kwargs)
new_kwargs.update(claims)
result = self.__class__(self._service_account_email,
self._signer,
scopes=self._scopes,
private_key_id=self._private_key_id,
client_id=self.client_id,
| python | {
"resource": ""
} |
q254841 | _JWTAccessCredentials.get_access_token | validation | def get_access_token(self, http=None, additional_claims=None):
"""Create a signed jwt.
Args:
http: unused
additional_claims: dict, additional claims to add to
the payload of the JWT.
Returns:
An AccessTokenInfo with the signed jwt
"""
if additional_claims is None:
| python | {
"resource": ""
} |
q254842 | _detect_gce_environment | validation | def _detect_gce_environment():
"""Determine if the current environment is Compute Engine.
Returns:
Boolean indicating whether or not the current environment is Google
Compute Engine.
"""
# NOTE: The explicit ``timeout`` is a workaround. The underlying
# issue is that resolving an unknown host on some networks will take
# 20-30 seconds; making this timeout short fixes the issue, but
# could lead to false negatives in the event that we are on GCE, but
# the metadata resolution was particularly slow. The latter case is
# "unlikely".
http = transport.get_http_object(timeout=GCE_METADATA_TIMEOUT)
try:
response, _ | python | {
"resource": ""
} |
q254843 | _in_gae_environment | validation | def _in_gae_environment():
"""Detects if the code is running in the App Engine environment.
Returns:
True if running in the GAE environment, False otherwise.
"""
if SETTINGS.env_name is not None:
return SETTINGS.env_name in ('GAE_PRODUCTION', 'GAE_LOCAL')
try:
import google.appengine # noqa: unused import
except ImportError:
pass
else:
| python | {
"resource": ""
} |
q254844 | _in_gce_environment | validation | def _in_gce_environment():
"""Detect if the code is running in the Compute Engine environment.
Returns:
True if running in the GCE environment, False otherwise.
| python | {
"resource": ""
} |
q254845 | _save_private_file | validation | def _save_private_file(filename, json_contents):
"""Saves a file with read-write permissions on for the owner.
Args:
filename: String. Absolute path to file.
json_contents: JSON serializable object to be saved. | python | {
"resource": ""
} |
q254846 | save_to_well_known_file | validation | def save_to_well_known_file(credentials, well_known_file=None):
"""Save the provided GoogleCredentials to the well known file.
Args:
credentials: the credentials to be saved to the well known file;
it should be an instance of GoogleCredentials
well_known_file: the name of the file where the credentials are to be
saved; this parameter is supposed to be used for
testing only
"""
# TODO(orestica): move this method to tools.py
# once the argparse import gets fixed (it is not present in Python 2.6)
| python | {
"resource": ""
} |
q254847 | _get_well_known_file | validation | def _get_well_known_file():
"""Get the well known file produced by command 'gcloud auth login'."""
# TODO(orestica): Revisit this method once gcloud provides a better way
# of pinpointing the exact location of the file.
default_config_dir = os.getenv(_CLOUDSDK_CONFIG_ENV_VAR)
if default_config_dir is None:
if os.name == 'nt':
try:
default_config_dir = os.path.join(os.environ['APPDATA'],
_CLOUDSDK_CONFIG_DIRECTORY)
except KeyError:
# This should never happen unless someone is really
# messing with things.
drive = os.environ.get('SystemDrive', 'C:')
default_config_dir = os.path.join(drive, '\\',
| python | {
"resource": ""
} |
q254848 | _get_application_default_credential_from_file | validation | def _get_application_default_credential_from_file(filename):
"""Build the Application Default Credentials from file."""
# read the credentials from the file
with open(filename) as file_obj:
client_credentials = json.load(file_obj)
credentials_type = client_credentials.get('type')
if credentials_type == AUTHORIZED_USER:
required_fields = set(['client_id', 'client_secret', 'refresh_token'])
elif credentials_type == SERVICE_ACCOUNT:
required_fields = set(['client_id', 'client_email', 'private_key_id',
'private_key'])
else:
raise ApplicationDefaultCredentialsError(
"'type' field should be defined (and have one of the '" +
AUTHORIZED_USER + "' or '" + SERVICE_ACCOUNT + "' values)")
missing_fields = required_fields.difference(client_credentials.keys())
if missing_fields:
_raise_exception_for_missing_fields(missing_fields)
| python | {
"resource": ""
} |
q254849 | verify_id_token | validation | def verify_id_token(id_token, audience, http=None,
cert_uri=ID_TOKEN_VERIFICATION_CERTS):
"""Verifies a signed JWT id_token.
This function requires PyOpenSSL and because of that it does not work on
App Engine.
Args:
id_token: string, A Signed JWT.
audience: string, The audience 'aud' that the token should be for.
http: httplib2.Http, instance to use to make the HTTP request. Callers
should supply an instance that has caching enabled.
cert_uri: string, URI of the certificates in JSON format to
verify the JWT against.
Returns:
The deserialized JSON in the JWT.
Raises:
| python | {
"resource": ""
} |
q254850 | _extract_id_token | validation | def _extract_id_token(id_token):
"""Extract the JSON payload from a JWT.
Does the extraction w/o checking the signature.
Args:
id_token: string or bytestring, OAuth 2.0 id_token.
Returns:
object, The deserialized JSON payload.
"""
if type(id_token) == bytes:
segments = id_token.split(b'.')
else:
| python | {
"resource": ""
} |
q254851 | _parse_exchange_token_response | validation | def _parse_exchange_token_response(content):
"""Parses response of an exchange token request.
Most providers return JSON but some (e.g. Facebook) return a
url-encoded string.
Args:
content: The body of a response
Returns:
Content as a dictionary object. Note that the dict could be empty,
i.e. {}. That basically indicates a failure.
"""
resp = {}
content = _helpers._from_bytes(content)
try:
resp = json.loads(content)
except Exception:
# different JSON libs raise different exceptions,
# so we | python | {
"resource": ""
} |
q254852 | credentials_from_code | validation | def credentials_from_code(client_id, client_secret, scope, code,
redirect_uri='postmessage', http=None,
user_agent=None,
token_uri=oauth2client.GOOGLE_TOKEN_URI,
auth_uri=oauth2client.GOOGLE_AUTH_URI,
revoke_uri=oauth2client.GOOGLE_REVOKE_URI,
device_uri=oauth2client.GOOGLE_DEVICE_URI,
token_info_uri=oauth2client.GOOGLE_TOKEN_INFO_URI,
pkce=False,
code_verifier=None):
"""Exchanges an authorization code for an OAuth2Credentials object.
Args:
client_id: string, client identifier.
client_secret: string, client secret.
scope: string or iterable of strings, scope(s) to request.
code: string, An authorization code, most likely passed down from
the client
redirect_uri: string, this is generally set to 'postmessage' to match
the redirect_uri that the client specified
http: httplib2.Http, optional http instance to use to do the fetch
token_uri: string, URI for token endpoint. For convenience defaults
to Google's endpoints but any OAuth 2.0 provider can be
used.
auth_uri: string, URI for authorization 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.
device_uri: string, URI for device authorization endpoint. For
convenience defaults to Google's endpoints but any OAuth
2.0 provider can be used.
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 | python | {
"resource": ""
} |
q254853 | credentials_from_clientsecrets_and_code | validation | def credentials_from_clientsecrets_and_code(filename, scope, code,
message=None,
redirect_uri='postmessage',
http=None,
cache=None,
device_uri=None):
"""Returns OAuth2Credentials from a clientsecrets file and an auth code.
Will create the right kind of Flow based on the contents of the
clientsecrets file or will raise InvalidClientSecretsError for unknown
types of Flows.
Args:
filename: string, File name of clientsecrets.
scope: string or iterable of strings, scope(s) to request.
code: string, An authorization code, most likely passed down from
the client
message: string, A friendly string to display to the user if the
clientsecrets file is missing or invalid. If message is
provided then sys.exit will be called in the case of an error.
If message in not provided then
clientsecrets.InvalidClientSecretsError will be raised.
redirect_uri: string, this is generally set to 'postmessage' to match
| python | {
"resource": ""
} |
q254854 | _oauth2_web_server_flow_params | validation | def _oauth2_web_server_flow_params(kwargs):
"""Configures redirect URI parameters for OAuth2WebServerFlow."""
params = {
'access_type': 'offline',
'response_type': 'code',
}
params.update(kwargs)
# Check for the presence of the deprecated approval_prompt param and
# warn appropriately.
approval_prompt = params.get('approval_prompt')
| python | {
"resource": ""
} |
q254855 | flow_from_clientsecrets | validation | def flow_from_clientsecrets(filename, scope, redirect_uri=None,
message=None, cache=None, login_hint=None,
device_uri=None, pkce=None, code_verifier=None,
prompt=None):
"""Create a Flow from a clientsecrets file.
Will create the right kind of Flow based on the contents of the
clientsecrets file or will raise InvalidClientSecretsError for unknown
types of Flows.
Args:
filename: string, File name of client secrets.
scope: string or iterable of strings, scope(s) to request.
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.
message: string, A friendly string to display to the user if the
clientsecrets file is missing or invalid. If message is
provided then sys.exit will be called in the case of an error.
If message in not provided then
clientsecrets.InvalidClientSecretsError will be raised.
cache: An optional cache service client that implements get() and set()
methods. See clientsecrets.loadfile() for details.
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.
Returns:
A Flow object.
Raises:
UnknownClientSecretsFlowError: if the file describes an unknown kind of
Flow.
clientsecrets.InvalidClientSecretsError: if the clientsecrets file is
invalid.
"""
try:
client_type, client_info = | python | {
"resource": ""
} |
q254856 | Credentials._to_json | validation | def _to_json(self, strip, to_serialize=None):
"""Utility function that creates JSON repr. of a Credentials object.
Args:
strip: array, An array of names of members to exclude from the
JSON.
to_serialize: dict, (Optional) The properties for this object
that will be serialized. This allows callers to
modify before serializing.
Returns:
string, a JSON representation of this instance, suitable to pass to
from_json().
"""
curr_type = self.__class__
if to_serialize is None:
to_serialize = copy.copy(self.__dict__)
else:
# Assumes it is a str->str dictionary, so we don't deep copy.
to_serialize = copy.copy(to_serialize)
for member in strip:
if member in to_serialize:
del to_serialize[member]
to_serialize['token_expiry'] = _parse_expiry(
to_serialize.get('token_expiry'))
| python | {
"resource": ""
} |
q254857 | Credentials.new_from_json | validation | def new_from_json(cls, json_data):
"""Utility class method to instantiate a Credentials subclass from JSON.
Expects the JSON string to have been produced by to_json().
Args:
json_data: string or bytes, JSON from to_json().
Returns:
An instance of the subclass of Credentials that was serialized with
to_json().
"""
json_data_as_unicode = _helpers._from_bytes(json_data)
data = json.loads(json_data_as_unicode)
# Find and call the right classmethod from_json() to restore
# the object.
module_name = data['_module']
try:
module_obj = __import__(module_name)
| python | {
"resource": ""
} |
q254858 | Storage.put | validation | def put(self, credentials):
"""Write a credential.
The Storage lock must be held when this is called.
Args:
| python | {
"resource": ""
} |
q254859 | OAuth2Credentials.has_scopes | validation | 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
| python | {
"resource": ""
} |
q254860 | OAuth2Credentials.from_json | validation | 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'],
| python | {
"resource": ""
} |
q254861 | OAuth2Credentials.access_token_expired | validation | 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:
| python | {
"resource": ""
} |
q254862 | OAuth2Credentials.get_access_token | validation | 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:
| python | {
"resource": ""
} |
q254863 | OAuth2Credentials._expires_in | validation | 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: | python | {
"resource": ""
} |
q254864 | OAuth2Credentials._generate_refresh_request_body | validation | 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,
| python | {
"resource": ""
} |
q254865 | OAuth2Credentials._refresh | validation | 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:
| python | {
"resource": ""
} |
q254866 | OAuth2Credentials._do_refresh_request | validation | 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']))
| python | {
"resource": ""
} |
q254867 | OAuth2Credentials._do_retrieve_scopes | validation | 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:
| python | {
"resource": ""
} |
q254868 | GoogleCredentials._implicit_credentials_from_files | validation | 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:
| python | {
"resource": ""
} |
q254869 | GoogleCredentials._get_implicit_credentials | validation | 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.
| python | {
"resource": ""
} |
q254870 | GoogleCredentials.from_stream | validation | 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):
| python | {
"resource": ""
} |
q254871 | DeviceFlowInfo.FromResponse | validation | 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(
| python | {
"resource": ""
} |
q254872 | OAuth2WebServerFlow.step1_get_authorize_url | validation | 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 | python | {
"resource": ""
} |
q254873 | OAuth2WebServerFlow.step1_get_device_and_user_codes | validation | 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 | python | {
"resource": ""
} |
q254874 | RsaVerifier.from_string | validation | def from_string(cls, key_pem, is_x509_cert):
"""Construct an RsaVerifier 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:
RsaVerifier instance.
Raises:
ValueError: if the key_pem can't be parsed. In either case, error
will begin with 'No PEM start marker'. If
``is_x509_cert`` | python | {
"resource": ""
} |
q254875 | RsaSigner.from_string | validation | def from_string(cls, key, password='notasecret'):
"""Construct an RsaSigner instance from a string.
Args:
key: string, private key in PEM format.
password: string, password for private key file. Unused for PEM
files.
Returns:
RsaSigner instance.
Raises:
ValueError if the key cannot be parsed as PKCS#1 or PKCS#8 in
PEM format.
"""
key = _helpers._from_bytes(key) # pem expects str in Py3
marker_id, key_bytes = pem.readPemBlocksFromFile(
six.StringIO(key), _PKCS1_MARKER, _PKCS8_MARKER)
if marker_id == 0:
pkey = rsa.key.PrivateKey.load_pkcs1(key_bytes,
format='DER')
elif marker_id == 1:
key_info, remaining = decoder.decode(
| python | {
"resource": ""
} |
q254876 | _create_file_if_needed | validation | def _create_file_if_needed(filename):
"""Creates the an empty file if it does not already exist.
Returns:
True if the file was created, False otherwise.
"""
if os.path.exists(filename):
return False
else:
# Equivalent | python | {
"resource": ""
} |
q254877 | _load_credentials_file | validation | def _load_credentials_file(credentials_file):
"""Load credentials from the given file handle.
The file is expected to be in this format:
{
"file_version": 2,
"credentials": {
"key": "base64 encoded json representation of credentials."
}
}
This function will warn and return empty credentials instead of raising
exceptions.
Args:
credentials_file: An open file handle.
Returns:
A dictionary mapping user-defined keys to an instance of
:class:`oauth2client.client.Credentials`.
"""
try:
credentials_file.seek(0)
data = json.load(credentials_file)
except Exception:
logger.warning(
'Credentials file could not be loaded, will ignore and '
'overwrite.')
return {}
if data.get('file_version') != 2:
logger.warning(
'Credentials file is not version 2, will ignore and '
'overwrite.')
| python | {
"resource": ""
} |
q254878 | _write_credentials_file | validation | def _write_credentials_file(credentials_file, credentials):
"""Writes credentials to a file.
Refer to :func:`_load_credentials_file` for the format.
Args:
credentials_file: An open file handle, must be read/write.
credentials: A dictionary mapping user-defined keys to an instance of
:class:`oauth2client.client.Credentials`.
"""
data = {'file_version': 2, 'credentials': {}}
for key, credential in iteritems(credentials):
| python | {
"resource": ""
} |
q254879 | _get_backend | validation | def _get_backend(filename):
"""A helper method to get or create a backend with thread locking.
This ensures that only one backend is used per-file per-process, so that
thread and process locks are appropriately shared.
Args:
filename: The full path to the credential storage file.
Returns:
An instance of :class:`_MultiprocessStorageBackend`.
| python | {
"resource": ""
} |
q254880 | MultiprocessFileStorage.locked_get | validation | def locked_get(self):
"""Retrieves the current credentials from the store.
Returns:
An instance of :class:`oauth2client.client.Credentials` or `None`.
"""
| python | {
"resource": ""
} |
q254881 | positional | validation | def positional(max_positional_args):
"""A decorator to declare that only the first N arguments my be positional.
This decorator makes it easy to support Python 3 style keyword-only
parameters. For example, in Python 3 it is possible to write::
def fn(pos1, *, kwonly1=None, kwonly1=None):
...
All named parameters after ``*`` must be a keyword::
fn(10, 'kw1', 'kw2') # Raises exception.
fn(10, kwonly1='kw1') # Ok.
Example
^^^^^^^
To define a function like above, do::
@positional(1)
def fn(pos1, kwonly1=None, kwonly2=None):
...
If no default value is provided to a keyword argument, it becomes a
required keyword argument::
@positional(0)
def fn(required_kw):
...
This must be called with the keyword parameter::
fn() # Raises exception.
fn(10) # Raises exception.
fn(required_kw=10) # Ok.
When defining instance or class methods always remember to account for
``self`` and ``cls``::
class MyClass(object):
@positional(2)
def my_method(self, pos1, kwonly1=None):
...
@classmethod
@positional(2)
def my_method(cls, pos1, kwonly1=None):
...
The positional decorator behavior is controlled by
``_helpers.positional_parameters_enforcement``, which may be set to
``POSITIONAL_EXCEPTION``, ``POSITIONAL_WARNING`` or
``POSITIONAL_IGNORE`` to raise an exception, log a warning, or do
nothing, respectively, if a declaration is violated.
Args:
max_positional_arguments: Maximum number of positional arguments. All
parameters after the this index must be
keyword only.
Returns:
A decorator that prevents using arguments after max_positional_args
from being used as positional parameters.
Raises:
TypeError: if a key-word only argument is provided as a positional
parameter, but only if
_helpers.positional_parameters_enforcement is set to
POSITIONAL_EXCEPTION.
"""
def positional_decorator(wrapped):
@functools.wraps(wrapped)
def | python | {
"resource": ""
} |
q254882 | string_to_scopes | validation | def string_to_scopes(scopes):
"""Converts stringifed scope value to a list.
If scopes is a list then it is simply passed through. If scopes is an
string then a list of each individual scope is returned.
Args:
scopes: a string or iterable of strings, the scopes.
Returns:
| python | {
"resource": ""
} |
q254883 | parse_unique_urlencoded | validation | def parse_unique_urlencoded(content):
"""Parses unique key-value parameters from urlencoded content.
Args:
content: string, URL-encoded key-value pairs.
Returns:
dict, The key-value pairs from ``content``.
Raises:
ValueError: if one of the keys is repeated.
"""
urlencoded_params = urllib.parse.parse_qs(content)
params = {}
for key, value in six.iteritems(urlencoded_params):
| python | {
"resource": ""
} |
q254884 | update_query_params | validation | def update_query_params(uri, params):
"""Updates a URI with new query parameters.
If a given key from ``params`` is repeated in the ``uri``, then
the URI will be considered invalid and an error will occur.
If the URI is valid, then each value from ``params`` will
replace the corresponding value in the query parameters (if
it exists).
Args:
uri: string, A valid URI, with potential existing query parameters.
params: dict, A dictionary of query parameters.
Returns:
The same URI but with the new query parameters added.
| python | {
"resource": ""
} |
q254885 | _add_query_parameter | validation | def _add_query_parameter(url, name, value):
"""Adds a query parameter to a url.
Replaces the current value if it already exists in the URL.
Args:
url: string, url to add the query parameter to.
name: string, query parameter name.
value: string, query parameter value.
Returns:
| python | {
"resource": ""
} |
q254886 | _apply_user_agent | validation | def _apply_user_agent(headers, user_agent):
"""Adds a user-agent to the headers.
Args:
headers: dict, request headers to add / modify user
agent within.
user_agent: str, the user agent to add.
Returns:
dict, the original headers passed in, but modified if the
user agent is not | python | {
"resource": ""
} |
q254887 | clean_headers | validation | def clean_headers(headers):
"""Forces header keys and values to be strings, i.e not unicode.
The httplib module just concats the header keys and values in a way that
may make the message header a unicode string, which, if it then tries to
contatenate to a binary request body may result in a unicode decode error.
Args:
headers: dict, A dictionary of headers.
Returns:
The same dictionary but with all the keys converted to strings.
"""
clean = {}
try:
for k, v in six.iteritems(headers):
if not isinstance(k, six.binary_type): | python | {
"resource": ""
} |
q254888 | wrap_http_for_auth | validation | def wrap_http_for_auth(credentials, http):
"""Prepares an HTTP object's request method for auth.
Wraps HTTP requests with logic to catch auth failures (typically
identified via a 401 status code). In the event of failure, tries
to refresh the token used and then retry the original request.
Args:
credentials: Credentials, the credentials used to identify
the authenticated user.
http: httplib2.Http, an http object to be used to make
auth requests.
"""
orig_request_method = http.request
# The closure that will replace 'httplib2.Http.request'.
def new_request(uri, method='GET', body=None, headers=None,
redirections=httplib2.DEFAULT_MAX_REDIRECTS,
connection_type=None):
if not credentials.access_token:
_LOGGER.info('Attempting refresh to obtain '
'initial access_token')
credentials._refresh(orig_request_method)
# Clone and modify the request headers to add the appropriate
# Authorization header.
headers = _initialize_headers(headers)
credentials.apply(headers) | python | {
"resource": ""
} |
q254889 | wrap_http_for_jwt_access | validation | def wrap_http_for_jwt_access(credentials, http):
"""Prepares an HTTP object's request method for JWT access.
Wraps HTTP requests with logic to catch auth failures (typically
identified via a 401 status code). In the event of failure, tries
to refresh the token used and then retry the original request.
Args:
credentials: _JWTAccessCredentials, the credentials used to identify
a service account that uses JWT access tokens.
http: httplib2.Http, an http object to be used to make
auth requests.
"""
orig_request_method = http.request
wrap_http_for_auth(credentials, http)
# The new value of ``http.request`` set by ``wrap_http_for_auth``.
authenticated_request_method = http.request
# The closure that will replace 'httplib2.Http.request'.
def new_request(uri, method='GET', body=None, headers=None,
| python | {
"resource": ""
} |
q254890 | request | validation | def request(http, uri, method='GET', body=None, headers=None,
redirections=httplib2.DEFAULT_MAX_REDIRECTS,
connection_type=None):
"""Make an HTTP request with an HTTP object and arguments.
Args:
http: httplib2.Http, an http object to be used to make requests.
uri: string, The URI to be requested.
method: string, The HTTP method to use for the request. Defaults
to 'GET'.
body: string, The payload / body in HTTP request. By default
there is no payload.
headers: dict, Key-value pairs of request headers. By default
there are no headers.
redirections: int, The number of allowed 203 redirects for
the request. Defaults to 5.
connection_type: httplib.HTTPConnection, a subclass to be used for
establishing connection. If not set, the type
will be | python | {
"resource": ""
} |
q254891 | _get_flow_for_token | validation | def _get_flow_for_token(csrf_token):
"""Retrieves the flow instance associated with a given CSRF token from
the Flask session."""
flow_pickle = session.pop(
_FLOW_KEY.format(csrf_token), None) | python | {
"resource": ""
} |
q254892 | UserOAuth2.init_app | validation | def init_app(self, app, scopes=None, client_secrets_file=None,
client_id=None, client_secret=None, authorize_callback=None,
storage=None, **kwargs):
"""Initialize this extension for the given app.
Arguments:
app: A Flask application.
scopes: Optional list of scopes to authorize.
client_secrets_file: Path to a file containing client secrets. You
can also specify the GOOGLE_OAUTH2_CLIENT_SECRETS_FILE config
value.
client_id: If not specifying a client secrets file, specify the
OAuth2 client id. You can also specify the
GOOGLE_OAUTH2_CLIENT_ID config value. You must also provide a
client secret.
client_secret: The OAuth2 client secret. You can also specify the
GOOGLE_OAUTH2_CLIENT_SECRET config value.
authorize_callback: A function that is executed after successful
user authorization.
storage: A oauth2client.client.Storage subclass for storing the
credentials. By default, this is a Flask session based storage.
| python | {
"resource": ""
} |
q254893 | UserOAuth2._load_config | validation | def _load_config(self, client_secrets_file, client_id, client_secret):
"""Loads oauth2 configuration in order of priority.
Priority:
1. Config passed to the constructor or init_app.
2. Config passed via the GOOGLE_OAUTH2_CLIENT_SECRETS_FILE app
config.
3. Config passed via the GOOGLE_OAUTH2_CLIENT_ID and
GOOGLE_OAUTH2_CLIENT_SECRET app config.
Raises:
ValueError if no config could be found.
"""
if client_id and client_secret:
self.client_id, self.client_secret = client_id, client_secret
return
if client_secrets_file:
self._load_client_secrets(client_secrets_file)
return
if 'GOOGLE_OAUTH2_CLIENT_SECRETS_FILE' in self.app.config:
self._load_client_secrets(
self.app.config['GOOGLE_OAUTH2_CLIENT_SECRETS_FILE'])
return
try:
self.client_id, self.client_secret = (
| python | {
"resource": ""
} |
q254894 | UserOAuth2.authorize_view | validation | def authorize_view(self):
"""Flask view that starts the authorization flow.
Starts flow by redirecting the user to the OAuth2 provider.
"""
args = request.args.to_dict()
# Scopes will be passed as mutliple args, and to_dict() will only
# return one. So, we use getlist() to get all of the scopes.
args['scopes'] = request.args.getlist('scopes')
| python | {
"resource": ""
} |
q254895 | UserOAuth2.callback_view | validation | def callback_view(self):
"""Flask view that handles the user's return from OAuth2 provider.
On return, exchanges the authorization code for credentials and stores
the credentials.
"""
if 'error' in request.args:
reason = request.args.get(
'error_description', request.args.get('error', ''))
reason = markupsafe.escape(reason)
return ('Authorization failed: {0}'.format(reason),
httplib.BAD_REQUEST)
try:
encoded_state = request.args['state']
server_csrf = session[_CSRF_KEY]
code = request.args['code']
except KeyError:
return 'Invalid request', httplib.BAD_REQUEST
try:
state = json.loads(encoded_state)
client_csrf = state['csrf_token']
return_url = state['return_url']
except (ValueError, KeyError):
return 'Invalid request state', httplib.BAD_REQUEST
if client_csrf != server_csrf:
return 'Invalid request state', httplib.BAD_REQUEST
flow = _get_flow_for_token(server_csrf)
if flow is None:
| python | {
"resource": ""
} |
q254896 | UserOAuth2.credentials | validation | def credentials(self):
"""The credentials for the current user or None if unavailable."""
ctx = _app_ctx_stack.top
if not hasattr(ctx, _CREDENTIALS_KEY):
| python | {
"resource": ""
} |
q254897 | UserOAuth2.has_credentials | validation | def has_credentials(self):
"""Returns True if there are valid credentials for the current user."""
if not self.credentials:
return False
| python | {
"resource": ""
} |
q254898 | UserOAuth2.email | validation | def email(self):
"""Returns the user's email address or None if there are no credentials.
The email address is provided by the current credentials' id_token.
This should not be used as unique identifier as the user can change
their email. If you need a unique identifier, use user_id.
"""
if not self.credentials:
return None
try:
| python | {
"resource": ""
} |
q254899 | get | validation | def get(http, path, root=METADATA_ROOT, recursive=None):
"""Fetch a resource from the metadata server.
Args:
http: an object to be used to make HTTP requests.
path: A string indicating the resource to retrieve. For example,
'instance/service-accounts/default'
root: A string indicating the full path to the metadata server root.
recursive: A boolean indicating whether to do a recursive query of
metadata. See
https://cloud.google.com/compute/docs/metadata#aggcontents
Returns:
A dictionary if the metadata server returns JSON, otherwise a string.
Raises:
http_client.HTTPException if an error corrured while
retrieving metadata.
"""
url = urlparse.urljoin(root, path)
url | python | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.