_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... | 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 garbag... | 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_filena... | 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
me... | 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('Fo... | 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 = workin... | 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_cach... | 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_inh... | 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 environ... | 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 p... | 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[PU... | 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 Value... | 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... | 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.
un... | 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_... | 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 bina... | 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::
n... | 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 ... | 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.... | 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 st... | 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... | 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... | 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 even... | 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_strip... | 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 databas... | 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 i... | 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_W... | 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.... | 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 ... | 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 act... | 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 = str... | 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_... | 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.
... | 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_... | 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 th... | 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.... | 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.tria... | 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 termin... | 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/subs... | 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 aft... | 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=su... | 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(serialize... | 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_callba... | 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_PER... | 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_ve... | 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
)
... | 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 resp... | 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 = C... | 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/do... | 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://stri... | 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 - T... | 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
mat... | 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_RED... | 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=sel... | 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... | 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... | 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_... | 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 on... | 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 manip... | 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... | 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: dic... | 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.... | 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``
... | 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
c... | 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
... | 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()
... | 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... | 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: ... | 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:
* **recei... | 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 immedi... | 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_defa... | 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 v... | 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.subscr... | 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()
... | 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) != ... | 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.sav... | python | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.