<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
 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)