_id
stringlengths
2
7
title
stringlengths
1
88
partition
stringclasses
3 values
text
stringlengths
75
19.8k
language
stringclasses
1 value
meta_information
dict
q25100
safe_delete
train
def safe_delete(filename): """Delete a file safely. If it's not present, no-op.""" try: os.unlink(filename) except OSError as e: if e.errno != errno.ENOENT: raise
python
{ "resource": "" }
q25101
chmod_plus_x
train
def chmod_plus_x(path): """Equivalent of unix `chmod a+x path`""" path_mode = os.stat(path).st_mode path_mode &= int('777', 8) if path_mode & stat.S_IRUSR: path_mode |= stat.S_IXUSR if path_mode & stat.S_IRGRP: path_mode |= stat.S_IXGRP if path_mode & stat.S_IROTH: path_mode |= stat.S_IXOTH os.chmod(path, path_mode)
python
{ "resource": "" }
q25102
chmod_plus_w
train
def chmod_plus_w(path): """Equivalent of unix `chmod +w path`""" path_mode = os.stat(path).st_mode path_mode &= int('777', 8) path_mode |= stat.S_IWRITE os.chmod(path, path_mode)
python
{ "resource": "" }
q25103
Chroot.clone
train
def clone(self, into=None): """Clone this chroot. :keyword into: (optional) An optional destination directory to clone the Chroot into. If not specified, a temporary directory will be created. .. versionchanged:: 0.8 The temporary directory created when ``into`` is not specified is now garbage collected on interpreter exit. """ into = into or safe_mkdtemp() new_chroot = Chroot(into) for label, fileset in self.filesets.items(): for fn in fileset: new_chroot.link(os.path.join(self.chroot, fn), fn, label=label) return new_chroot
python
{ "resource": "" }
q25104
Chroot.files
train
def files(self): """Get all files in the chroot.""" all_files = set() for label in self.filesets: all_files.update(self.filesets[label]) return all_files
python
{ "resource": "" }
q25105
PEX._scan_pth_files
train
def _scan_pth_files(dir_paths): """Given an iterable of directory paths, yield paths to all .pth files within.""" for dir_path in dir_paths: if not os.path.exists(dir_path): continue pth_filenames = (f for f in os.listdir(dir_path) if f.endswith('.pth')) for pth_filename in pth_filenames: yield os.path.join(dir_path, pth_filename)
python
{ "resource": "" }
q25106
PEX.minimum_sys_modules
train
def minimum_sys_modules(cls, site_libs, modules=None): """Given a set of site-packages paths, return a "clean" sys.modules. When importing site, modules within sys.modules have their __path__'s populated with additional paths as defined by *-nspkg.pth in site-packages, or alternately by distribution metadata such as *.dist-info/namespace_packages.txt. This can possibly cause namespace packages to leak into imports despite being scrubbed from sys.path. NOTE: This method mutates modules' __path__ attributes in sys.modules, so this is currently an irreversible operation. """ modules = modules or sys.modules new_modules = {} for module_name, module in modules.items(): # builtins can stay if not hasattr(module, '__path__'): new_modules[module_name] = module continue # Unexpected objects, e.g. PEP 420 namespace packages, should just be dropped. if not isinstance(module.__path__, list): TRACER.log('Dropping %s' % (module_name,), V=3) continue # Pop off site-impacting __path__ elements in-place. for k in reversed(range(len(module.__path__))): if cls._tainted_path(module.__path__[k], site_libs): TRACER.log('Scrubbing %s.__path__: %s' % (module_name, module.__path__[k]), V=3) module.__path__.pop(k) # It still contains path elements not in site packages, so it can stay in sys.modules if module.__path__: new_modules[module_name] = module return new_modules
python
{ "resource": "" }
q25107
PEX.minimum_sys
train
def minimum_sys(cls, inherit_path): """Return the minimum sys necessary to run this interpreter, a la python -S. :returns: (sys.path, sys.path_importer_cache, sys.modules) tuple of a bare python installation. """ site_libs = set(cls.site_libs()) for site_lib in site_libs: TRACER.log('Found site-library: %s' % site_lib) for extras_path in cls._extras_paths(): TRACER.log('Found site extra: %s' % extras_path) site_libs.add(extras_path) site_libs = set(os.path.normpath(path) for path in site_libs) sys_path, sys_path_importer_cache = cls.minimum_sys_path(site_libs, inherit_path) sys_modules = cls.minimum_sys_modules(site_libs) return sys_path, sys_path_importer_cache, sys_modules
python
{ "resource": "" }
q25108
PEX.patch_pkg_resources
train
def patch_pkg_resources(cls, working_set): """Patch pkg_resources given a new working set.""" pkg_resources.working_set = working_set pkg_resources.require = working_set.require pkg_resources.iter_entry_points = working_set.iter_entry_points pkg_resources.run_script = pkg_resources.run_main = working_set.run_script pkg_resources.add_activation_listener = working_set.subscribe
python
{ "resource": "" }
q25109
PEX.patch_sys
train
def patch_sys(self, inherit_path): """Patch sys with all site scrubbed.""" def patch_dict(old_value, new_value): old_value.clear() old_value.update(new_value) def patch_all(path, path_importer_cache, modules): sys.path[:] = path patch_dict(sys.path_importer_cache, path_importer_cache) patch_dict(sys.modules, modules) new_sys_path, new_sys_path_importer_cache, new_sys_modules = self.minimum_sys(inherit_path) new_sys_path.extend(merge_split(self._pex_info.pex_path, self._vars.PEX_PATH)) patch_all(new_sys_path, new_sys_path_importer_cache, new_sys_modules)
python
{ "resource": "" }
q25110
PEX.execute
train
def execute(self): """Execute the PEX. This function makes assumptions that it is the last function called by the interpreter. """ teardown_verbosity = self._vars.PEX_TEARDOWN_VERBOSE try: pex_inherit_path = self._vars.PEX_INHERIT_PATH if pex_inherit_path == "false": pex_inherit_path = self._pex_info.inherit_path self.patch_sys(pex_inherit_path) working_set = self._activate() self.patch_pkg_resources(working_set) exit_code = self._wrap_coverage(self._wrap_profiling, self._execute) if exit_code: sys.exit(exit_code) except Exception: # Allow the current sys.excepthook to handle this app exception before we tear things down in # finally, then reraise so that the exit status is reflected correctly. sys.excepthook(*sys.exc_info()) raise except SystemExit as se: # Print a SystemExit error message, avoiding a traceback in python3. # This must happen here, as sys.stderr is about to be torn down if not isinstance(se.code, int) and se.code is not None: print(se.code, file=sys.stderr) raise finally: # squash all exceptions on interpreter teardown -- the primary type here are # atexit handlers failing to run because of things such as: # http://stackoverflow.com/questions/2572172/referencing-other-modules-in-atexit if not teardown_verbosity: sys.stderr.flush() sys.stderr = DevNull() sys.excepthook = lambda *a, **kw: None
python
{ "resource": "" }
q25111
PEX.cmdline
train
def cmdline(self, args=()): """The commandline to run this environment. :keyword args: Additional arguments to be passed to the application being invoked by the environment. """ cmds = [self._interpreter.binary] cmds.append(self._pex) cmds.extend(args) return cmds
python
{ "resource": "" }
q25112
PEX.run
train
def run(self, args=(), with_chroot=False, blocking=True, setsid=False, **kwargs): """Run the PythonEnvironment in an interpreter in a subprocess. :keyword args: Additional arguments to be passed to the application being invoked by the environment. :keyword with_chroot: Run with cwd set to the environment's working directory. :keyword blocking: If true, return the return code of the subprocess. If false, return the Popen object of the invoked subprocess. :keyword setsid: If true, run the PEX in a separate operating system session. Remaining keyword arguments are passed directly to subprocess.Popen. """ self.clean_environment() cmdline = self.cmdline(args) TRACER.log('PEX.run invoking %s' % ' '.join(cmdline)) process = Executor.open_process(cmdline, cwd=self._pex if with_chroot else os.getcwd(), preexec_fn=os.setsid if setsid else None, stdin=kwargs.pop('stdin', None), stdout=kwargs.pop('stdout', None), stderr=kwargs.pop('stderr', None), **kwargs) return process.wait() if blocking else process
python
{ "resource": "" }
q25113
urlsafe_b64decode
train
def urlsafe_b64decode(data): """urlsafe_b64decode without padding""" pad = b'=' * (4 - (len(data) & 3)) return base64.urlsafe_b64decode(data + pad)
python
{ "resource": "" }
q25114
Compiler.compile
train
def compile(self, root, relpaths): """Compiles the given python source files using this compiler's interpreter. :param string root: The root path all the source files are found under. :param list relpaths: The realtive paths from the `root` of the source files to compile. :returns: A list of relative paths of the compiled bytecode files. :raises: A :class:`Compiler.Error` if there was a problem bytecode compiling any of the files. """ with named_temporary_file() as fp: fp.write(to_bytes(_COMPILER_MAIN % {'root': root, 'relpaths': relpaths}, encoding='utf-8')) fp.flush() try: out, _ = Executor.execute([self._interpreter.binary, '-sE', fp.name]) except Executor.NonZeroExit as e: raise self.CompilationFailure( 'encountered %r during bytecode compilation.\nstderr was:\n%s\n' % (e, e.stderr) ) return out.splitlines()
python
{ "resource": "" }
q25115
crypto_sign
train
def crypto_sign(msg, sk): """Return signature+message given message and secret key. The signature is the first SIGNATUREBYTES bytes of the return value. A copy of msg is in the remainder.""" if len(sk) != SECRETKEYBYTES: raise ValueError("Bad signing key length %d" % len(sk)) vkbytes = sk[PUBLICKEYBYTES:] skbytes = sk[:PUBLICKEYBYTES] sig = djbec.signature(msg, skbytes, vkbytes) return sig + msg
python
{ "resource": "" }
q25116
crypto_sign_open
train
def crypto_sign_open(signed, vk): """Return message given signature+message and the verifying key.""" if len(vk) != PUBLICKEYBYTES: raise ValueError("Bad verifying key length %d" % len(vk)) rc = djbec.checkvalid(signed[:SIGNATUREBYTES], signed[SIGNATUREBYTES:], vk) if not rc: raise ValueError("rc != True", rc) return signed[SIGNATUREBYTES:]
python
{ "resource": "" }
q25117
Bootstrap.locate
train
def locate(cls): """Locates the active PEX bootstrap. :rtype: :class:`Bootstrap` """ if cls._INSTANCE is None: bootstrap_path = __file__ module_import_path = __name__.split('.') # For example, our __file__ might be requests.pex/.bootstrap/pex/bootstrap.pyc and our import # path pex.bootstrap; so we walk back through all the module components of our import path to # find the base sys.path entry where we were found (requests.pex/.bootstrap in this example). for _ in module_import_path: bootstrap_path = os.path.dirname(bootstrap_path) cls._INSTANCE = cls(sys_path_entry=bootstrap_path) return cls._INSTANCE
python
{ "resource": "" }
q25118
Bootstrap.demote
train
def demote(self): """Demote the bootstrap code to the end of the `sys.path` so it is found last. :return: The list of un-imported bootstrap modules. :rtype: list of :class:`types.ModuleType` """ import sys # Grab a hold of `sys` early since we'll be un-importing our module in this process. unimported_modules = [] for name, module in reversed(sorted(sys.modules.items())): if self.imported_from_bootstrap(module): unimported_modules.append(sys.modules.pop(name)) sys.path[:] = [path for path in sys.path if os.path.realpath(path) != self._realpath] sys.path.append(self._sys_path_entry) return unimported_modules
python
{ "resource": "" }
q25119
Bootstrap.imported_from_bootstrap
train
def imported_from_bootstrap(self, module): """Return ``True`` if the given ``module`` object was imported from bootstrap code. :param module: The module to check the provenance of. :type module: :class:`types.ModuleType` :rtype: bool """ # A vendored module. path = getattr(module, '__file__', None) if path and os.path.realpath(path).startswith(self._realpath): return True # A vendored package. path = getattr(module, '__path__', None) if path and any(os.path.realpath(path_item).startswith(self._realpath) for path_item in path): return True return False
python
{ "resource": "" }
q25120
maybe_reexec_pex
train
def maybe_reexec_pex(compatibility_constraints): """ Handle environment overrides for the Python interpreter to use when executing this pex. This function supports interpreter filtering based on interpreter constraints stored in PEX-INFO metadata. If PEX_PYTHON is set in a pexrc, it attempts to obtain the binary location of the interpreter specified by PEX_PYTHON. If PEX_PYTHON_PATH is set, it attempts to search the path for a matching interpreter in accordance with the interpreter constraints. If both variables are present in a pexrc, this function gives precedence to PEX_PYTHON_PATH and errors out if no compatible interpreters can be found on said path. If neither variable is set, we fall back to plain PEX execution using PATH searching or the currently executing interpreter. If compatibility constraints are used, we match those constraints against these interpreters. :param compatibility_constraints: list of requirements-style strings that constrain the Python interpreter to re-exec this pex with. """ if os.environ.pop('SHOULD_EXIT_BOOTSTRAP_REEXEC', None): # We've already been here and selected an interpreter. Continue to execution. return target = None with TRACER.timed('Selecting runtime interpreter based on pexrc', V=3): if ENV.PEX_PYTHON and not ENV.PEX_PYTHON_PATH: # preserve PEX_PYTHON re-exec for backwards compatibility # TODO: Kill this off completely in favor of PEX_PYTHON_PATH # https://github.com/pantsbuild/pex/issues/431 target = _select_pex_python_interpreter(ENV.PEX_PYTHON, compatibility_constraints=compatibility_constraints) elif ENV.PEX_PYTHON_PATH: target = _select_interpreter(pex_python_path=ENV.PEX_PYTHON_PATH, compatibility_constraints=compatibility_constraints) elif compatibility_constraints: # Apply constraints to target using regular PATH target = _select_interpreter(compatibility_constraints=compatibility_constraints) if target and os.path.realpath(target) != os.path.realpath(sys.executable): cmdline = [target] + sys.argv TRACER.log('Re-executing: cmdline="%s", sys.executable="%s", PEX_PYTHON="%s", ' 'PEX_PYTHON_PATH="%s", COMPATIBILITY_CONSTRAINTS="%s"' % (cmdline, sys.executable, ENV.PEX_PYTHON, ENV.PEX_PYTHON_PATH, compatibility_constraints)) ENV.delete('PEX_PYTHON') ENV.delete('PEX_PYTHON_PATH') os.environ['SHOULD_EXIT_BOOTSTRAP_REEXEC'] = '1' os.execve(target, cmdline, ENV.copy())
python
{ "resource": "" }
q25121
bootstrap_pex_env
train
def bootstrap_pex_env(entry_point): """Bootstrap the current runtime environment using a given pex.""" pex_info = _bootstrap(entry_point) from .environment import PEXEnvironment PEXEnvironment(entry_point, pex_info).activate()
python
{ "resource": "" }
q25122
make_relative_to_root
train
def make_relative_to_root(path): """Update options so that defaults are user relative to specified pex_root.""" return os.path.normpath(path.format(pex_root=ENV.PEX_ROOT))
python
{ "resource": "" }
q25123
parse_info
train
def parse_info(wininfo_name, egginfo_name): """Extract metadata from filenames. Extracts the 4 metadataitems needed (name, version, pyversion, arch) from the installer filename and the name of the egg-info directory embedded in the zipfile (if any). The egginfo filename has the format:: name-ver(-pyver)(-arch).egg-info The installer filename has the format:: name-ver.arch(-pyver).exe Some things to note: 1. The installer filename is not definitive. An installer can be renamed and work perfectly well as an installer. So more reliable data should be used whenever possible. 2. The egg-info data should be preferred for the name and version, because these come straight from the distutils metadata, and are mandatory. 3. The pyver from the egg-info data should be ignored, as it is constructed from the version of Python used to build the installer, which is irrelevant - the installer filename is correct here (even to the point that when it's not there, any version is implied). 4. The architecture must be taken from the installer filename, as it is not included in the egg-info data. 5. Architecture-neutral installers still have an architecture because the installer format itself (being executable) is architecture-specific. We should therefore ignore the architecture if the content is pure-python. """ egginfo = None if egginfo_name: egginfo = egg_info_re.search(egginfo_name) if not egginfo: raise ValueError("Egg info filename %s is not valid" % (egginfo_name,)) # Parse the wininst filename # 1. Distribution name (up to the first '-') w_name, sep, rest = wininfo_name.partition('-') if not sep: raise ValueError("Installer filename %s is not valid" % (wininfo_name,)) # Strip '.exe' rest = rest[:-4] # 2. Python version (from the last '-', must start with 'py') rest2, sep, w_pyver = rest.rpartition('-') if sep and w_pyver.startswith('py'): rest = rest2 w_pyver = w_pyver.replace('.', '') else: # Not version specific - use py2.py3. While it is possible that # pure-Python code is not compatible with both Python 2 and 3, there # is no way of knowing from the wininst format, so we assume the best # here (the user can always manually rename the wheel to be more # restrictive if needed). w_pyver = 'py2.py3' # 3. Version and architecture w_ver, sep, w_arch = rest.rpartition('.') if not sep: raise ValueError("Installer filename %s is not valid" % (wininfo_name,)) if egginfo: w_name = egginfo.group('name') w_ver = egginfo.group('ver') return {'name': w_name, 'ver': w_ver, 'arch': w_arch, 'pyver': w_pyver}
python
{ "resource": "" }
q25124
StripeDecimalCurrencyAmountField.stripe_to_db
train
def stripe_to_db(self, data): """Convert the raw value to decimal representation.""" val = data.get(self.name) # Note: 0 is a possible return value, which is 'falseish' if val is not None: return val / decimal.Decimal("100")
python
{ "resource": "" }
q25125
StripeDateTimeField.stripe_to_db
train
def stripe_to_db(self, data): """Convert the raw timestamp value to a DateTime representation.""" val = data.get(self.name) # Note: 0 is a possible return value, which is 'falseish' if val is not None: return convert_tstamp(val)
python
{ "resource": "" }
q25126
WebhookEventTrigger.from_request
train
def from_request(cls, request): """ Create, validate and process a WebhookEventTrigger given a Django request object. The process is three-fold: 1. Create a WebhookEventTrigger object from a Django request. 2. Validate the WebhookEventTrigger as a Stripe event using the API. 3. If valid, process it into an Event object (and child resource). """ headers = fix_django_headers(request.META) assert headers try: body = request.body.decode(request.encoding or "utf-8") except Exception: body = "(error decoding body)" ip = request.META.get("REMOTE_ADDR") if ip is None: warnings.warn( "Could not determine remote IP (missing REMOTE_ADDR). " "This is likely an issue with your wsgi/server setup." ) ip = "0.0.0.0" obj = cls.objects.create(headers=headers, body=body, remote_ip=ip) try: obj.valid = obj.validate() if obj.valid: if djstripe_settings.WEBHOOK_EVENT_CALLBACK: # If WEBHOOK_EVENT_CALLBACK, pass it for processing djstripe_settings.WEBHOOK_EVENT_CALLBACK(obj) else: # Process the item (do not save it, it'll get saved below) obj.process(save=False) except Exception as e: max_length = WebhookEventTrigger._meta.get_field("exception").max_length obj.exception = str(e)[:max_length] obj.traceback = format_exc() # Send the exception as the webhook_processing_error signal webhook_processing_error.send( sender=WebhookEventTrigger, exception=e, data=getattr(e, "http_body", "") ) # re-raise the exception so Django sees it raise e finally: obj.save() return obj
python
{ "resource": "" }
q25127
WebhookEventTrigger.validate
train
def validate(self, api_key=None): """ The original contents of the Event message must be confirmed by refetching it and comparing the fetched data with the original data. This function makes an API call to Stripe to redownload the Event data and returns whether or not it matches the WebhookEventTrigger data. """ local_data = self.json_body if "id" not in local_data or "livemode" not in local_data: return False if self.is_test_event: logger.info("Test webhook received: {}".format(local_data)) return False if djstripe_settings.WEBHOOK_VALIDATION is None: # validation disabled return True elif ( djstripe_settings.WEBHOOK_VALIDATION == "verify_signature" and djstripe_settings.WEBHOOK_SECRET ): try: stripe.WebhookSignature.verify_header( self.body, self.headers.get("stripe-signature"), djstripe_settings.WEBHOOK_SECRET, djstripe_settings.WEBHOOK_TOLERANCE, ) except stripe.error.SignatureVerificationError: return False else: return True livemode = local_data["livemode"] api_key = api_key or djstripe_settings.get_default_api_key(livemode) # Retrieve the event using the api_version specified in itself with stripe_temporary_api_version(local_data["api_version"], validate=False): remote_data = Event.stripe_class.retrieve(id=local_data["id"], api_key=api_key) return local_data["data"] == remote_data["data"]
python
{ "resource": "" }
q25128
Card.remove
train
def remove(self): """ Removes a card from this customer's account. """ # First, wipe default source on all customers that use this card. Customer.objects.filter(default_source=self.id).update(default_source=None) try: self._api_delete() except InvalidRequestError as exc: if "No such source:" in str(exc) or "No such customer:" in str(exc): # The exception was thrown because the stripe customer or card was already # deleted on the stripe side, ignore the exception pass else: # The exception was raised for another reason, re-raise it raise self.delete()
python
{ "resource": "" }
q25129
Source.detach
train
def detach(self): """ Detach the source from its customer. """ # First, wipe default source on all customers that use this. Customer.objects.filter(default_source=self.id).update(default_source=None) try: # TODO - we could use the return value of sync_from_stripe_data # or call its internals - self._sync/_attach_objects_hook etc here # to update `self` at this point? self.sync_from_stripe_data(self.api_retrieve().detach()) return True except (InvalidRequestError, NotImplementedError): # The source was already detached. Resyncing. # NotImplementedError is an artifact of stripe-python<2.0 # https://github.com/stripe/stripe-python/issues/376 self.sync_from_stripe_data(self.api_retrieve()) return False
python
{ "resource": "" }
q25130
CustomerSubscriptionStatusListFilter.lookups
train
def lookups(self, request, model_admin): """ Return a list of tuples. The first element in each tuple is the coded value for the option that will appear in the URL query. The second element is the human-readable name for the option that will appear in the right sidebar. source: https://docs.djangoproject.com/en/1.10/ref/contrib/admin/#django.contrib.admin.ModelAdmin.list_filter """ statuses = [ [x, x.replace("_", " ").title()] for x in models.Subscription.objects.values_list("status", flat=True).distinct() ] statuses.append(["none", "No Subscription"]) return statuses
python
{ "resource": "" }
q25131
handler
train
def handler(*event_types): """ Decorator that registers a function as a webhook handler. Functions can be registered for event types (e.g. 'customer') or fully qualified event sub-types (e.g. 'customer.subscription.deleted'). If an event type is specified, the handler will receive callbacks for ALL webhook events of that type. For example, if 'customer' is specified, the handler will receive events for 'customer.subscription.created', 'customer.subscription.updated', etc. :param event_types: The event type(s) that should be handled. :type event_types: str. """ def decorator(func): for event_type in event_types: registrations[event_type].append(func) return func return decorator
python
{ "resource": "" }
q25132
handler_all
train
def handler_all(func=None): """ Decorator that registers a function as a webhook handler for ALL webhook events. Handles all webhooks regardless of event type or sub-type. """ if not func: return functools.partial(handler_all) registrations_global.append(func) return func
python
{ "resource": "" }
q25133
check_stripe_api_version
train
def check_stripe_api_version(app_configs=None, **kwargs): """Check the user has configured API version correctly.""" from . import settings as djstripe_settings messages = [] default_version = djstripe_settings.DEFAULT_STRIPE_API_VERSION version = djstripe_settings.get_stripe_api_version() if not validate_stripe_api_version(version): msg = "Invalid Stripe API version: {}".format(version) hint = "STRIPE_API_VERSION should be formatted as: YYYY-MM-DD" messages.append(checks.Critical(msg, hint=hint, id="djstripe.C004")) if version != default_version: msg = ( "The Stripe API version has a non-default value of '{}'. " "Non-default versions are not explicitly supported, and may " "cause compatibility issues.".format(version) ) hint = "Use the dj-stripe default for Stripe API version: {}".format(default_version) messages.append(checks.Warning(msg, hint=hint, id="djstripe.W001")) return messages
python
{ "resource": "" }
q25134
check_native_jsonfield_postgres_engine
train
def check_native_jsonfield_postgres_engine(app_configs=None, **kwargs): """ Check that the DJSTRIPE_USE_NATIVE_JSONFIELD isn't set unless Postgres is in use. """ from . import settings as djstripe_settings messages = [] error_msg = "DJSTRIPE_USE_NATIVE_JSONFIELD is not compatible with engine {engine} for database {name}" if djstripe_settings.USE_NATIVE_JSONFIELD: for db_name, db_config in settings.DATABASES.items(): # Hi there. # You may be reading this because you are using Postgres, but # dj-stripe is not detecting that correctly. For example, maybe you # are using multiple databases with different engines, or you have # your own backend. As long as you are certain you can support jsonb, # you can use the SILENCED_SYSTEM_CHECKS setting to ignore this check. engine = db_config.get("ENGINE", "") if "postgresql" not in engine and "postgis" not in engine: messages.append( checks.Critical( error_msg.format(name=repr(db_name), engine=repr(engine)), hint="Switch to Postgres, or unset DJSTRIPE_USE_NATIVE_JSONFIELD", id="djstripe.C005", ) ) return messages
python
{ "resource": "" }
q25135
check_stripe_api_host
train
def check_stripe_api_host(app_configs=None, **kwargs): """ Check that STRIPE_API_HOST is not being used in production. """ from django.conf import settings messages = [] if not settings.DEBUG and hasattr(settings, "STRIPE_API_HOST"): messages.append( checks.Warning( "STRIPE_API_HOST should not be set in production! This is most likely unintended.", hint="Remove STRIPE_API_HOST from your Django settings.", id="djstripe.W002", ) ) return messages
python
{ "resource": "" }
q25136
check_webhook_secret
train
def check_webhook_secret(app_configs=None, **kwargs): """ Check that DJSTRIPE_WEBHOOK_SECRET looks correct """ from . import settings as djstripe_settings messages = [] secret = djstripe_settings.WEBHOOK_SECRET if secret and not secret.startswith("whsec_"): messages.append( checks.Warning( "DJSTRIPE_WEBHOOK_SECRET does not look valid", hint="It should start with whsec_...", id="djstripe.W003", ) ) return messages
python
{ "resource": "" }
q25137
check_webhook_validation
train
def check_webhook_validation(app_configs=None, **kwargs): """ Check that DJSTRIPE_WEBHOOK_VALIDATION is valid """ from . import settings as djstripe_settings messages = [] validation_options = ("verify_signature", "retrieve_event") if djstripe_settings.WEBHOOK_VALIDATION is None: messages.append( checks.Warning( "Webhook validation is disabled, this is a security risk if the webhook view is enabled", hint="Set DJSTRIPE_WEBHOOK_VALIDATION to one of {}".format( ", ".join(validation_options) ), id="djstripe.W004", ) ) elif djstripe_settings.WEBHOOK_VALIDATION == "verify_signature": if not djstripe_settings.WEBHOOK_SECRET: messages.append( checks.Critical( "DJSTRIPE_WEBHOOK_VALIDATION='verify_signature' but DJSTRIPE_WEBHOOK_SECRET is not set", hint="Set DJSTRIPE_WEBHOOK_SECRET or set DJSTRIPE_WEBHOOK_VALIDATION='retrieve_event'", id="djstripe.C006", ) ) elif djstripe_settings.WEBHOOK_VALIDATION not in validation_options: messages.append( checks.Critical( "DJSTRIPE_WEBHOOK_VALIDATION is invalid", hint="Set DJSTRIPE_WEBHOOK_VALIDATION to one of {} or None".format( ", ".join(validation_options) ), id="djstripe.C007", ) ) return messages
python
{ "resource": "" }
q25138
check_subscriber_key_length
train
def check_subscriber_key_length(app_configs=None, **kwargs): """ Check that DJSTRIPE_SUBSCRIBER_CUSTOMER_KEY fits in metadata. Docs: https://stripe.com/docs/api#metadata """ from . import settings as djstripe_settings messages = [] key = djstripe_settings.SUBSCRIBER_CUSTOMER_KEY key_size = len(str(key)) if key and key_size > 40: messages.append( checks.Error( "DJSTRIPE_SUBSCRIBER_CUSTOMER_KEY must be no more than 40 characters long", hint="Current value: %r (%i characters)" % (key, key_size), id="djstripe.E001", ) ) return messages
python
{ "resource": "" }
q25139
Command.handle
train
def handle(self, *args, **options): """Call sync_from_stripe_data for each plan returned by api_list.""" for plan_data in Plan.api_list(): plan = Plan.sync_from_stripe_data(plan_data) print("Synchronized plan {0}".format(plan.id))
python
{ "resource": "" }
q25140
subscriber_has_active_subscription
train
def subscriber_has_active_subscription(subscriber, plan=None): """ Helper function to check if a subscriber has an active subscription. Throws improperlyConfigured if the subscriber is an instance of AUTH_USER_MODEL and get_user_model().is_anonymous == True. Activate subscription rules (or): * customer has active subscription If the subscriber is an instance of AUTH_USER_MODEL, active subscription rules (or): * customer has active subscription * user.is_superuser * user.is_staff :param subscriber: The subscriber for which to check for an active subscription. :type subscriber: dj-stripe subscriber :param plan: The plan for which to check for an active subscription. If plan is None and there exists only one subscription, this method will check if that subscription is active. Calling this method with no plan and multiple subscriptions will throw an exception. :type plan: Plan or string (plan ID) """ if isinstance(subscriber, AnonymousUser): raise ImproperlyConfigured(ANONYMOUS_USER_ERROR_MSG) if isinstance(subscriber, get_user_model()): if subscriber.is_superuser or subscriber.is_staff: return True from .models import Customer customer, created = Customer.get_or_create(subscriber) if created or not customer.has_active_subscription(plan): return False return True
python
{ "resource": "" }
q25141
get_supported_currency_choices
train
def get_supported_currency_choices(api_key): """ Pull a stripe account's supported currencies and returns a choices tuple of those supported currencies. :param api_key: The api key associated with the account from which to pull data. :type api_key: str """ import stripe stripe.api_key = api_key account = stripe.Account.retrieve() supported_payment_currencies = stripe.CountrySpec.retrieve(account["country"])[ "supported_payment_currencies" ] return [(currency, currency.upper()) for currency in supported_payment_currencies]
python
{ "resource": "" }
q25142
PaymentsContextMixin.get_context_data
train
def get_context_data(self, **kwargs): """Inject STRIPE_PUBLIC_KEY and plans into context_data.""" context = super().get_context_data(**kwargs) context.update( { "STRIPE_PUBLIC_KEY": djstripe_settings.STRIPE_PUBLIC_KEY, "plans": Plan.objects.all(), } ) return context
python
{ "resource": "" }
q25143
SubscriptionMixin.get_context_data
train
def get_context_data(self, *args, **kwargs): """Inject is_plans_plural and customer into context_data.""" context = super().get_context_data(**kwargs) context["is_plans_plural"] = Plan.objects.count() > 1 context["customer"], _created = Customer.get_or_create( subscriber=djstripe_settings.subscriber_request_callback(self.request) ) context["subscription"] = context["customer"].subscription return context
python
{ "resource": "" }
q25144
Invoice.retry
train
def retry(self): """ Retry payment on this invoice if it isn't paid, closed, or forgiven.""" if not self.paid and not self.forgiven and not self.closed: stripe_invoice = self.api_retrieve() updated_stripe_invoice = ( stripe_invoice.pay() ) # pay() throws an exception if the charge is not successful. type(self).sync_from_stripe_data(updated_stripe_invoice) return True return False
python
{ "resource": "" }
q25145
Invoice.status
train
def status(self): """ Attempts to label this invoice with a status. Note that an invoice can be more than one of the choices. We just set a priority on which status appears. """ if self.paid: return self.STATUS_PAID if self.forgiven: return self.STATUS_FORGIVEN if self.closed: return self.STATUS_CLOSED return self.STATUS_OPEN
python
{ "resource": "" }
q25146
Invoice.plan
train
def plan(self): """ Gets the associated plan for this invoice. In order to provide a consistent view of invoices, the plan object should be taken from the first invoice item that has one, rather than using the plan associated with the subscription. Subscriptions (and their associated plan) are updated by the customer and represent what is current, but invoice items are immutable within the invoice and stay static/unchanged. In other words, a plan retrieved from an invoice item will represent the plan as it was at the time an invoice was issued. The plan retrieved from the subscription will be the currently active plan. :returns: The associated plan for the invoice. :rtype: ``djstripe.Plan`` """ for invoiceitem in self.invoiceitems.all(): if invoiceitem.plan: return invoiceitem.plan if self.subscription: return self.subscription.plan
python
{ "resource": "" }
q25147
Plan.get_or_create
train
def get_or_create(cls, **kwargs): """ Get or create a Plan.""" try: return Plan.objects.get(id=kwargs["id"]), False except Plan.DoesNotExist: return cls.create(**kwargs), True
python
{ "resource": "" }
q25148
Plan.update_name
train
def update_name(self): """ Update the name of the Plan in Stripe and in the db. Assumes the object being called has the name attribute already reset, but has not been saved. Stripe does not allow for update of any other Plan attributes besides name. """ p = self.api_retrieve() p.name = self.name p.save() self.save()
python
{ "resource": "" }
q25149
Subscription.extend
train
def extend(self, delta): """ Extends this subscription by the provided delta. :param delta: The timedelta by which to extend this subscription. :type delta: timedelta """ if delta.total_seconds() < 0: raise ValueError("delta must be a positive timedelta.") if self.trial_end is not None and self.trial_end > timezone.now(): period_end = self.trial_end else: period_end = self.current_period_end period_end += delta return self.update(prorate=False, trial_end=period_end)
python
{ "resource": "" }
q25150
Subscription.cancel
train
def cancel(self, at_period_end=djstripe_settings.CANCELLATION_AT_PERIOD_END): """ Cancels this subscription. If you set the at_period_end parameter to true, the subscription will remain active until the end of the period, at which point it will be canceled and not renewed. By default, the subscription is terminated immediately. In either case, the customer will not be charged again for the subscription. Note, however, that any pending invoice items that you've created will still be charged for at the end of the period unless manually deleted. If you've set the subscription to cancel at period end, any pending prorations will also be left in place and collected at the end of the period, but if the subscription is set to cancel immediately, pending prorations will be removed. By default, all unpaid invoices for the customer will be closed upon subscription cancellation. We do this in order to prevent unexpected payment retries once the customer has canceled a subscription. However, you can reopen the invoices manually after subscription cancellation to have us proceed with automatic retries, or you could even re-attempt payment yourself on all unpaid invoices before allowing the customer to cancel the subscription at all. :param at_period_end: A flag that if set to true will delay the cancellation of the subscription until the end of the current period. Default is False. :type at_period_end: boolean .. important:: If a subscription is cancelled during a trial period, the ``at_period_end`` flag will be \ overridden to False so that the trial ends immediately and the customer's card isn't charged. """ # If plan has trial days and customer cancels before # trial period ends, then end subscription now, # i.e. at_period_end=False if self.trial_end and self.trial_end > timezone.now(): at_period_end = False if at_period_end: stripe_subscription = self.api_retrieve() stripe_subscription.cancel_at_period_end = True stripe_subscription.save() else: try: stripe_subscription = self._api_delete() except InvalidRequestError as exc: if "No such subscription:" in str(exc): # cancel() works by deleting the subscription. The object still # exists in Stripe however, and can still be retrieved. # If the subscription was already canceled (status=canceled), # that api_retrieve() call will fail with "No such subscription". # However, this may also happen if the subscription legitimately # does not exist, in which case the following line will re-raise. stripe_subscription = self.api_retrieve() else: raise return Subscription.sync_from_stripe_data(stripe_subscription)
python
{ "resource": "" }
q25151
Subscription.reactivate
train
def reactivate(self): """ Reactivates this subscription. If a customer's subscription is canceled with ``at_period_end`` set to True and it has not yet reached the end of the billing period, it can be reactivated. Subscriptions canceled immediately cannot be reactivated. (Source: https://stripe.com/docs/subscriptions/canceling-pausing) .. warning:: Reactivating a fully canceled Subscription will fail silently. Be sure to check the returned \ Subscription's status. """ stripe_subscription = self.api_retrieve() stripe_subscription.plan = self.plan.id stripe_subscription.cancel_at_period_end = False return Subscription.sync_from_stripe_data(stripe_subscription.save())
python
{ "resource": "" }
q25152
Subscription.is_period_current
train
def is_period_current(self): """ Returns True if this subscription's period is current, false otherwise.""" return self.current_period_end > timezone.now() or ( self.trial_end and self.trial_end > timezone.now() )
python
{ "resource": "" }
q25153
Subscription.is_status_temporarily_current
train
def is_status_temporarily_current(self): """ A status is temporarily current when the subscription is canceled with the ``at_period_end`` flag. The subscription is still active, but is technically canceled and we're just waiting for it to run out. You could use this method to give customers limited service after they've canceled. For example, a video on demand service could only allow customers to download their libraries and do nothing else when their subscription is temporarily current. """ return ( self.canceled_at and self.start < self.canceled_at and self.cancel_at_period_end )
python
{ "resource": "" }
q25154
Command.handle
train
def handle(self, *args, **options): """Create Customer objects for Subscribers without Customer objects associated.""" for subscriber in get_subscriber_model().objects.filter(djstripe_customers=None): # use get_or_create in case of race conditions on large subscriber bases Customer.get_or_create(subscriber=subscriber) print("Created subscriber for {0}".format(subscriber.email))
python
{ "resource": "" }
q25155
SubscriptionRestView.get
train
def get(self, request, **kwargs): """ Return the customer's valid subscriptions. Returns with status code 200. """ customer, _created = Customer.get_or_create( subscriber=subscriber_request_callback(self.request) ) serializer = SubscriptionSerializer(customer.subscription) return Response(serializer.data)
python
{ "resource": "" }
q25156
SubscriptionRestView.post
train
def post(self, request, **kwargs): """ Create a new current subscription for the user. Returns with status code 201. """ serializer = CreateSubscriptionSerializer(data=request.data) if serializer.is_valid(): try: customer, _created = Customer.get_or_create( subscriber=subscriber_request_callback(self.request) ) customer.add_card(serializer.data["stripe_token"]) charge_immediately = serializer.data.get("charge_immediately") if charge_immediately is None: charge_immediately = True customer.subscribe(serializer.data["plan"], charge_immediately) return Response(serializer.data, status=status.HTTP_201_CREATED) except Exception: # TODO: Better error messages return Response( "Something went wrong processing the payment.", status=status.HTTP_400_BAD_REQUEST ) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
python
{ "resource": "" }
q25157
SubscriptionRestView.delete
train
def delete(self, request, **kwargs): """ Mark the customers current subscription as cancelled. Returns with status code 204. """ try: customer, _created = Customer.get_or_create( subscriber=subscriber_request_callback(self.request) ) customer.subscription.cancel(at_period_end=CANCELLATION_AT_PERIOD_END) return Response(status=status.HTTP_204_NO_CONTENT) except Exception: return Response( "Something went wrong cancelling the subscription.", status=status.HTTP_400_BAD_REQUEST, )
python
{ "resource": "" }
q25158
stripe_temporary_api_version
train
def stripe_temporary_api_version(version, validate=True): """ Temporarily replace the global api_version used in stripe API calls with the given value. The original value is restored as soon as context exits. """ old_version = djstripe_settings.get_stripe_api_version() try: djstripe_settings.set_stripe_api_version(version, validate=validate) yield finally: # Validation is bypassed since we're restoring a previous value. djstripe_settings.set_stripe_api_version(old_version, validate=False)
python
{ "resource": "" }
q25159
subscription_payment_required
train
def subscription_payment_required( function=None, plan=None, pay_page=SUBSCRIPTION_REDIRECT ): """ Decorator for views that require subscription payment. Redirects to `pay_page` if necessary. """ actual_decorator = subscriber_passes_pay_test( subscriber_has_active_subscription, plan=plan, pay_page=pay_page ) if function: return actual_decorator(function) return actual_decorator
python
{ "resource": "" }
q25160
customer_webhook_handler
train
def customer_webhook_handler(event): """Handle updates to customer objects. First determines the crud_type and then handles the event if a customer exists locally. As customers are tied to local users, djstripe will not create customers that do not already exist locally. Docs and an example customer webhook response: https://stripe.com/docs/api#customer_object """ if event.customer: # As customers are tied to local users, djstripe will not create # customers that do not already exist locally. _handle_crud_like_event( target_cls=models.Customer, event=event, crud_exact=True, crud_valid=True )
python
{ "resource": "" }
q25161
customer_discount_webhook_handler
train
def customer_discount_webhook_handler(event): """Handle updates to customer discount objects. Docs: https://stripe.com/docs/api#discounts Because there is no concept of a "Discount" model in dj-stripe (due to the lack of a stripe id on them), this is a little different to the other handlers. """ crud_type = CrudType.determine(event=event) discount_data = event.data.get("object", {}) coupon_data = discount_data.get("coupon", {}) customer = event.customer if crud_type.created or crud_type.updated: coupon, _ = _handle_crud_like_event( target_cls=models.Coupon, event=event, data=coupon_data, id=coupon_data.get("id") ) coupon_start = discount_data.get("start") coupon_end = discount_data.get("end") else: coupon = None coupon_start = None coupon_end = None customer.coupon = coupon customer.coupon_start = convert_tstamp(coupon_start) customer.coupon_end = convert_tstamp(coupon_end) customer.save()
python
{ "resource": "" }
q25162
customer_source_webhook_handler
train
def customer_source_webhook_handler(event): """Handle updates to customer payment-source objects. Docs: https://stripe.com/docs/api#customer_object-sources. """ customer_data = event.data.get("object", {}) source_type = customer_data.get("object", {}) # TODO: handle other types of sources (https://stripe.com/docs/api#customer_object-sources) if source_type == SourceType.card: if event.verb.endswith("deleted") and customer_data: # On customer.source.deleted, we do not delete the object, we merely unlink it. # customer = Customer.objects.get(id=customer_data["id"]) # NOTE: for now, customer.sources still points to Card # Also, https://github.com/dj-stripe/dj-stripe/issues/576 models.Card.objects.filter(id=customer_data.get("id", "")).delete() models.DjstripePaymentMethod.objects.filter(id=customer_data.get("id", "")).delete() else: _handle_crud_like_event(target_cls=models.Card, event=event)
python
{ "resource": "" }
q25163
other_object_webhook_handler
train
def other_object_webhook_handler(event): """Handle updates to transfer, charge, invoice, invoiceitem, plan, product and source objects. Docs for: - charge: https://stripe.com/docs/api#charges - coupon: https://stripe.com/docs/api#coupons - invoice: https://stripe.com/docs/api#invoices - invoiceitem: https://stripe.com/docs/api#invoiceitems - plan: https://stripe.com/docs/api#plans - product: https://stripe.com/docs/api#products - source: https://stripe.com/docs/api#sources """ if event.parts[:2] == ["charge", "dispute"]: # Do not attempt to handle charge.dispute.* events. # We do not have a Dispute model yet. target_cls = models.Dispute else: target_cls = { "charge": models.Charge, "coupon": models.Coupon, "invoice": models.Invoice, "invoiceitem": models.InvoiceItem, "plan": models.Plan, "product": models.Product, "transfer": models.Transfer, "source": models.Source, }.get(event.category) _handle_crud_like_event(target_cls=target_cls, event=event)
python
{ "resource": "" }
q25164
_handle_crud_like_event
train
def _handle_crud_like_event( target_cls, event, data=None, verb=None, id=None, customer=None, crud_type=None, crud_exact=False, crud_valid=False, ): """ Helper to process crud_type-like events for objects. Non-deletes (creates, updates and "anything else" events) are treated as update_or_create events - The object will be retrieved locally, then it is synchronised with the Stripe API for parity. Deletes only occur for delete events and cause the object to be deleted from the local database, if it existed. If it doesn't exist then it is ignored (but the event processing still succeeds). :param target_cls: The djstripe model being handled. :type: ``djstripe.models.StripeObject`` :param data: The event object data (defaults to ``event.data``). :param verb: The event verb (defaults to ``event.verb``). :param id: The object Stripe ID (defaults to ``object.id``). :param customer: The customer object (defaults to ``event.customer``). :param crud_type: The CrudType object (determined by default). :param crud_exact: If True, match verb against CRUD type exactly. :param crud_valid: If True, CRUD type must match valid type. :returns: The object (if any) and the event CrudType. :rtype: ``tuple(obj, CrudType)`` """ data = data or event.data id = id or data.get("object", {}).get("id", None) if not id: # We require an object when applying CRUD-like events, so if there's # no ID the event is ignored/dropped. This happens in events such as # invoice.upcoming, which refer to a future (non-existant) invoice. logger.debug("Ignoring %r Stripe event without object ID: %r", event.type, event) return verb = verb or event.verb customer = customer or event.customer crud_type = crud_type or CrudType.determine(event=event, verb=verb, exact=crud_exact) obj = None if crud_valid and not crud_type.valid: logger.debug( "Ignoring %r Stripe event without valid CRUD type: %r", event.type, event ) return if crud_type.deleted: qs = target_cls.objects.filter(id=id) if target_cls is models.Customer and qs.exists(): qs.get().purge() else: obj = target_cls.objects.filter(id=id).delete() else: # Any other event type (creates, updates, etc.) - This can apply to # verbs that aren't strictly CRUD but Stripe do intend an update. Such # as invoice.payment_failed. kwargs = {"id": id} if hasattr(target_cls, "customer"): kwargs["customer"] = customer data = target_cls(**kwargs).api_retrieve() obj = target_cls.sync_from_stripe_data(data) return obj, crud_type
python
{ "resource": "" }
q25165
SubscriptionPaymentMiddleware.is_matching_rule
train
def is_matching_rule(self, request): """Check according to the rules defined in the class docstring.""" # First, if in DEBUG mode and with django-debug-toolbar, we skip # this entire process. if settings.DEBUG and request.path.startswith("/__debug__"): return True # Second we check against matches match = resolve(request.path, getattr(request, "urlconf", settings.ROOT_URLCONF)) if "({0})".format(match.app_name) in EXEMPT: return True if "[{0}]".format(match.namespace) in EXEMPT: return True if "{0}:{1}".format(match.namespace, match.url_name) in EXEMPT: return True if match.url_name in EXEMPT: return True # Third, we check wildcards: for exempt in [x for x in EXEMPT if x.startswith("fn:")]: exempt = exempt.replace("fn:", "") if fnmatch.fnmatch(request.path, exempt): return True return False
python
{ "resource": "" }
q25166
SubscriptionPaymentMiddleware.check_subscription
train
def check_subscription(self, request): """Redirect to the subscribe page if the user lacks an active subscription.""" subscriber = subscriber_request_callback(request) if not subscriber_has_active_subscription(subscriber): if not SUBSCRIPTION_REDIRECT: raise ImproperlyConfigured("DJSTRIPE_SUBSCRIPTION_REDIRECT is not set.") return redirect(SUBSCRIPTION_REDIRECT)
python
{ "resource": "" }
q25167
SubscriptionManager.started_during
train
def started_during(self, year, month): """Return Subscriptions not in trial status between a certain time range.""" return self.exclude(status="trialing").filter(start__year=year, start__month=month)
python
{ "resource": "" }
q25168
SubscriptionManager.canceled_during
train
def canceled_during(self, year, month): """Return Subscriptions canceled during a certain time range.""" return self.canceled().filter(canceled_at__year=year, canceled_at__month=month)
python
{ "resource": "" }
q25169
SubscriptionManager.started_plan_summary_for
train
def started_plan_summary_for(self, year, month): """Return started_during Subscriptions with plan counts annotated.""" return ( self.started_during(year, month) .values("plan") .order_by() .annotate(count=models.Count("plan")) )
python
{ "resource": "" }
q25170
SubscriptionManager.active_plan_summary
train
def active_plan_summary(self): """Return active Subscriptions with plan counts annotated.""" return self.active().values("plan").order_by().annotate(count=models.Count("plan"))
python
{ "resource": "" }
q25171
SubscriptionManager.canceled_plan_summary_for
train
def canceled_plan_summary_for(self, year, month): """Return Subscriptions canceled within a time range with plan counts annotated.""" return ( self.canceled_during(year, month) .values("plan") .order_by() .annotate(count=models.Count("plan")) )
python
{ "resource": "" }
q25172
SubscriptionManager.churn
train
def churn(self): """Return number of canceled Subscriptions divided by active Subscriptions.""" canceled = self.canceled().count() active = self.active().count() return decimal.Decimal(str(canceled)) / decimal.Decimal(str(active))
python
{ "resource": "" }
q25173
TransferManager.during
train
def during(self, year, month): """Return Transfers between a certain time range.""" return self.filter(created__year=year, created__month=month)
python
{ "resource": "" }
q25174
TransferManager.paid_totals_for
train
def paid_totals_for(self, year, month): """Return paid Transfers during a certain year, month with total amounts annotated.""" return self.during(year, month).aggregate(total_amount=models.Sum("amount"))
python
{ "resource": "" }
q25175
ChargeManager.paid_totals_for
train
def paid_totals_for(self, year, month): """Return paid Charges during a certain year, month with total amount, fee and refunded annotated.""" return ( self.during(year, month) .filter(paid=True) .aggregate( total_amount=models.Sum("amount"), total_refunded=models.Sum("amount_refunded") ) )
python
{ "resource": "" }
q25176
StripeModel.get_stripe_dashboard_url
train
def get_stripe_dashboard_url(self): """Get the stripe dashboard url for this object.""" if not self.stripe_dashboard_item_name or not self.id: return "" else: return "{base_url}{item}/{id}".format( base_url=self._get_base_stripe_dashboard_url(), item=self.stripe_dashboard_item_name, id=self.id, )
python
{ "resource": "" }
q25177
StripeModel.api_retrieve
train
def api_retrieve(self, api_key=None): """ Call the stripe API's retrieve operation for this model. :param api_key: The api key to use for this request. Defaults to settings.STRIPE_SECRET_KEY. :type api_key: string """ api_key = api_key or self.default_api_key return self.stripe_class.retrieve( id=self.id, api_key=api_key, expand=self.expand_fields )
python
{ "resource": "" }
q25178
StripeModel.api_list
train
def api_list(cls, api_key=djstripe_settings.STRIPE_SECRET_KEY, **kwargs): """ Call the stripe API's list operation for this model. :param api_key: The api key to use for this request. Defaults to djstripe_settings.STRIPE_SECRET_KEY. :type api_key: string See Stripe documentation for accepted kwargs for each object. :returns: an iterator over all items in the query """ return cls.stripe_class.list(api_key=api_key, **kwargs).auto_paging_iter()
python
{ "resource": "" }
q25179
StripeModel._api_create
train
def _api_create(cls, api_key=djstripe_settings.STRIPE_SECRET_KEY, **kwargs): """ Call the stripe API's create operation for this model. :param api_key: The api key to use for this request. Defaults to djstripe_settings.STRIPE_SECRET_KEY. :type api_key: string """ return cls.stripe_class.create(api_key=api_key, **kwargs)
python
{ "resource": "" }
q25180
StripeModel._api_delete
train
def _api_delete(self, api_key=None, **kwargs): """ Call the stripe API's delete operation for this model :param api_key: The api key to use for this request. Defaults to djstripe_settings.STRIPE_SECRET_KEY. :type api_key: string """ api_key = api_key or self.default_api_key return self.api_retrieve(api_key=api_key).delete(**kwargs)
python
{ "resource": "" }
q25181
StripeModel._stripe_object_to_record
train
def _stripe_object_to_record(cls, data, current_ids=None, pending_relations=None): """ This takes an object, as it is formatted in Stripe's current API for our object type. In return, it provides a dict. The dict can be used to create a record or to update a record This function takes care of mapping from one field name to another, converting from cents to dollars, converting timestamps, and eliminating unused fields (so that an objects.create() call would not fail). :param data: the object, as sent by Stripe. Parsed from JSON, into a dict :type data: dict :param current_ids: stripe ids of objects that are currently being processed :type current_ids: set :param pending_relations: list of tuples of relations to be attached post-save :type pending_relations: list :return: All the members from the input, translated, mutated, etc :rtype: dict """ manipulated_data = cls._manipulate_stripe_object_hook(data) if "object" not in data: raise ValueError("Stripe data has no `object` value. Aborting. %r" % (data)) if not cls.is_valid_object(data): raise ValueError( "Trying to fit a %r into %r. Aborting." % (data["object"], cls.__name__) ) result = {} if current_ids is None: current_ids = set() # Iterate over all the fields that we know are related to Stripe, let each field work its own magic ignore_fields = ["date_purged", "subscriber"] # XXX: Customer hack for field in cls._meta.fields: if field.name.startswith("djstripe_") or field.name in ignore_fields: continue if isinstance(field, models.ForeignKey): field_data, skip = cls._stripe_object_field_to_foreign_key( field=field, manipulated_data=manipulated_data, current_ids=current_ids, pending_relations=pending_relations, ) if skip: continue else: if hasattr(field, "stripe_to_db"): field_data = field.stripe_to_db(manipulated_data) else: field_data = manipulated_data.get(field.name) if isinstance(field, (models.CharField, models.TextField)) and field_data is None: field_data = "" result[field.name] = field_data return result
python
{ "resource": "" }
q25182
StripeModel._stripe_object_field_to_foreign_key
train
def _stripe_object_field_to_foreign_key( cls, field, manipulated_data, current_ids=None, pending_relations=None ): """ This converts a stripe API field to the dj stripe object it references, so that foreign keys can be connected up automatically. :param field: :type field: models.ForeignKey :param manipulated_data: :type manipulated_data: dict :param current_ids: stripe ids of objects that are currently being processed :type current_ids: set :param pending_relations: list of tuples of relations to be attached post-save :type pending_relations: list :return: """ field_data = None field_name = field.name raw_field_data = manipulated_data.get(field_name) refetch = False skip = False if issubclass(field.related_model, StripeModel): id_ = cls._id_from_data(raw_field_data) if not raw_field_data: skip = True elif id_ == raw_field_data: # A field like {"subscription": "sub_6lsC8pt7IcFpjA", ...} refetch = True else: # A field like {"subscription": {"id": sub_6lsC8pt7IcFpjA", ...}} pass if id_ in current_ids: # this object is currently being fetched, don't try to fetch again, to avoid recursion # instead, record the relation that should be be created once "object_id" object exists if pending_relations is not None: object_id = manipulated_data["id"] pending_relations.append((object_id, field, id_)) skip = True if not skip: field_data, _ = field.related_model._get_or_create_from_stripe_object( manipulated_data, field_name, refetch=refetch, current_ids=current_ids, pending_relations=pending_relations, ) else: # eg PaymentMethod, handled in hooks skip = True return field_data, skip
python
{ "resource": "" }
q25183
StripeModel._attach_objects_post_save_hook
train
def _attach_objects_post_save_hook(self, cls, data, pending_relations=None): """ Gets called by this object's create and sync methods just after save. Use this to populate fields after the model is saved. :param cls: The target class for the instantiated object. :param data: The data dictionary received from the Stripe API. :type data: dict """ unprocessed_pending_relations = [] if pending_relations is not None: for post_save_relation in pending_relations: object_id, field, id_ = post_save_relation if self.id == id_: # the target instance now exists target = field.model.objects.get(id=object_id) setattr(target, field.name, self) target.save() if django.VERSION < (2, 1): # refresh_from_db doesn't clear related objects cache on django<2.1 # instead manually clear the instance cache so refresh_from_db will reload it for field in self._meta.concrete_fields: if field.is_relation and field.is_cached(self): field.delete_cached_value(self) # reload so that indirect relations back to this object - eg self.charge.invoice = self are set # TODO - reverse the field reference here to avoid hitting the DB? self.refresh_from_db() else: unprocessed_pending_relations.append(post_save_relation) if len(pending_relations) != len(unprocessed_pending_relations): # replace in place so passed in list is updated in calling method pending_relations[:] = unprocessed_pending_relations
python
{ "resource": "" }
q25184
StripeModel._create_from_stripe_object
train
def _create_from_stripe_object( cls, data, current_ids=None, pending_relations=None, save=True ): """ Instantiates a model instance using the provided data object received from Stripe, and saves it to the database if specified. :param data: The data dictionary received from the Stripe API. :type data: dict :param current_ids: stripe ids of objects that are currently being processed :type current_ids: set :param pending_relations: list of tuples of relations to be attached post-save :type pending_relations: list :param save: If True, the object is saved after instantiation. :type save: bool :returns: The instantiated object. """ instance = cls( **cls._stripe_object_to_record( data, current_ids=current_ids, pending_relations=pending_relations ) ) instance._attach_objects_hook(cls, data) if save: instance.save(force_insert=True) instance._attach_objects_post_save_hook( cls, data, pending_relations=pending_relations ) return instance
python
{ "resource": "" }
q25185
StripeModel._stripe_object_to_invoice_items
train
def _stripe_object_to_invoice_items(cls, target_cls, data, invoice): """ Retrieves InvoiceItems for an invoice. If the invoice item doesn't exist already then it is created. If the invoice is an upcoming invoice that doesn't persist to the database (i.e. ephemeral) then the invoice items are also not saved. :param target_cls: The target class to instantiate per invoice item. :type target_cls: ``InvoiceItem`` :param data: The data dictionary received from the Stripe API. :type data: dict :param invoice: The invoice object that should hold the invoice items. :type invoice: ``djstripe.models.Invoice`` """ lines = data.get("lines") if not lines: return [] invoiceitems = [] for line in lines.get("data", []): if invoice.id: save = True line.setdefault("invoice", invoice.id) if line.get("type") == "subscription": # Lines for subscriptions need to be keyed based on invoice and # subscription, because their id is *just* the subscription # when received from Stripe. This means that future updates to # a subscription will change previously saved invoices - Doing # the composite key avoids this. if not line["id"].startswith(invoice.id): line["id"] = "{invoice_id}-{subscription_id}".format( invoice_id=invoice.id, subscription_id=line["id"] ) else: # Don't save invoice items for ephemeral invoices save = False line.setdefault("customer", invoice.customer.id) line.setdefault("date", int(dateformat.format(invoice.date, "U"))) item, _ = target_cls._get_or_create_from_stripe_object( line, refetch=False, save=save ) invoiceitems.append(item) return invoiceitems
python
{ "resource": "" }
q25186
StripeModel._stripe_object_to_subscription_items
train
def _stripe_object_to_subscription_items(cls, target_cls, data, subscription): """ Retrieves SubscriptionItems for a subscription. If the subscription item doesn't exist already then it is created. :param target_cls: The target class to instantiate per invoice item. :type target_cls: ``SubscriptionItem`` :param data: The data dictionary received from the Stripe API. :type data: dict :param invoice: The invoice object that should hold the invoice items. :type invoice: ``djstripe.models.Subscription`` """ items = data.get("items") if not items: return [] subscriptionitems = [] for item_data in items.get("data", []): item, _ = target_cls._get_or_create_from_stripe_object(item_data, refetch=False) subscriptionitems.append(item) return subscriptionitems
python
{ "resource": "" }
q25187
StripeModel.sync_from_stripe_data
train
def sync_from_stripe_data(cls, data, field_name="id"): """ Syncs this object from the stripe data provided. :param data: stripe object :type data: dict """ current_ids = set() if data.get(field_name, None): # stop nested objects from trying to retrieve this object before initial sync is complete current_ids.add(cls._id_from_data(data.get(field_name))) instance, created = cls._get_or_create_from_stripe_object( data, field_name=field_name, current_ids=current_ids ) if not created: instance._sync(cls._stripe_object_to_record(data)) instance._attach_objects_hook(cls, data) instance.save() instance._attach_objects_post_save_hook(cls, data) return instance
python
{ "resource": "" }
q25188
Charge.refund
train
def refund(self, amount=None, reason=None): """ Initiate a refund. If amount is not provided, then this will be a full refund. :param amount: A positive decimal amount representing how much of this charge to refund. Can only refund up to the unrefunded amount remaining of the charge. :trye amount: Decimal :param reason: String indicating the reason for the refund. If set, possible values are ``duplicate``, ``fraudulent``, and ``requested_by_customer``. Specifying ``fraudulent`` as the reason when you believe the charge to be fraudulent will help Stripe improve their fraud detection algorithms. :return: Stripe charge object :rtype: dict """ charge_obj = self.api_retrieve().refund( amount=self._calculate_refund_amount(amount=amount), reason=reason ) return self.__class__.sync_from_stripe_data(charge_obj)
python
{ "resource": "" }
q25189
Charge.capture
train
def capture(self): """ Capture the payment of an existing, uncaptured, charge. This is the second half of the two-step payment flow, where first you created a charge with the capture option set to False. See https://stripe.com/docs/api#capture_charge """ captured_charge = self.api_retrieve().capture() return self.__class__.sync_from_stripe_data(captured_charge)
python
{ "resource": "" }
q25190
Customer.get_or_create
train
def get_or_create(cls, subscriber, livemode=djstripe_settings.STRIPE_LIVE_MODE): """ Get or create a dj-stripe customer. :param subscriber: The subscriber model instance for which to get or create a customer. :type subscriber: User :param livemode: Whether to get the subscriber in live or test mode. :type livemode: bool """ try: return Customer.objects.get(subscriber=subscriber, livemode=livemode), False except Customer.DoesNotExist: action = "create:{}".format(subscriber.pk) idempotency_key = djstripe_settings.get_idempotency_key("customer", action, livemode) return cls.create(subscriber, idempotency_key=idempotency_key), True
python
{ "resource": "" }
q25191
Customer.subscribe
train
def subscribe( self, plan, charge_immediately=True, application_fee_percent=None, coupon=None, quantity=None, metadata=None, tax_percent=None, billing_cycle_anchor=None, trial_end=None, trial_from_plan=None, trial_period_days=None, ): """ Subscribes this customer to a plan. :param plan: The plan to which to subscribe the customer. :type plan: Plan or string (plan ID) :param application_fee_percent: This represents the percentage of the subscription invoice subtotal that will be transferred to the application owner's Stripe account. The request must be made with an OAuth key in order to set an application fee percentage. :type application_fee_percent: Decimal. Precision is 2; anything more will be ignored. A positive decimal between 1 and 100. :param coupon: The code of the coupon to apply to this subscription. A coupon applied to a subscription will only affect invoices created for that particular subscription. :type coupon: string :param quantity: The quantity applied to this subscription. Default is 1. :type quantity: integer :param metadata: A set of key/value pairs useful for storing additional information. :type metadata: dict :param tax_percent: This represents the percentage of the subscription invoice subtotal that will be calculated and added as tax to the final amount each billing period. :type tax_percent: Decimal. Precision is 2; anything more will be ignored. A positive decimal between 1 and 100. :param billing_cycle_anchor: A future timestamp to anchor the subscription’s billing cycle. This is used to determine the date of the first full invoice, and, for plans with month or year intervals, the day of the month for subsequent invoices. :type billing_cycle_anchor: datetime :param trial_end: The end datetime of the trial period the customer will get before being charged for the first time. If set, this will override the default trial period of the plan the customer is being subscribed to. The special value ``now`` can be provided to end the customer's trial immediately. :type trial_end: datetime :param charge_immediately: Whether or not to charge for the subscription upon creation. If False, an invoice will be created at the end of this period. :type charge_immediately: boolean :param trial_from_plan: Indicates if a plan’s trial_period_days should be applied to the subscription. Setting trial_end per subscription is preferred, and this defaults to false. Setting this flag to true together with trial_end is not allowed. :type trial_from_plan: boolean :param trial_period_days: Integer representing the number of trial period days before the customer is charged for the first time. This will always overwrite any trials that might apply via a subscribed plan. :type trial_period_days: integer .. Notes: .. ``charge_immediately`` is only available on ``Customer.subscribe()`` .. if you're using ``Customer.subscribe()`` instead of ``Customer.subscribe()``, ``plan`` \ can only be a string """ from .billing import Subscription # Convert Plan to id if isinstance(plan, StripeModel): plan = plan.id stripe_subscription = Subscription._api_create( plan=plan, customer=self.id, application_fee_percent=application_fee_percent, coupon=coupon, quantity=quantity, metadata=metadata, billing_cycle_anchor=billing_cycle_anchor, tax_percent=tax_percent, trial_end=trial_end, trial_from_plan=trial_from_plan, trial_period_days=trial_period_days, ) if charge_immediately: self.send_invoice() return Subscription.sync_from_stripe_data(stripe_subscription)
python
{ "resource": "" }
q25192
Customer.charge
train
def charge( self, amount, currency=None, application_fee=None, capture=None, description=None, destination=None, metadata=None, shipping=None, source=None, statement_descriptor=None, idempotency_key=None, ): """ Creates a charge for this customer. Parameters not implemented: * **receipt_email** - Since this is a charge on a customer, the customer's email address is used. :param amount: The amount to charge. :type amount: Decimal. Precision is 2; anything more will be ignored. :param currency: 3-letter ISO code for currency :type currency: string :param application_fee: A fee that will be applied to the charge and transfered to the platform owner's account. :type application_fee: Decimal. Precision is 2; anything more will be ignored. :param capture: Whether or not to immediately capture the charge. When false, the charge issues an authorization (or pre-authorization), and will need to be captured later. Uncaptured charges expire in 7 days. Default is True :type capture: bool :param description: An arbitrary string. :type description: string :param destination: An account to make the charge on behalf of. :type destination: Account :param metadata: A set of key/value pairs useful for storing additional information. :type metadata: dict :param shipping: Shipping information for the charge. :type shipping: dict :param source: The source to use for this charge. Must be a source attributed to this customer. If None, the customer's default source is used. Can be either the id of the source or the source object itself. :type source: string, Source :param statement_descriptor: An arbitrary string to be displayed on the customer's credit card statement. :type statement_descriptor: string """ if not isinstance(amount, decimal.Decimal): raise ValueError("You must supply a decimal value representing dollars.") # TODO: better default detection (should charge in customer default) currency = currency or "usd" # Convert Source to id if source and isinstance(source, StripeModel): source = source.id stripe_charge = Charge._api_create( amount=int(amount * 100), # Convert dollars into cents currency=currency, application_fee=int(application_fee * 100) if application_fee else None, # Convert dollars into cents capture=capture, description=description, destination=destination, metadata=metadata, shipping=shipping, customer=self.id, source=source, statement_descriptor=statement_descriptor, idempotency_key=idempotency_key, ) return Charge.sync_from_stripe_data(stripe_charge)
python
{ "resource": "" }
q25193
Customer.add_invoice_item
train
def add_invoice_item( self, amount, currency, description=None, discountable=None, invoice=None, metadata=None, subscription=None, ): """ Adds an arbitrary charge or credit to the customer's upcoming invoice. Different than creating a charge. Charges are separate bills that get processed immediately. Invoice items are appended to the customer's next invoice. This is extremely useful when adding surcharges to subscriptions. :param amount: The amount to charge. :type amount: Decimal. Precision is 2; anything more will be ignored. :param currency: 3-letter ISO code for currency :type currency: string :param description: An arbitrary string. :type description: string :param discountable: Controls whether discounts apply to this invoice item. Defaults to False for prorations or negative invoice items, and True for all other invoice items. :type discountable: boolean :param invoice: An existing invoice to add this invoice item to. When left blank, the invoice item will be added to the next upcoming scheduled invoice. Use this when adding invoice items in response to an ``invoice.created`` webhook. You cannot add an invoice item to an invoice that has already been paid, attempted or closed. :type invoice: Invoice or string (invoice ID) :param metadata: A set of key/value pairs useful for storing additional information. :type metadata: dict :param subscription: A subscription to add this invoice item to. When left blank, the invoice item will be be added to the next upcoming scheduled invoice. When set, scheduled invoices for subscriptions other than the specified subscription will ignore the invoice item. Use this when you want to express that an invoice item has been accrued within the context of a particular subscription. :type subscription: Subscription or string (subscription ID) .. Notes: .. if you're using ``Customer.add_invoice_item()`` instead of ``Customer.add_invoice_item()``, \ ``invoice`` and ``subscriptions`` can only be strings """ from .billing import InvoiceItem if not isinstance(amount, decimal.Decimal): raise ValueError("You must supply a decimal value representing dollars.") # Convert Invoice to id if invoice is not None and isinstance(invoice, StripeModel): invoice = invoice.id # Convert Subscription to id if subscription is not None and isinstance(subscription, StripeModel): subscription = subscription.id stripe_invoiceitem = InvoiceItem._api_create( amount=int(amount * 100), # Convert dollars into cents currency=currency, customer=self.id, description=description, discountable=discountable, invoice=invoice, metadata=metadata, subscription=subscription, ) return InvoiceItem.sync_from_stripe_data(stripe_invoiceitem)
python
{ "resource": "" }
q25194
Customer.add_card
train
def add_card(self, source, set_default=True): """ Adds a card to this customer's account. :param source: Either a token, like the ones returned by our Stripe.js, or a dictionary containing a user's credit card details. Stripe will automatically validate the card. :type source: string, dict :param set_default: Whether or not to set the source as the customer's default source :type set_default: boolean """ from .payment_methods import DjstripePaymentMethod stripe_customer = self.api_retrieve() new_stripe_payment_method = stripe_customer.sources.create(source=source) if set_default: stripe_customer.default_source = new_stripe_payment_method["id"] stripe_customer.save() new_payment_method = DjstripePaymentMethod.from_stripe_object( new_stripe_payment_method ) # Change the default source if set_default: self.default_source = new_payment_method self.save() return new_payment_method.resolve()
python
{ "resource": "" }
q25195
Customer.has_active_subscription
train
def has_active_subscription(self, plan=None): """ Checks to see if this customer has an active subscription to the given plan. :param plan: The plan for which to check for an active subscription. If plan is None and there exists only one active subscription, this method will check if that subscription is valid. Calling this method with no plan and multiple valid subscriptions for this customer will throw an exception. :type plan: Plan or string (plan ID) :returns: True if there exists an active subscription, False otherwise. :throws: TypeError if ``plan`` is None and more than one active subscription exists for this customer. """ if plan is None: valid_subscriptions = self._get_valid_subscriptions() if len(valid_subscriptions) == 0: return False elif len(valid_subscriptions) == 1: return True else: raise TypeError( "plan cannot be None if more than one valid subscription exists for this customer." ) else: # Convert Plan to id if isinstance(plan, StripeModel): plan = plan.id return any( [ subscription.is_valid() for subscription in self.subscriptions.filter(plan__id=plan) ] )
python
{ "resource": "" }
q25196
Customer.subscription
train
def subscription(self): """ Shortcut to get this customer's subscription. :returns: None if the customer has no subscriptions, the subscription if the customer has a subscription. :raises MultipleSubscriptionException: Raised if the customer has multiple subscriptions. In this case, use ``Customer.subscriptions`` instead. """ subscriptions = self.valid_subscriptions if subscriptions.count() > 1: raise MultipleSubscriptionException( "This customer has multiple subscriptions. Use Customer.subscriptions " "to access them." ) else: return subscriptions.first()
python
{ "resource": "" }
q25197
Customer.send_invoice
train
def send_invoice(self): """ Pay and send the customer's latest invoice. :returns: True if an invoice was able to be created and paid, False otherwise (typically if there was nothing to invoice). """ from .billing import Invoice try: invoice = Invoice._api_create(customer=self.id) invoice.pay() return True except InvalidRequestError: # TODO: Check this for a more specific error message. return False
python
{ "resource": "" }
q25198
Customer.retry_unpaid_invoices
train
def retry_unpaid_invoices(self): """ Attempt to retry collecting payment on the customer's unpaid invoices.""" self._sync_invoices() for invoice in self.invoices.filter(paid=False, closed=False): try: invoice.retry() # Always retry unpaid invoices except InvalidRequestError as exc: if str(exc) != "Invoice is already paid": raise
python
{ "resource": "" }
q25199
Customer.add_coupon
train
def add_coupon(self, coupon, idempotency_key=None): """ Add a coupon to a Customer. The coupon can be a Coupon object, or a valid Stripe Coupon ID. """ if isinstance(coupon, StripeModel): coupon = coupon.id stripe_customer = self.api_retrieve() stripe_customer["coupon"] = coupon stripe_customer.save(idempotency_key=idempotency_key) return self.__class__.sync_from_stripe_data(stripe_customer)
python
{ "resource": "" }