_id stringlengths 2 7 | title stringlengths 1 88 | partition stringclasses 3
values | text stringlengths 31 13.1k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q254900 | get_token | validation | def get_token(http, service_account='default'):
"""Fetch an oauth token for the
Args:
http: an object to be used to make HTTP requests.
service_account: An email specifying the service account this token
should represent. Default will be a token for the "default" service
account of the current compute engine instance.
| python | {
"resource": ""
} |
q254901 | xsrf_secret_key | validation | def xsrf_secret_key():
"""Return the secret key for use for XSRF protection.
If the Site entity does not have a secret key, this method will also create
one and persist it.
Returns:
The secret key.
"""
secret = memcache.get(XSRF_MEMCACHE_ID, namespace=OAUTH2CLIENT_NAMESPACE)
if not secret:
# Load the one and only instance of SiteXsrfSecretKey.
model = SiteXsrfSecretKey.get_or_insert(key_name='site')
| python | {
"resource": ""
} |
q254902 | _build_state_value | validation | def _build_state_value(request_handler, user):
"""Composes the value for the 'state' parameter.
Packs the current request URI and an XSRF token into an opaque string that
can be passed to the authentication server via the 'state' parameter.
Args:
request_handler: webapp.RequestHandler, The request.
user: google.appengine.api.users.User, The current user.
Returns:
| python | {
"resource": ""
} |
q254903 | _parse_state_value | validation | def _parse_state_value(state, user):
"""Parse the value of the 'state' parameter.
Parses the value and validates the XSRF token in the state parameter.
Args:
state: string, The value of the state parameter.
user: google.appengine.api.users.User, The current user.
Returns:
The redirect URI, or None if XSRF token is not valid.
| python | {
"resource": ""
} |
q254904 | oauth2decorator_from_clientsecrets | validation | def oauth2decorator_from_clientsecrets(filename, scope,
message=None, cache=None):
"""Creates an OAuth2Decorator populated from a clientsecrets file.
Args:
filename: string, File name of client secrets.
scope: string or list of strings, scope(s) of the credentials being
requested.
message: string, A friendly string to display to the user if the
clientsecrets file is missing or invalid. The message may
contain HTML and will be presented on the web interface for
| python | {
"resource": ""
} |
q254905 | AppAssertionCredentials.service_account_email | validation | def service_account_email(self):
"""Get the email for the current service account.
Returns:
string, The email associated with the Google App Engine
service account.
"""
if self._service_account_email is | python | {
"resource": ""
} |
q254906 | StorageByKeyName._is_ndb | validation | def _is_ndb(self):
"""Determine whether the model of the instance is an NDB model.
Returns:
Boolean indicating whether or not the model is an NDB or DB model.
"""
# issubclass will fail if one of the arguments is not a class, only
# need worry about new-style classes since ndb and db models are
# new-style
if isinstance(self._model, type): | python | {
"resource": ""
} |
q254907 | StorageByKeyName._get_entity | validation | def _get_entity(self):
"""Retrieve entity from datastore.
Uses a different model method for db or ndb models.
Returns:
Instance of the model corresponding to the current storage object
and stored using the key name of the storage object.
""" | python | {
"resource": ""
} |
q254908 | StorageByKeyName._delete_entity | validation | def _delete_entity(self):
"""Delete entity from datastore.
Attempts to delete using the key_name stored on the object, whether or
not the given key is in the datastore.
"""
if self._is_ndb():
| python | {
"resource": ""
} |
q254909 | StorageByKeyName.locked_get | validation | def locked_get(self):
"""Retrieve Credential from datastore.
Returns:
oauth2client.Credentials
"""
credentials = None
if self._cache:
json = self._cache.get(self._key_name)
if json:
credentials = client.Credentials.new_from_json(json)
if credentials is None:
entity = self._get_entity()
if entity is not None:
credentials = getattr(entity, self._property_name)
| python | {
"resource": ""
} |
q254910 | StorageByKeyName.locked_put | validation | def locked_put(self, credentials):
"""Write a Credentials to the datastore.
Args:
credentials: Credentials, the credentials to store.
"""
entity | python | {
"resource": ""
} |
q254911 | StorageByKeyName.locked_delete | validation | def locked_delete(self):
"""Delete Credential from datastore."""
if self._cache:
| python | {
"resource": ""
} |
q254912 | OAuth2Decorator.oauth_required | validation | def oauth_required(self, method):
"""Decorator that starts the OAuth 2.0 dance.
Starts the OAuth dance for the logged in user if they haven't already
granted access for this application.
Args:
method: callable, to be decorated method of a webapp.RequestHandler
instance.
"""
def check_oauth(request_handler, *args, **kwargs):
if self._in_error:
self._display_error_message(request_handler)
return
user = users.get_current_user()
# Don't use @login_decorator as this could be used in a
# POST request.
if not user:
request_handler.redirect(users.create_login_url(
request_handler.request.uri))
return
self._create_flow(request_handler)
# Store the request URI in 'state' so we can use it later
self.flow.params['state'] = _build_state_value(
request_handler, user)
| python | {
"resource": ""
} |
q254913 | OAuth2Decorator._create_flow | validation | def _create_flow(self, request_handler):
"""Create the Flow object.
The Flow is calculated lazily since we don't know where this app is
running until it receives a request, at which point redirect_uri can be
calculated and then the Flow object can be constructed.
Args:
request_handler: webapp.RequestHandler, the request handler.
"""
if self.flow is None:
redirect_uri = request_handler.request.relative_url(
self._callback_path) # Usually /oauth2callback
self.flow | python | {
"resource": ""
} |
q254914 | OAuth2Decorator.oauth_aware | validation | def oauth_aware(self, method):
"""Decorator that sets up for OAuth 2.0 dance, but doesn't do it.
Does all the setup for the OAuth dance, but doesn't initiate it.
This decorator is useful if you want to create a page that knows
whether or not the user has granted access to this application.
From within a method decorated with @oauth_aware the has_credentials()
and authorize_url() methods can be called.
Args:
method: callable, to be decorated method of a webapp.RequestHandler
instance.
"""
def setup_oauth(request_handler, *args, **kwargs):
if self._in_error:
self._display_error_message(request_handler)
return
user = users.get_current_user()
# Don't use @login_decorator as this could be used in a
# POST request.
if not user:
request_handler.redirect(users.create_login_url(
| python | {
"resource": ""
} |
q254915 | OAuth2Decorator.http | validation | def http(self, *args, **kwargs):
"""Returns an authorized http instance.
Must only be called from within an @oauth_required decorated method, or
from within an @oauth_aware decorated method where has_credentials()
returns True.
Args:
*args: Positional arguments | python | {
"resource": ""
} |
q254916 | OAuth2Decorator.callback_handler | validation | def callback_handler(self):
"""RequestHandler for the OAuth 2.0 redirect callback.
Usage::
app = webapp.WSGIApplication([
('/index', MyIndexHandler),
...,
(decorator.callback_path, decorator.callback_handler())
])
Returns:
A webapp.RequestHandler that handles the redirect back from the
server during the OAuth 2.0 dance.
"""
decorator = self
class OAuth2Handler(webapp.RequestHandler):
"""Handler for the redirect_uri of the OAuth 2.0 dance."""
@login_required
def get(self):
error = self.request.get('error')
if error:
errormsg = self.request.get('error_description', error)
self.response.out.write(
'The authorization request failed: {0}'.format(
| python | {
"resource": ""
} |
q254917 | generate_token | validation | def generate_token(key, user_id, action_id='', when=None):
"""Generates a URL-safe token for the given user, action, time tuple.
Args:
key: secret key to use.
user_id: the user ID of the authenticated user.
action_id: a string identifier of the action they requested
authorization for.
when: the time in seconds since the epoch at which the user was
| python | {
"resource": ""
} |
q254918 | validate_token | validation | def validate_token(key, token, user_id, action_id="", current_time=None):
"""Validates that the given token authorizes the user for the action.
Tokens are invalid if the time of issue is too old or if the token
does not match what generateToken outputs (i.e. the token was forged).
Args:
key: secret key to use.
token: a string of the token generated by generateToken.
user_id: the user ID of the authenticated user.
action_id: a string identifier of the action they requested
authorization for.
Returns:
A boolean - True if the user is authorized for the action, False
| python | {
"resource": ""
} |
q254919 | _validate_clientsecrets | validation | def _validate_clientsecrets(clientsecrets_dict):
"""Validate parsed client secrets from a file.
Args:
clientsecrets_dict: dict, a dictionary holding the client secrets.
Returns:
tuple, a string of the client type and the information parsed
from the file.
"""
_INVALID_FILE_FORMAT_MSG = (
'Invalid file format. See '
'https://developers.google.com/api-client-library/'
'python/guide/aaa_client_secrets')
if clientsecrets_dict is None:
raise InvalidClientSecretsError(_INVALID_FILE_FORMAT_MSG)
try:
(client_type, client_info), = clientsecrets_dict.items()
except (ValueError, AttributeError):
raise InvalidClientSecretsError(
_INVALID_FILE_FORMAT_MSG + ' '
'Expected a JSON object with a single property for a "web" or '
'"installed" application')
| python | {
"resource": ""
} |
q254920 | loadfile | validation | def loadfile(filename, cache=None):
"""Loading of client_secrets JSON file, optionally backed by a cache.
Typical cache storage would be App Engine memcache service,
but you can pass in any other cache client that implements
these methods:
* ``get(key, namespace=ns)``
* ``set(key, value, namespace=ns)``
Usage::
# without caching
client_type, client_info = loadfile('secrets.json')
# using App Engine memcache service
from google.appengine.api import memcache
client_type, client_info = loadfile('secrets.json', cache=memcache)
Args:
filename: string, Path to a client_secrets.json file on a filesystem.
cache: An optional cache service client that implements get() and set()
methods. If not specified, the file is always being loaded from
a filesystem.
Raises:
InvalidClientSecretsError: In case of a validation error or some
I/O failure. Can happen only on cache miss.
Returns:
(client_type, client_info) tuple, | python | {
"resource": ""
} |
q254921 | _SendRecv | validation | def _SendRecv():
"""Communicate with the Developer Shell server socket."""
port = int(os.getenv(DEVSHELL_ENV, 0))
if port == 0:
raise NoDevshellServer()
sock = socket.socket()
sock.connect(('localhost', port))
data = CREDENTIAL_INFO_REQUEST_JSON
msg = '{0}\n{1}'.format(len(data), data)
sock.sendall(_helpers._to_bytes(msg, encoding='utf-8'))
header = sock.recv(6).decode()
if '\n' not in header:
raise CommunicationError('saw no newline | python | {
"resource": ""
} |
q254922 | run_flow | validation | def run_flow(flow, storage, flags=None, http=None):
"""Core code for a command-line application.
The ``run()`` function is called from your application and runs
through all the steps to obtain credentials. It takes a ``Flow``
argument and attempts to open an authorization server page in the
user's default web browser. The server asks the user to grant your
application access to the user's data. If the user grants access,
the ``run()`` function returns new credentials. The new credentials
are also stored in the ``storage`` argument, which updates the file
associated with the ``Storage`` object.
It presumes it is run from a command-line application and supports the
following flags:
``--auth_host_name`` (string, default: ``localhost``)
Host name to use when running a local web server to handle
redirects during OAuth authorization.
``--auth_host_port`` (integer, default: ``[8080, 8090]``)
Port to use when running a local web server to handle redirects
during OAuth authorization. Repeat this option to specify a list
of values.
``--[no]auth_local_webserver`` (boolean, default: ``True``)
Run a local web server to handle redirects during OAuth
authorization.
The tools module defines an ``ArgumentParser`` the already contains the
flag definitions that ``run()`` requires. You can pass that
``ArgumentParser`` to your ``ArgumentParser`` constructor::
parser = argparse.ArgumentParser(
description=__doc__,
formatter_class=argparse.RawDescriptionHelpFormatter,
parents=[tools.argparser])
flags = parser.parse_args(argv)
Args:
flow: Flow, an OAuth 2.0 Flow to step through.
storage: Storage, a ``Storage`` to store the credential in.
flags: ``argparse.Namespace``, (Optional) The command-line flags. This
is the object returned from calling ``parse_args()`` on
``argparse.ArgumentParser`` as described above. Defaults
to ``argparser.parse_args()``.
http: An instance of ``httplib2.Http.request`` or something that
acts like it.
Returns:
Credentials, the obtained credential.
"""
if flags is None:
flags = argparser.parse_args()
logging.getLogger().setLevel(getattr(logging, flags.logging_level))
if not flags.noauth_local_webserver:
success = False
port_number = 0
for port in flags.auth_host_port:
port_number = port
try:
httpd = ClientRedirectServer((flags.auth_host_name, port),
| python | {
"resource": ""
} |
q254923 | ClientRedirectHandler.do_GET | validation | def do_GET(self):
"""Handle a GET request.
Parses the query parameters and prints a message
if the flow has completed. Note that we can't detect
if an error occurred.
"""
self.send_response(http_client.OK)
self.send_header('Content-type', 'text/html')
self.end_headers()
parts = urllib.parse.urlparse(self.path)
query = _helpers.parse_unique_urlencoded(parts.query)
| python | {
"resource": ""
} |
q254924 | oauth_enabled | validation | def oauth_enabled(decorated_function=None, scopes=None, **decorator_kwargs):
""" Decorator to enable OAuth Credentials if authorized, and setup
the oauth object on the request object to provide helper functions
to start the flow otherwise.
.. code-block:: python
:caption: views.py
:name: views_enabled3
from oauth2client.django_util.decorators import oauth_enabled
@oauth_enabled
def optional_oauth2(request):
if request.oauth.has_credentials():
# this could be passed into a view
# request.oauth.http is also initialized
return HttpResponse("User email: {0}".format(
request.oauth.credentials.id_token['email'])
else:
return HttpResponse('Here is an OAuth Authorize link:
<a href="{0}">Authorize</a>'.format(
request.oauth.get_authorize_redirect()))
Args:
decorated_function: View function to decorate.
scopes: Scopes to require, will default.
decorator_kwargs: Can include ``return_url`` to specify the URL to
return to after OAuth2 authorization is complete.
Returns:
The | python | {
"resource": ""
} |
q254925 | code_verifier | validation | def code_verifier(n_bytes=64):
"""
Generates a 'code_verifier' as described in section 4.1 of RFC 7636.
This is a 'high-entropy cryptographic random string' that will be
impractical for an attacker to guess.
Args:
n_bytes: integer between 31 and 96, inclusive. default: 64
number of bytes of entropy to include in verifier.
Returns:
Bytestring, representing urlsafe base64-encoded random data.
"""
verifier = base64.urlsafe_b64encode(os.urandom(n_bytes)).rstrip(b'=')
| python | {
"resource": ""
} |
q254926 | code_challenge | validation | def code_challenge(verifier):
"""
Creates a 'code_challenge' as described in section 4.2 of RFC 7636
by taking the sha256 hash of the verifier and then urlsafe
base64-encoding it.
Args:
verifier: bytestring, representing a code_verifier as generated by
code_verifier().
Returns:
Bytestring, representing | python | {
"resource": ""
} |
q254927 | AppAssertionCredentials._retrieve_info | validation | def _retrieve_info(self, http):
"""Retrieves service account info for invalid credentials.
Args:
http: an object to be used to make HTTP requests.
"""
if self.invalid:
info = _metadata.get_service_account_info(
http,
| python | {
"resource": ""
} |
q254928 | DjangoORMStorage.locked_get | validation | def locked_get(self):
"""Retrieve stored credential from the Django ORM.
Returns:
oauth2client.Credentials retrieved from the Django ORM, associated
with the ``model``, ``key_value``->``key_name`` pair used to query
for the model, and ``property_name`` identifying the
``CredentialsProperty`` field, all of which | python | {
"resource": ""
} |
q254929 | DjangoORMStorage.locked_put | validation | def locked_put(self, credentials):
"""Write a Credentials to the Django datastore.
Args:
credentials: Credentials, the credentials to store.
"""
entity, _ = self.model_class.objects.get_or_create(
| python | {
"resource": ""
} |
q254930 | DjangoORMStorage.locked_delete | validation | def locked_delete(self):
"""Delete Credentials from the datastore."""
| python | {
"resource": ""
} |
q254931 | DictionaryStorage.locked_get | validation | def locked_get(self):
"""Retrieve the credentials from the dictionary, if they exist.
Returns: A :class:`oauth2client.client.OAuth2Credentials` instance.
"""
serialized = self._dictionary.get(self._key)
if serialized is None:
| python | {
"resource": ""
} |
q254932 | DictionaryStorage.locked_put | validation | def locked_put(self, credentials):
"""Save the credentials to the dictionary.
Args:
credentials: A :class:`oauth2client.client.OAuth2Credentials`
instance.
| python | {
"resource": ""
} |
q254933 | FlowNDBProperty._validate | validation | def _validate(self, value):
"""Validates a value as a proper Flow object.
Args:
value: A value to be set on the property.
Raises:
TypeError if the value is not an instance of Flow.
"""
_LOGGER.info('validate: Got type %s', type(value))
if value is | python | {
"resource": ""
} |
q254934 | CredentialsNDBProperty._from_base_type | validation | def _from_base_type(self, value):
"""Converts our stored JSON string back to the desired type.
Args:
value: A value from the datastore to be converted to the
desired type.
Returns:
A deserialized Credentials (or subclass) object, else None if
the value can't be parsed.
"""
if not value:
return None
try:
| python | {
"resource": ""
} |
q254935 | _get_flow_for_token | validation | def _get_flow_for_token(csrf_token, request):
""" Looks up the flow in session to recover information about requested
scopes.
Args:
csrf_token: The token passed in the callback request that should
match the one previously generated and stored in the request on the
initial authorization view.
Returns:
| python | {
"resource": ""
} |
q254936 | oauth2_callback | validation | def oauth2_callback(request):
""" View that handles the user's return from OAuth2 provider.
This view verifies the CSRF state and OAuth authorization code, and on
success stores the credentials obtained in the storage provider,
and redirects to the return_url specified in the authorize view and
stored in the session.
Args:
request: Django request.
Returns:
A redirect response back to the return_url.
"""
if 'error' in request.GET:
reason = request.GET.get(
'error_description', request.GET.get('error', ''))
reason = html.escape(reason)
return http.HttpResponseBadRequest(
'Authorization failed {0}'.format(reason))
try:
encoded_state = request.GET['state']
code = request.GET['code']
except KeyError:
return http.HttpResponseBadRequest(
'Request missing state or authorization code')
try:
server_csrf = request.session[_CSRF_KEY]
except KeyError:
return http.HttpResponseBadRequest(
'No existing session for this flow.')
try:
state = json.loads(encoded_state)
client_csrf = state['csrf_token']
return_url = state['return_url']
except (ValueError, KeyError):
return http.HttpResponseBadRequest('Invalid state parameter.')
if client_csrf != | python | {
"resource": ""
} |
q254937 | oauth2_authorize | validation | def oauth2_authorize(request):
""" View to start the OAuth2 Authorization flow.
This view starts the OAuth2 authorization flow. If scopes is passed in
as a GET URL parameter, it will authorize those scopes, otherwise the
default scopes specified in settings. The return_url can also be
specified as a GET parameter, otherwise the referer header will be
checked, and if that isn't found it will return to the root path.
Args:
request: The Django request object.
Returns:
A redirect to Google OAuth2 Authorization.
"""
return_url = request.GET.get('return_url', None)
if not return_url:
return_url = request.META.get('HTTP_REFERER', '/')
scopes = request.GET.getlist('scopes', django_util.oauth2_settings.scopes)
# Model storage (but not session storage) requires a logged in user
if django_util.oauth2_settings.storage_model:
if not request.user.is_authenticated():
return | python | {
"resource": ""
} |
q254938 | Storage._create_file_if_needed | validation | def _create_file_if_needed(self):
"""Create an empty file if necessary.
This method will not initialize the file. Instead it implements a
simple version of "touch" to ensure the file has been created.
"""
if not os.path.exists(self._filename):
| python | {
"resource": ""
} |
q254939 | CredentialsField.get_prep_value | validation | def get_prep_value(self, value):
"""Overrides ``models.Field`` method. This is used to convert
the value from an instances of this class to bytes that can be
inserted into the database.
"""
if value is None: | python | {
"resource": ""
} |
q254940 | CredentialsField.value_to_string | validation | def value_to_string(self, obj):
"""Convert the field value from the provided model to a string.
Used during model serialization.
Args:
obj: db.Model, model object
Returns: | python | {
"resource": ""
} |
q254941 | make_signed_jwt | validation | def make_signed_jwt(signer, payload, key_id=None):
"""Make a signed JWT.
See http://self-issued.info/docs/draft-jones-json-web-token.html.
Args:
signer: crypt.Signer, Cryptographic signer.
payload: dict, Dictionary of data to convert to JSON and then sign.
key_id: string, (Optional) Key ID header.
Returns:
string, The JWT for the payload.
"""
header = {'typ': 'JWT', 'alg': 'RS256'}
if key_id is not None:
header['kid'] = key_id
segments = [
_helpers._urlsafe_b64encode(_helpers._json_encode(header)),
| python | {
"resource": ""
} |
q254942 | _verify_signature | validation | def _verify_signature(message, signature, certs):
"""Verifies signed content using a list of certificates.
Args:
message: string or bytes, The message to verify.
signature: string or bytes, The signature on the message.
certs: iterable, certificates in PEM format.
Raises:
AppIdentityError: If none of the certificates can verify the message
against the signature.
"""
for pem in certs:
| python | {
"resource": ""
} |
q254943 | _check_audience | validation | def _check_audience(payload_dict, audience):
"""Checks audience field from a JWT payload.
Does nothing if the passed in ``audience`` is null.
Args:
payload_dict: dict, A dictionary containing a JWT payload.
audience: string or NoneType, an audience to check for in
the JWT payload.
Raises:
AppIdentityError: If there is no ``'aud'`` field in the payload
dictionary but there is an ``audience`` to check.
AppIdentityError: If the ``'aud'`` field in the payload dictionary
| python | {
"resource": ""
} |
q254944 | _verify_time_range | validation | def _verify_time_range(payload_dict):
"""Verifies the issued at and expiration from a JWT payload.
Makes sure the current time (in UTC) falls between the issued at and
expiration for the JWT (with some skew allowed for via
``CLOCK_SKEW_SECS``).
Args:
payload_dict: dict, A dictionary containing a JWT payload.
Raises:
AppIdentityError: If there is no ``'iat'`` field in the payload
dictionary.
AppIdentityError: If there is no ``'exp'`` field in the payload
dictionary.
AppIdentityError: If the JWT expiration is too far in the future (i.e.
if the expiration would imply a token lifetime
longer than what is allowed.)
AppIdentityError: If the token appears to have been issued in the
future (up to clock skew).
AppIdentityError: If the token appears to have expired in the past
(up to clock skew).
"""
# Get the current time to use throughout.
now = int(time.time())
# Make sure issued at and expiration are in the payload.
issued_at = payload_dict.get('iat')
if issued_at is None:
raise AppIdentityError(
'No iat field in token: {0}'.format(payload_dict))
expiration = payload_dict.get('exp')
if | python | {
"resource": ""
} |
q254945 | verify_signed_jwt_with_certs | validation | def verify_signed_jwt_with_certs(jwt, certs, audience=None):
"""Verify a JWT against public certs.
See http://self-issued.info/docs/draft-jones-json-web-token.html.
Args:
jwt: string, A JWT.
certs: dict, Dictionary where values of public keys in PEM format.
audience: string, The audience, 'aud', that this JWT should contain. If
None then the JWT's 'aud' parameter is not verified.
Returns:
dict, The deserialized JSON payload in the JWT.
Raises:
AppIdentityError: if any checks are failed.
"""
jwt = _helpers._to_bytes(jwt)
if jwt.count(b'.') != 2:
raise AppIdentityError(
'Wrong number of segments in token: {0}'.format(jwt))
header, payload, signature = jwt.split(b'.')
message_to_sign = header + b'.' + payload
signature = _helpers._urlsafe_b64decode(signature) | python | {
"resource": ""
} |
q254946 | Templates.get | validation | def get(self, template_id, **queryparams):
"""
Get information about a specific template.
:param template_id: The unique id for the template.
:type template_id: :py:class:`str`
| python | {
"resource": ""
} |
q254947 | Templates.update | validation | def update(self, template_id, data):
"""
Update the name, HTML, or folder_id of an existing template.
:param template_id: The unique id for the template.
:type template_id: :py:class:`str`
:param data: The request body parameters
:type data: :py:class:`dict`
data = {
"name": string*,
"html": string*
}
"""
if 'name' not in data:
| python | {
"resource": ""
} |
q254948 | Templates.delete | validation | def delete(self, template_id):
"""
Delete a specific template.
:param template_id: The unique id for the template.
:type template_id: :py:class:`str`
| python | {
"resource": ""
} |
q254949 | get_subscriber_hash | validation | def get_subscriber_hash(member_email):
"""
The MD5 hash of the lowercase version of the list member's email.
Used as subscriber_hash
:param member_email: The member's email address | python | {
"resource": ""
} |
q254950 | check_url | validation | def check_url(url):
"""
Function that verifies that the string passed is a valid url.
Original regex author Diego Perini (http://www.iport.it)
regex ported to Python by adamrofer (https://github.com/adamrofer)
Used under MIT license.
:param url:
:return: Nothing
"""
URL_REGEX = re.compile(
u"^"
u"(?:(?:https?|ftp)://)"
u"(?:\S+(?::\S*)?@)?"
u"(?:"
u"(?!(?:10|127)(?:\.\d{1,3}){3})"
| python | {
"resource": ""
} |
q254951 | merge_results | validation | def merge_results(x, y):
"""
Given two dicts, x and y, merge them into a new dict as a shallow copy.
The result only differs from `x.update(y)` in the way that it handles list
values when both x and y have list values for the same key. In which case
the returned dictionary, z, has a value according to:
z[key] = x[key] + z[key]
:param x: The first dictionary
:type x: :py:class:`dict`
:param | python | {
"resource": ""
} |
q254952 | Lists.create | validation | def create(self, data):
"""
Create a new list in your MailChimp account.
:param data: The request body parameters
:type data: :py:class:`dict`
data = {
"name": string*,
"contact": object*
{
"company": string*,
"address1": string*,
"city": string*,
"state": string*,
"zip": string*,
"country": string*
},
"permission_reminder": string*,
"campaign_defaults": object*
{
"from_name": string*,
"from_email": string*,
"subject": string*,
"language": string*
},
"email_type_option": boolean
}
"""
if 'name' not in data:
raise KeyError('The list must have a name')
if 'contact' not in data:
raise KeyError('The list must have a contact')
if 'company' not in data['contact']:
raise KeyError('The list contact must have a company')
if 'address1' not in data['contact']:
raise KeyError('The list contact must have a address1')
if 'city' not in data['contact']:
raise KeyError('The list contact must have a city')
if 'state' not in data['contact']:
raise KeyError('The list contact must have a state')
if 'zip' not in data['contact']:
raise KeyError('The list contact must have a zip')
if 'country' not in data['contact']:
raise KeyError('The list contact must have a country')
| python | {
"resource": ""
} |
q254953 | Lists.update_members | validation | def update_members(self, list_id, data):
"""
Batch subscribe or unsubscribe list members.
Only the members array is required in the request body parameters.
Within the members array, each member requires an email_address
and either a status or status_if_new. The update_existing parameter
will also be considered required to help prevent accidental updates
to existing members and will default to false if not present.
:param list_id: The unique id for the list.
:type list_id: :py:class:`str`
:param data: The request body parameters
:type data: :py:class:`dict`
data = {
"members": array*
[
{
"email_address": string*,
"status": string* (Must be one of 'subscribed', 'unsubscribed', 'cleaned', or 'pending'),
"status_if_new": string* (Must be one of 'subscribed', 'unsubscribed', 'cleaned', or 'pending')
}
| python | {
"resource": ""
} |
q254954 | Lists.update | validation | def update(self, list_id, data):
"""
Update the settings for a specific list.
:param list_id: The unique id for the list.
:type list_id: :py:class:`str`
:param data: The request body parameters
:type data: :py:class:`dict`
data = {
"name": string*,
"contact": object*
{
"company": string*,
"address1": string*,
"city": string*,
"state": string*,
"zip": string*,
"country": string*
},
"permission_reminder": string*,
"campaign_defaults": object*
{
"from_name": string*,
"from_email": string*,
"subject": string*,
"language": string*
},
"email_type_option": boolean
}
"""
self.list_id = list_id
if 'name' not in data:
raise KeyError('The list must have a name')
if 'contact' not in data:
raise KeyError('The list must have a contact')
if 'company' not in data['contact']:
raise KeyError('The list contact must have a company')
if 'address1' not in data['contact']:
raise KeyError('The list contact must have a address1')
if 'city' not in data['contact']:
raise KeyError('The list contact must have a city')
if 'state' not in data['contact']:
raise KeyError('The list contact must have a state')
if 'zip' not in data['contact']:
raise KeyError('The list contact must have a zip')
| python | {
"resource": ""
} |
q254955 | StoreOrderLines.create | validation | def create(self, store_id, order_id, data):
"""
Add a new line item to an existing order.
:param store_id: The store id.
:type store_id: :py:class:`str`
:param order_id: The id for the order in a store.
:type order_id: :py:class:`str`
:param data: The request body parameters
:type data: :py:class:`dict`
data = {
"id": string*,
"product_id": string*,
"product_variant_id": string*,
"quantity": integer*,
"price": number*
}
| python | {
"resource": ""
} |
q254956 | Root.get | validation | def get(self, **queryparams):
"""
Get links to all other resources available in the API.
:param queryparams: The query string parameters
queryparams['fields'] = []
| python | {
"resource": ""
} |
q254957 | AuthorizedApps.create | validation | def create(self, data):
"""
Retrieve OAuth2-based credentials to associate API calls with your
application.
:param data: The request body parameters
:type data: :py:class:`dict`
data = {
"client_id": string*,
"client_secret": string*
}
"""
self.app_id = None
if 'client_id' not in data:
raise KeyError('The authorized app | python | {
"resource": ""
} |
q254958 | AuthorizedApps.get | validation | def get(self, app_id, **queryparams):
"""
Get information about a specific authorized application
:param app_id: The unique id for the connected authorized application
:type app_id: :py:class:`str`
:param queryparams: The query string parameters
queryparams['fields'] = []
| python | {
"resource": ""
} |
q254959 | StorePromoRules.create | validation | def create(self, store_id, data):
"""
Add new promo rule to a store
:param store_id: The store id
:type store_id: :py:class:`str`
:param data: The request body parameters
:type data: :py:class:`dict'
data = {
"id": string*,
"title": string,
"description": string*,
"starts_at": string,
"ends_at": string,
"amount": number*,
"type": string*,
"target": string*,
"enabled": boolean,
"created_at_foreign": string,
"updated_at_foreign": string,
}
"""
self.store_id = store_id
if 'id' not in data:
raise KeyError('The promo rule must have an id')
if 'description' not in data:
raise KeyError('This promo rule must have a description')
if | python | {
"resource": ""
} |
q254960 | CampaignFolders.get | validation | def get(self, folder_id, **queryparams):
"""
Get information about a specific folder used to organize campaigns.
:param folder_id: The unique id for the campaign folder.
:type folder_id: :py:class:`str`
:param queryparams: The query string parameters
queryparams['fields'] = []
| python | {
"resource": ""
} |
q254961 | AutomationEmails.get | validation | def get(self, workflow_id, email_id):
"""
Get information about an individual Automation workflow email.
:param workflow_id: The unique id for the Automation workflow.
:type workflow_id: :py:class:`str`
:param email_id: The unique id for the Automation workflow email.
:type email_id: :py:class:`str`
| python | {
"resource": ""
} |
q254962 | FileManagerFiles.create | validation | def create(self, data):
"""
Upload a new image or file to the File Manager.
:param data: The request body parameters
:type data: :py:class:`dict`
data = {
"name": string*,
"file_data": string*
}
"""
if 'name' not in data:
raise KeyError('The file must have a name')
if 'file_data' not in data:
raise KeyError('The file must have file_data')
| python | {
"resource": ""
} |
q254963 | FileManagerFiles.get | validation | def get(self, file_id, **queryparams):
"""
Get information about a specific file in the File Manager.
:param file_id: The unique id for the File Manager file.
:type file_id: :py:class:`str` | python | {
"resource": ""
} |
q254964 | FileManagerFiles.update | validation | def update(self, file_id, data):
"""
Update a file in the File Manager.
:param file_id: The unique id for the File Manager file.
:type file_id: :py:class:`str`
:param data: The request body parameters
:type data: :py:class:`dict`
data = {
"name": string*,
"file_data": string*
}
"""
self.file_id = file_id
| python | {
"resource": ""
} |
q254965 | FileManagerFiles.delete | validation | def delete(self, file_id):
"""
Remove a specific file from the File Manager.
:param file_id: The unique id for | python | {
"resource": ""
} |
q254966 | BaseApi._build_path | validation | def _build_path(self, *args):
"""
Build path with endpoint and args
:param args: Tokens in the endpoint URL
:type args: :py:class:`unicode`
| python | {
"resource": ""
} |
q254967 | BaseApi._iterate | validation | def _iterate(self, url, **queryparams):
"""
Iterate over all pages for the given url. Feed in the result of self._build_path as the url.
:param url: The url of the endpoint
:type url: :py:class:`str`
:param queryparams: The query string parameters
queryparams['fields'] = []
queryparams['exclude_fields'] = []
queryparams['count'] = integer
queryparams['offset'] = integer
"""
# fields as a query string parameter should be a string with
# comma-separated substring values to pass along to
# self._mc_client._get(). It should also contain total_items whenever
# the parameter is employed, which is forced here.
| python | {
"resource": ""
} |
q254968 | AutomationRemovedSubscribers.all | validation | def all(self, workflow_id):
"""
Get information about subscribers who were removed from an Automation
workflow.
:param workflow_id: The unique | python | {
"resource": ""
} |
q254969 | ListWebhooks.create | validation | def create(self, list_id, data):
"""
Create a new webhook for a specific list.
The documentation does not include any required request body
parameters but the url parameter is being listed here as a required
parameter in documentation and error-checking based on the description
of the method
:param list_id: The unique id for the list.
:type list_id: :py:class:`str`
:param data: The request body parameters
:type data: :py:class:`dict`
data = {
"url": string*
}
| python | {
"resource": ""
} |
q254970 | ListWebhooks.get | validation | def get(self, list_id, webhook_id):
"""
Get information about a specific webhook.
:param list_id: The unique id for the list.
:type list_id: :py:class:`str`
:param webhook_id: The unique id for the webhook.
:type webhook_id: :py:class:`str`
""" | python | {
"resource": ""
} |
q254971 | ListWebhooks.update | validation | def update(self, list_id, webhook_id, data):
"""
Update the settings for an existing webhook.
:param list_id: The unique id for the list
:type list_id: :py:class:`str`
:param webhook_id: The unique id for the webhook
:type webhook_id: :py:class:`str`
""" | python | {
"resource": ""
} |
q254972 | ListWebhooks.delete | validation | def delete(self, list_id, webhook_id):
"""
Delete a specific webhook in a list.
:param list_id: The unique id for the list.
:type list_id: :py:class:`str`
:param webhook_id: The unique id for the webhook.
:type webhook_id: :py:class:`str`
""" | python | {
"resource": ""
} |
q254973 | Segments.all | validation | def all(self, list_id, **queryparams):
"""
returns the first 10 segments for a specific list.
"""
| python | {
"resource": ""
} |
q254974 | Segments.get | validation | def get(self, list_id, segment_id):
"""
returns the specified list segment.
"""
| python | {
"resource": ""
} |
q254975 | Segments.update | validation | def update(self, list_id, segment_id, data):
"""
updates an existing list segment.
"""
| python | {
"resource": ""
} |
q254976 | Segments.delete | validation | def delete(self, list_id, segment_id):
"""
removes an existing list segment from the list. This cannot be undone.
"""
| python | {
"resource": ""
} |
q254977 | Segments.create | validation | def create(self, list_id, data):
"""
adds a new segment to the list.
"""
| python | {
"resource": ""
} |
q254978 | MailChimpClient._post | validation | def _post(self, url, data=None):
"""
Handle authenticated POST requests
:param url: The url for the endpoint including path parameters
:type url: :py:class:`str`
:param data: The request body parameters
:type data: :py:data:`none` or :py:class:`dict`
:returns: The JSON output from the API or an error message
"""
url = urljoin(self.base_url, url)
try:
r = self._make_request(**dict(
method='POST',
url=url,
json=data,
auth=self.auth,
timeout=self.timeout,
hooks=self.request_hooks,
headers=self.request_headers
))
except requests.exceptions.RequestException as e:
raise e
| python | {
"resource": ""
} |
q254979 | MailChimpOAuth.get_metadata | validation | def get_metadata(self):
"""
Get the metadata returned after authentication
"""
try:
r = requests.get('https://login.mailchimp.com/oauth2/metadata', auth=self)
except requests.exceptions.RequestException as e:
raise e
else:
| python | {
"resource": ""
} |
q254980 | CampaignContent.update | validation | def update(self, campaign_id, data):
"""
Set the content for a campaign.
:param campaign_id: The unique id for the campaign.
:type campaign_id: :py:class:`str`
:param data: The request body parameters
:type data: :py:class:`dict`
"""
| python | {
"resource": ""
} |
q254981 | Conversations.get | validation | def get(self, conversation_id, **queryparams):
"""
Get details about an individual conversation.
:param conversation_id: The unique id for the conversation.
:type conversation_id: :py:class:`str`
| python | {
"resource": ""
} |
q254982 | ReportUnsubscribes.all | validation | def all(self, campaign_id, get_all=False, **queryparams):
"""
Get information about members who have unsubscribed from a specific
campaign.
:param campaign_id: The unique id for the campaign.
:type campaign_id: :py:class:`str`
:param get_all: Should the query get all results
:type get_all: :py:class:`bool`
:param queryparams: The query string parameters
queryparams['fields'] = []
queryparams['exclude_fields'] = []
queryparams['count'] = integer
queryparams['offset'] = integer
"""
| python | {
"resource": ""
} |
q254983 | AutomationEmailQueues.create | validation | def create(self, workflow_id, email_id, data):
"""
Manually add a subscriber to a workflow, bypassing the default trigger
settings. You can also use this endpoint to trigger a series of
automated emails in an API 3.0 workflow type or add subscribers to an
automated email queue that uses the API request delay type.
:param workflow_id: The unique id for the Automation workflow.
:type workflow_id: :py:class:`str`
:param email_id: The unique id for the Automation workflow email.
| python | {
"resource": ""
} |
q254984 | AutomationEmailQueues.all | validation | def all(self, workflow_id, email_id):
"""
Get information about an Automation email queue.
:param workflow_id: The unique id for the Automation workflow.
:type workflow_id: :py:class:`str`
:param email_id: The unique id for the Automation workflow email.
:type email_id: :py:class:`str`
| python | {
"resource": ""
} |
q254985 | AutomationEmailQueues.get | validation | def get(self, workflow_id, email_id, subscriber_hash):
"""
Get information about a specific subscriber in an Automation email
queue.
:param workflow_id: The unique id for the Automation workflow.
:type workflow_id: :py:class:`str`
:param email_id: The unique id for the Automation workflow email.
:type email_id: :py:class:`str`
:param subscriber_hash: The MD5 hash of the lowercase version of the
list member’s email address.
:type subscriber_hash: :py:class:`str`
"""
subscriber_hash | python | {
"resource": ""
} |
q254986 | CampaignActions.cancel | validation | def cancel(self, campaign_id):
"""
Cancel a Regular or Plain-Text Campaign after you send, before all of
your recipients receive it. This feature is included with MailChimp
Pro.
:param campaign_id: The unique id for the campaign.
:type | python | {
"resource": ""
} |
q254987 | CampaignActions.pause | validation | def pause(self, campaign_id):
"""
Pause an RSS-Driven campaign.
:param campaign_id: The unique id for the campaign.
| python | {
"resource": ""
} |
q254988 | CampaignActions.replicate | validation | def replicate(self, campaign_id):
"""
Replicate a campaign in saved or send status.
:param campaign_id: The unique id for | python | {
"resource": ""
} |
q254989 | CampaignActions.resume | validation | def resume(self, campaign_id):
"""
Resume an RSS-Driven campaign.
:param campaign_id: The unique id for the campaign.
| python | {
"resource": ""
} |
q254990 | CampaignActions.send | validation | def send(self, campaign_id):
"""
Send a MailChimp campaign. For RSS Campaigns, the campaign will send
according to its schedule. All other campaigns will send immediately.
:param campaign_id: The unique id for the campaign.
:type campaign_id: :py:class:`str`
| python | {
"resource": ""
} |
q254991 | StoreCustomers.create | validation | def create(self, store_id, data):
"""
Add a new customer to a store.
:param store_id: The store id.
:type store_id: :py:class:`str`
:param data: The request body parameters
:type data: :py:class:`dict`
data = {
"id": string*,
"email_address": string*,
"opt_in_status": boolean*
}
"""
self.store_id = store_id
if 'id' not in data:
raise KeyError('The store customer must have an id')
if 'email_address' not in data:
raise KeyError('The store customer must have an email_address')
check_email(data['email_address'])
if 'opt_in_status' not in data:
| python | {
"resource": ""
} |
q254992 | StoreCustomers.get | validation | def get(self, store_id, customer_id, **queryparams):
"""
Get information about a specific customer.
:param store_id: The store id.
:type store_id: :py:class:`str`
:param customer_id: The id for the customer of a store.
:type customer_id: :py:class:`str`
:param queryparams: The query string parameters
queryparams['fields'] = | python | {
"resource": ""
} |
q254993 | StoreCustomers.create_or_update | validation | def create_or_update(self, store_id, customer_id, data):
"""
Add or update a customer.
:param store_id: The store id.
:type store_id: :py:class:`str`
:param customer_id: The id for the customer of a store.
:type customer_id: :py:class:`str`
:param data: The request body parameters
:type data: :py:class:`dict`
data = {
"id": string*,
"email_address": string*,
"opt_in_status": boolean
}
"""
self.store_id = store_id
self.customer_id = customer_id
if 'id' not in data:
raise KeyError('The store customer must have an | python | {
"resource": ""
} |
q254994 | StoreProductVariants.create_or_update | validation | def create_or_update(self, store_id, product_id, variant_id, data):
"""
Add or update a product variant.
:param store_id: The store id.
:type store_id: :py:class:`str`
:param product_id: The id for the product of a store.
:type product_id: :py:class:`str`
:param variant_id: The id for the product variant.
:type variant_id: :py:class:`str`
:param data: The request body parameters
| python | {
"resource": ""
} |
q254995 | CampaignFeedback.create | validation | def create(self, campaign_id, data, **queryparams):
"""
Add feedback on a specific campaign.
:param campaign_id: The unique id for the campaign.
:type campaign_id: :py:class:`str`
:param data: The request body parameters
:type data: :py:class:`dict`
data = {
"message": string*
}
:param queryparams: The query string parameters
queryparams['fields'] = []
queryparams['exclude_fields'] = []
"""
self.campaign_id = campaign_id
if 'message' not in data:
raise | python | {
"resource": ""
} |
q254996 | CampaignFeedback.update | validation | def update(self, campaign_id, feedback_id, data):
"""
Update a specific feedback message for a campaign.
:param campaign_id: The unique id for the campaign.
:type campaign_id: :py:class:`str`
:param feedback_id: The unique id for the feedback message.
:type feedback_id: :py:class:`str`
:param data: The request body parameters
:type data: :py:class:`dict`
data = {
"message": string*
}
"""
| python | {
"resource": ""
} |
q254997 | ListMergeFields.create | validation | def create(self, list_id, data):
"""
Add a new merge field for a specific list.
:param list_id: The unique id for the list.
:type list_id: :py:class:`str`
:param data: The request body parameters
:type data: :py:class:`dict`
data = {
"name": string*,
"type": string*
}
"""
self.list_id = list_id
if 'name' not in data:
raise KeyError('The list merge field must have a name')
if 'type' | python | {
"resource": ""
} |
q254998 | ListMergeFields.get | validation | def get(self, list_id, merge_id):
"""
Get information about a specific merge field in a list.
:param list_id: The unique id for the list.
:type list_id: :py:class:`str`
:param merge_id: The id for the merge field.
:type merge_id: :py:class:`str`
| python | {
"resource": ""
} |
q254999 | BatchWebhooks.get | validation | def get(self, batch_webhook_id, **queryparams):
"""
Get information about a specific batch webhook.
:param batch_webhook_id: The unique id for the batch webhook.
:type batch_webhook_id: :py:class:`str`
| python | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.