_id
stringlengths
2
7
title
stringlengths
1
88
partition
stringclasses
3 values
text
stringlengths
75
19.8k
language
stringclasses
1 value
meta_information
dict
q18900
_Tasks.find_by_project
train
def find_by_project(self, project_id, params={}, **options): """Returns the compact task records for all tasks within the given project, ordered by their priority within the project. Parameters ---------- projectId : {Id} The project in which to search for tasks. [params] : {Object} Parameters for the request """ path = "/projects/%s/tasks" % (project_id) return self.client.get_collection(path, params, **options)
python
{ "resource": "" }
q18901
_Tasks.find_by_tag
train
def find_by_tag(self, tag, params={}, **options): """Returns the compact task records for all tasks with the given tag. Parameters ---------- tag : {Id} The tag in which to search for tasks. [params] : {Object} Parameters for the request """ path = "/tags/%s/tasks" % (tag) return self.client.get_collection(path, params, **options)
python
{ "resource": "" }
q18902
_Tasks.dependencies
train
def dependencies(self, task, params={}, **options): """Returns the compact representations of all of the dependencies of a task. Parameters ---------- task : {Id} The task to get dependencies on. [params] : {Object} Parameters for the request """ path = "/tasks/%s/dependencies" % (task) return self.client.get(path, params, **options)
python
{ "resource": "" }
q18903
_Tasks.dependents
train
def dependents(self, task, params={}, **options): """Returns the compact representations of all of the dependents of a task. Parameters ---------- task : {Id} The task to get dependents on. [params] : {Object} Parameters for the request """ path = "/tasks/%s/dependents" % (task) return self.client.get(path, params, **options)
python
{ "resource": "" }
q18904
_Tasks.remove_dependencies
train
def remove_dependencies(self, task, params={}, **options): """Unlinks a set of dependencies from this task. Parameters ---------- task : {Id} The task to remove dependencies from. [data] : {Object} Data for the request - dependencies : {Array} An array of task IDs to remove as dependencies. """ path = "/tasks/%s/removeDependencies" % (task) return self.client.post(path, params, **options)
python
{ "resource": "" }
q18905
_Tasks.remove_dependents
train
def remove_dependents(self, task, params={}, **options): """Unlinks a set of dependents from this task. Parameters ---------- task : {Id} The task to remove dependents from. [data] : {Object} Data for the request - dependents : {Array} An array of task IDs to remove as dependents. """ path = "/tasks/%s/removeDependents" % (task) return self.client.post(path, params, **options)
python
{ "resource": "" }
q18906
_Tasks.add_followers
train
def add_followers(self, task, params={}, **options): """Adds each of the specified followers to the task, if they are not already following. Returns the complete, updated record for the affected task. Parameters ---------- task : {Id} The task to add followers to. [data] : {Object} Data for the request - followers : {Array} An array of followers to add to the task. """ path = "/tasks/%s/addFollowers" % (task) return self.client.post(path, params, **options)
python
{ "resource": "" }
q18907
_Tasks.remove_followers
train
def remove_followers(self, task, params={}, **options): """Removes each of the specified followers from the task if they are following. Returns the complete, updated record for the affected task. Parameters ---------- task : {Id} The task to remove followers from. [data] : {Object} Data for the request - followers : {Array} An array of followers to remove from the task. """ path = "/tasks/%s/removeFollowers" % (task) return self.client.post(path, params, **options)
python
{ "resource": "" }
q18908
_Tasks.projects
train
def projects(self, task, params={}, **options): """Returns a compact representation of all of the projects the task is in. Parameters ---------- task : {Id} The task to get projects on. [params] : {Object} Parameters for the request """ path = "/tasks/%s/projects" % (task) return self.client.get_collection(path, params, **options)
python
{ "resource": "" }
q18909
_Tasks.add_project
train
def add_project(self, task, params={}, **options): """Adds the task to the specified project, in the optional location specified. If no location arguments are given, the task will be added to the end of the project. `addProject` can also be used to reorder a task within a project or section that already contains it. At most one of `insert_before`, `insert_after`, or `section` should be specified. Inserting into a section in an non-order-dependent way can be done by specifying `section`, otherwise, to insert within a section in a particular place, specify `insert_before` or `insert_after` and a task within the section to anchor the position of this task. Returns an empty data block. Parameters ---------- task : {Id} The task to add to a project. [data] : {Object} Data for the request - project : {Id} The project to add the task to. - [insert_after] : {Id} A task in the project to insert the task after, or `null` to insert at the beginning of the list. - [insert_before] : {Id} A task in the project to insert the task before, or `null` to insert at the end of the list. - [section] : {Id} A section in the project to insert the task into. The task will be inserted at the bottom of the section. """ path = "/tasks/%s/addProject" % (task) return self.client.post(path, params, **options)
python
{ "resource": "" }
q18910
_Tasks.remove_project
train
def remove_project(self, task, params={}, **options): """Removes the task from the specified project. The task will still exist in the system, but it will not be in the project anymore. Returns an empty data block. Parameters ---------- task : {Id} The task to remove from a project. [data] : {Object} Data for the request - project : {Id} The project to remove the task from. """ path = "/tasks/%s/removeProject" % (task) return self.client.post(path, params, **options)
python
{ "resource": "" }
q18911
_Tasks.tags
train
def tags(self, task, params={}, **options): """Returns a compact representation of all of the tags the task has. Parameters ---------- task : {Id} The task to get tags on. [params] : {Object} Parameters for the request """ path = "/tasks/%s/tags" % (task) return self.client.get_collection(path, params, **options)
python
{ "resource": "" }
q18912
_Tasks.add_tag
train
def add_tag(self, task, params={}, **options): """Adds a tag to a task. Returns an empty data block. Parameters ---------- task : {Id} The task to add a tag to. [data] : {Object} Data for the request - tag : {Id} The tag to add to the task. """ path = "/tasks/%s/addTag" % (task) return self.client.post(path, params, **options)
python
{ "resource": "" }
q18913
_Tasks.remove_tag
train
def remove_tag(self, task, params={}, **options): """Removes a tag from the task. Returns an empty data block. Parameters ---------- task : {Id} The task to remove a tag from. [data] : {Object} Data for the request - tag : {Id} The tag to remove from the task. """ path = "/tasks/%s/removeTag" % (task) return self.client.post(path, params, **options)
python
{ "resource": "" }
q18914
_Tasks.subtasks
train
def subtasks(self, task, params={}, **options): """Returns a compact representation of all of the subtasks of a task. Parameters ---------- task : {Id} The task to get the subtasks of. [params] : {Object} Parameters for the request """ path = "/tasks/%s/subtasks" % (task) return self.client.get_collection(path, params, **options)
python
{ "resource": "" }
q18915
_Tasks.add_subtask
train
def add_subtask(self, task, params={}, **options): """Creates a new subtask and adds it to the parent task. Returns the full record for the newly created subtask. Parameters ---------- task : {Id} The task to add a subtask to. [data] : {Object} Data for the request """ path = "/tasks/%s/subtasks" % (task) return self.client.post(path, params, **options)
python
{ "resource": "" }
q18916
_Tasks.stories
train
def stories(self, task, params={}, **options): """Returns a compact representation of all of the stories on the task. Parameters ---------- task : {Id} The task containing the stories to get. [params] : {Object} Parameters for the request """ path = "/tasks/%s/stories" % (task) return self.client.get_collection(path, params, **options)
python
{ "resource": "" }
q18917
_ProjectStatuses.find_by_id
train
def find_by_id(self, project_status, params={}, **options): """Returns the complete record for a single status update. Parameters ---------- project-status : {Id} The project status update to get. [params] : {Object} Parameters for the request """ path = "/project_statuses/%s" % (project_status) return self.client.get(path, params, **options)
python
{ "resource": "" }
q18918
_ProjectStatuses.delete
train
def delete(self, project_status, params={}, **options): """Deletes a specific, existing project status update. Returns an empty data record. Parameters ---------- project-status : {Id} The project status update to delete. """ path = "/project_statuses/%s" % (project_status) return self.client.delete(path, params, **options)
python
{ "resource": "" }
q18919
Client.request
train
def request(self, method, path, **options): """Dispatches a request to the Asana HTTP API""" options = self._merge_options(options) url = options['base_url'] + path retry_count = 0 request_options = self._parse_request_options(options) self._add_version_header(request_options) while True: try: response = getattr(self.session, method)( url, auth=self.auth, **request_options) if response.status_code in STATUS_MAP: raise STATUS_MAP[response.status_code](response) elif 500 <= response.status_code < 600: # Any unhandled 500 is a server error. raise error.ServerError(response) else: if options['full_payload']: return response.json() else: return response.json()['data'] except error.RetryableAsanaError as e: if retry_count < options['max_retries']: self._handle_retryable_error(e, retry_count) retry_count += 1 else: raise e
python
{ "resource": "" }
q18920
Client.get
train
def get(self, path, query, **options): """Parses GET request options and dispatches a request.""" api_options = self._parse_api_options(options, query_string=True) query_options = self._parse_query_options(options) parameter_options = self._parse_parameter_options(options) # options in the query takes precendence query = _merge(query_options, api_options, parameter_options, query) return self.request('get', path, params=query, **options)
python
{ "resource": "" }
q18921
Client.get_collection
train
def get_collection(self, path, query, **options): """Get a collection from a collection endpoint. Parses GET request options for a collection endpoint and dispatches a request. """ options = self._merge_options(options) if options['iterator_type'] == 'items': return CollectionPageIterator(self, path, query, options).items() if options['iterator_type'] is None: return self.get(path, query, **options) raise Exception('Unknown value for "iterator_type" option: {}'.format( str(options['iterator_type'])))
python
{ "resource": "" }
q18922
Client.put
train
def put(self, path, data, **options): """Parses PUT request options and dispatches a request.""" parameter_options = self._parse_parameter_options(options) body = { # values in the data body takes precendence 'data': _merge(parameter_options, data), 'options': self._parse_api_options(options) } headers = _merge( {'content-type': 'application/json'}, options.pop('headers', {}) ) return self.request('put', path, data=body, headers=headers, **options)
python
{ "resource": "" }
q18923
Client._parse_parameter_options
train
def _parse_parameter_options(self, options): """Select all unknown options. Select all unknown options (not query string, API, or request options) """ return self._select_options(options, self.ALL_OPTIONS, invert=True)
python
{ "resource": "" }
q18924
Client._parse_api_options
train
def _parse_api_options(self, options, query_string=False): """Select API options out of the provided options object. Selects API string options out of the provided options object and formats for either request body (default) or query string. """ api_options = self._select_options(options, self.API_OPTIONS) if query_string: # Prefix all options with "opt_" query_api_options = {} for key in api_options: # Transform list/tuples into comma separated list if isinstance(api_options[key], (list, tuple)): query_api_options[ 'opt_' + key] = ','.join(api_options[key]) else: query_api_options[ 'opt_' + key] = api_options[key] return query_api_options else: return api_options
python
{ "resource": "" }
q18925
Client._parse_request_options
train
def _parse_request_options(self, options): """Select request options out of the provided options object. Select and formats options to be passed to the 'requests' library's request methods. """ request_options = self._select_options(options, self.REQUEST_OPTIONS) if 'params' in request_options: params = request_options['params'] for key in params: if isinstance(params[key], bool): params[key] = json.dumps(params[key]) if 'data' in request_options: # remove empty 'options': if 'options' in request_options['data'] and ( len(request_options['data']['options']) == 0): del request_options['data']['options'] # serialize 'data' to JSON, requests doesn't do this automatically: request_options['data'] = json.dumps(request_options['data']) headers = self.headers.copy() headers.update(request_options.get('headers', {})) request_options['headers'] = headers return request_options
python
{ "resource": "" }
q18926
Client._select_options
train
def _select_options(self, options, keys, invert=False): """Select the provided keys out of an options object. Selects the provided keys (or everything except the provided keys) out of an options object. """ options = self._merge_options(options) result = {} for key in options: if (invert and key not in keys) or (not invert and key in keys): result[key] = options[key] return result
python
{ "resource": "" }
q18927
Client._version_header
train
def _version_header(self): """Generate the client version header to send on each request.""" if not self._cached_version_header: self._cached_version_header = urlparse.urlencode( self._version_values()) return self._cached_version_header
python
{ "resource": "" }
q18928
_Webhooks.get_by_id
train
def get_by_id(self, webhook, params={}, **options): """Returns the full record for the given webhook. Parameters ---------- webhook : {Id} The webhook to get. [params] : {Object} Parameters for the request """ path = "/webhooks/%s" % (webhook) return self.client.get(path, params, **options)
python
{ "resource": "" }
q18929
_Webhooks.delete_by_id
train
def delete_by_id(self, webhook, params={}, **options): """This method permanently removes a webhook. Note that it may be possible to receive a request that was already in flight after deleting the webhook, but no further requests will be issued. Parameters ---------- webhook : {Id} The webhook to delete. """ path = "/webhooks/%s" % (webhook) return self.client.delete(path, params, **options)
python
{ "resource": "" }
q18930
_Projects.create_in_team
train
def create_in_team(self, team, params={}, **options): """Creates a project shared with the given team. Returns the full record of the newly created project. Parameters ---------- team : {Id} The team to create the project in. [data] : {Object} Data for the request """ path = "/teams/%s/projects" % (team) return self.client.post(path, params, **options)
python
{ "resource": "" }
q18931
_Projects.find_by_id
train
def find_by_id(self, project, params={}, **options): """Returns the complete project record for a single project. Parameters ---------- project : {Id} The project to get. [params] : {Object} Parameters for the request """ path = "/projects/%s" % (project) return self.client.get(path, params, **options)
python
{ "resource": "" }
q18932
_Projects.update
train
def update(self, project, params={}, **options): """A specific, existing project can be updated by making a PUT request on the URL for that project. Only the fields provided in the `data` block will be updated; any unspecified fields will remain unchanged. When using this method, it is best to specify only those fields you wish to change, or else you may overwrite changes made by another user since you last retrieved the task. Returns the complete updated project record. Parameters ---------- project : {Id} The project to update. [data] : {Object} Data for the request """ path = "/projects/%s" % (project) return self.client.put(path, params, **options)
python
{ "resource": "" }
q18933
_Projects.delete
train
def delete(self, project, params={}, **options): """A specific, existing project can be deleted by making a DELETE request on the URL for that project. Returns an empty data record. Parameters ---------- project : {Id} The project to delete. """ path = "/projects/%s" % (project) return self.client.delete(path, params, **options)
python
{ "resource": "" }
q18934
_Projects.find_by_team
train
def find_by_team(self, team, params={}, **options): """Returns the compact project records for all projects in the team. Parameters ---------- team : {Id} The team to find projects in. [params] : {Object} Parameters for the request - [archived] : {Boolean} Only return projects whose `archived` field takes on the value of this parameter. """ path = "/teams/%s/projects" % (team) return self.client.get_collection(path, params, **options)
python
{ "resource": "" }
q18935
_Projects.tasks
train
def tasks(self, project, params={}, **options): """Returns the compact task records for all tasks within the given project, ordered by their priority within the project. Tasks can exist in more than one project at a time. Parameters ---------- project : {Id} The project in which to search for tasks. [params] : {Object} Parameters for the request """ path = "/projects/%s/tasks" % (project) return self.client.get_collection(path, params, **options)
python
{ "resource": "" }
q18936
_Projects.add_followers
train
def add_followers(self, project, params={}, **options): """Adds the specified list of users as followers to the project. Followers are a subset of members, therefore if the users are not already members of the project they will also become members as a result of this operation. Returns the updated project record. Parameters ---------- project : {Id} The project to add followers to. [data] : {Object} Data for the request - followers : {Array} An array of followers to add to the project. """ path = "/projects/%s/addFollowers" % (project) return self.client.post(path, params, **options)
python
{ "resource": "" }
q18937
_Projects.remove_followers
train
def remove_followers(self, project, params={}, **options): """Removes the specified list of users from following the project, this will not affect project membership status. Returns the updated project record. Parameters ---------- project : {Id} The project to remove followers from. [data] : {Object} Data for the request - followers : {Array} An array of followers to remove from the project. """ path = "/projects/%s/removeFollowers" % (project) return self.client.post(path, params, **options)
python
{ "resource": "" }
q18938
_Projects.add_members
train
def add_members(self, project, params={}, **options): """Adds the specified list of users as members of the project. Returns the updated project record. Parameters ---------- project : {Id} The project to add members to. [data] : {Object} Data for the request - members : {Array} An array of members to add to the project. """ path = "/projects/%s/addMembers" % (project) return self.client.post(path, params, **options)
python
{ "resource": "" }
q18939
_Projects.remove_members
train
def remove_members(self, project, params={}, **options): """Removes the specified list of members from the project. Returns the updated project record. Parameters ---------- project : {Id} The project to remove members from. [data] : {Object} Data for the request - members : {Array} An array of members to remove from the project. """ path = "/projects/%s/removeMembers" % (project) return self.client.post(path, params, **options)
python
{ "resource": "" }
q18940
_Projects.add_custom_field_setting
train
def add_custom_field_setting(self, project, params={}, **options): """Create a new custom field setting on the project. Parameters ---------- project : {Id} The project to associate the custom field with [data] : {Object} Data for the request - custom_field : {Id} The id of the custom field to associate with this project. - [is_important] : {Boolean} Whether this field should be considered important to this project. - [insert_before] : {Id} An id of a Custom Field Settings on this project, before which the new Custom Field Settings will be added. `insert_before` and `insert_after` parameters cannot both be specified. - [insert_after] : {Id} An id of a Custom Field Settings on this project, after which the new Custom Field Settings will be added. `insert_before` and `insert_after` parameters cannot both be specified. """ path = "/projects/%s/addCustomFieldSetting" % (project) return self.client.post(path, params, **options)
python
{ "resource": "" }
q18941
_Projects.remove_custom_field_setting
train
def remove_custom_field_setting(self, project, params={}, **options): """Remove a custom field setting on the project. Parameters ---------- project : {Id} The project to associate the custom field with [data] : {Object} Data for the request - [custom_field] : {Id} The id of the custom field to remove from this project. """ path = "/projects/%s/removeCustomFieldSetting" % (project) return self.client.post(path, params, **options)
python
{ "resource": "" }
q18942
_Users.find_by_id
train
def find_by_id(self, user, params={}, **options): """Returns the full user record for the single user with the provided ID. Parameters ---------- user : {String} An identifier for the user. Can be one of an email address, the globally unique identifier for the user, or the keyword `me` to indicate the current user making the request. [params] : {Object} Parameters for the request """ path = "/users/%s" % (user) return self.client.get(path, params, **options)
python
{ "resource": "" }
q18943
shipping_cost
train
def shipping_cost(request): """ Returns the shipping cost for a given country If the shipping cost for the given country has not been set, it will fallback to the default shipping cost if it has been enabled in the app settings """ try: code = request.query_params.get('country_code') except AttributeError: return Response(data={"message": "No country code supplied"}, status=status.HTTP_400_BAD_REQUEST) option = request.query_params.get('shipping_rate_name', 'standard') try: settings = Configuration.for_site(request.site) data = utils.get_shipping_cost(settings, code, option) response = Response(data=data, status=status.HTTP_200_OK) except utils.InvalidShippingRate: response = Response(data={"message": "Shipping option {} is invalid".format(option)}, status=status.HTTP_400_BAD_REQUEST) except utils.InvalidShippingCountry: response = Response(data={"message": "Shipping to {} is not available".format(code)}, status=status.HTTP_400_BAD_REQUEST) return response
python
{ "resource": "" }
q18944
shipping_countries
train
def shipping_countries(request): """ Get all shipping countries """ queryset = models.Country.objects.exclude(shippingrate=None) serializer = serializers.CountrySerializer(queryset, many=True) return Response(data=serializer.data, status=status.HTTP_200_OK)
python
{ "resource": "" }
q18945
shipping_options
train
def shipping_options(request, country): """ Get the shipping options for a given country """ qrs = models.ShippingRate.objects.filter(countries__in=[country]) serializer = serializers.ShippingRateSerializer(qrs, many=True) return Response( data=serializer.data, status=status.HTTP_200_OK )
python
{ "resource": "" }
q18946
BasketViewSet.create
train
def create(self, request): """ Add an item to the basket """ variant_id = request.data.get("variant_id", None) if variant_id is not None: variant = ProductVariant.objects.get(id=variant_id) quantity = int(request.data.get("quantity", 1)) items, bid = utils.get_basket_items(request) # Check if the variant is already in the basket in_basket = False for item in items: if item.variant.id == variant.id: item.increase_quantity(quantity) in_basket = True break if not in_basket: item = BasketItem(variant=variant, quantity=quantity, basket_id=bid) item.save() serializer = BasketItemSerializer(self.get_queryset(request), many=True) response = Response(data=serializer.data, status=status.HTTP_201_CREATED) else: response = Response( {"message": "Missing 'variant_id'"}, status=status.HTTP_400_BAD_REQUEST) return response
python
{ "resource": "" }
q18947
BasketViewSet.bulk_update
train
def bulk_update(self, request): """Put multiple items in the basket, removing anything that already exists """ # Delete everything in the basket bid = utils.destroy_basket(request) for item_data in request.data: item = BasketItem(basket_id=bid, **item_data) item.save() serializer = BasketItemSerializer(self.get_queryset(request), many=True) response = Response(data=serializer.data, status=status.HTTP_200_OK) return response
python
{ "resource": "" }
q18948
BasketViewSet.destroy
train
def destroy(self, request, variant_id=None): """ Remove an item from the basket """ variant = ProductVariant.objects.get(id=variant_id) quantity = int(request.data.get("quantity", 1)) try: item = BasketItem.objects.get( basket_id=utils.basket_id(request), variant=variant) item.decrease_quantity(quantity) except BasketItem.DoesNotExist: pass serializer = BasketItemSerializer(self.get_queryset(request), many=True) return Response(data=serializer.data, status=status.HTTP_200_OK)
python
{ "resource": "" }
q18949
BasketViewSet.total_items
train
def total_items(self, request): """ Get total number of items in the basket """ n_total = 0 for item in self.get_queryset(request): n_total += item.quantity return Response(data={"quantity": n_total}, status=status.HTTP_200_OK)
python
{ "resource": "" }
q18950
BasketViewSet.item_count
train
def item_count(self, request, variant_id=None): """ Get quantity of a single item in the basket """ bid = utils.basket_id(request) item = ProductVariant.objects.get(id=variant_id) try: count = BasketItem.objects.get(basket_id=bid, variant=item).quantity except BasketItem.DoesNotExist: count = 0 return Response(data={"quantity": count}, status=status.HTTP_200_OK)
python
{ "resource": "" }
q18951
sdist.compile_assets
train
def compile_assets(self): """ Compile the front end assets """ try: # Move into client dir curdir = os.path.abspath(os.curdir) client_path = os.path.join(os.path.dirname(__file__), 'longclaw', 'client') os.chdir(client_path) subprocess.check_call(['npm', 'install']) subprocess.check_call(['npm', 'run', 'build']) os.chdir(curdir) except (OSError, subprocess.CalledProcessError) as err: print('Error compiling assets: {}'.format(err)) raise SystemExit(1)
python
{ "resource": "" }
q18952
requests_admin
train
def requests_admin(request, pk): """Table display of each request for a given product. Allows the given Page pk to refer to a direct parent of the ProductVariant model or be the ProductVariant model itself. This allows for the standard longclaw product modelling philosophy where ProductVariant refers to the actual product (in the case where there is only 1 variant) or to be variants of the product page. """ page = Page.objects.get(pk=pk).specific if hasattr(page, 'variants'): requests = ProductRequest.objects.filter( variant__in=page.variants.all() ) else: requests = ProductRequest.objects.filter(variant=page) return render( request, "productrequests/requests_admin.html", {'page': page, 'requests': requests} )
python
{ "resource": "" }
q18953
OrderViewSet.refund_order
train
def refund_order(self, request, pk): """Refund the order specified by the pk """ order = Order.objects.get(id=pk) order.refund() return Response(status=status.HTTP_204_NO_CONTENT)
python
{ "resource": "" }
q18954
OrderViewSet.fulfill_order
train
def fulfill_order(self, request, pk): """Mark the order specified by pk as fulfilled """ order = Order.objects.get(id=pk) order.fulfill() return Response(status=status.HTTP_204_NO_CONTENT)
python
{ "resource": "" }
q18955
product_requests_button
train
def product_requests_button(page, page_perms, is_parent=False): """Renders a 'requests' button on the page index showing the number of times the product has been requested. Attempts to only show such a button for valid product/variant pages """ # Is this page the 'product' model? # It is generally safe to assume either the page will have a 'variants' # member or will be an instance of longclaw.utils.ProductVariant if hasattr(page, 'variants') or isinstance(page, ProductVariant): yield widgets.PageListingButton( 'View Requests', reverse('productrequests_admin', kwargs={'pk': page.id}), priority=40 )
python
{ "resource": "" }
q18956
gateway_client_js
train
def gateway_client_js(): """ Template tag which provides a `script` tag for each javascript item required by the payment gateway """ javascripts = GATEWAY.client_js() if isinstance(javascripts, (tuple, list)): tags = [] for js in javascripts: tags.append('<script type="text/javascript" src="{}"></script>'.format(js)) return tags else: raise TypeError( 'function client_js of {} must return a list or tuple'.format(GATEWAY.__name__))
python
{ "resource": "" }
q18957
get_basket_items
train
def get_basket_items(request): """ Get all items in the basket """ bid = basket_id(request) return BasketItem.objects.filter(basket_id=bid), bid
python
{ "resource": "" }
q18958
destroy_basket
train
def destroy_basket(request): """Delete all items in the basket """ items, bid = get_basket_items(request) for item in items: item.delete() return bid
python
{ "resource": "" }
q18959
shipping_rate
train
def shipping_rate(context, **kwargs): """Return the shipping rate for a country & shipping option name. """ settings = Configuration.for_site(context["request"].site) code = kwargs.get('code', None) name = kwargs.get('name', None) return get_shipping_cost(settings, code, name)
python
{ "resource": "" }
q18960
ProductBase.price_range
train
def price_range(self): """ Calculate the price range of the products variants """ ordered = self.variants.order_by('base_price') if ordered: return ordered.first().price, ordered.last().price else: return None, None
python
{ "resource": "" }
q18961
create_project
train
def create_project(args): """ Create a new django project using the longclaw template """ # Make sure given name is not already in use by another python package/module. try: __import__(args.project_name) except ImportError: pass else: sys.exit("'{}' conflicts with the name of an existing " "Python module and cannot be used as a project " "name. Please try another name.".format(args.project_name)) # Get the longclaw template path template_path = path.join(path.dirname(longclaw.__file__), 'project_template') utility = ManagementUtility(( 'django-admin.py', 'startproject', '--template={}'.format(template_path), '--extension=html,css,js,py,txt', args.project_name )) utility.execute() print("{} has been created.".format(args.project_name))
python
{ "resource": "" }
q18962
build_assets
train
def build_assets(args): """ Build the longclaw assets """ # Get the path to the JS directory asset_path = path.join(path.dirname(longclaw.__file__), 'client') try: # Move into client dir curdir = os.path.abspath(os.curdir) os.chdir(asset_path) print('Compiling assets....') subprocess.check_call(['npm', 'install']) subprocess.check_call(['npm', 'run', 'build']) os.chdir(curdir) print('Complete!') except (OSError, subprocess.CalledProcessError) as err: print('Error compiling assets: {}'.format(err)) raise SystemExit(1)
python
{ "resource": "" }
q18963
main
train
def main(): """ Setup the parser and call the command function """ parser = argparse.ArgumentParser(description='Longclaw CLI') subparsers = parser.add_subparsers() start = subparsers.add_parser('start', help='Create a Wagtail+Longclaw project') start.add_argument('project_name', help='Name of the project') start.set_defaults(func=create_project) build = subparsers.add_parser('build', help='Build the front-end assets for Longclaw') build.set_defaults(func=build_assets) args = parser.parse_args() # Python 3 lost the default behaviour to fall back to printing # help if a subparser is not selected. # See: https://bugs.python.org/issue16308 # So we must explicitly catch the error thrown on py3 if # no commands given to longclaw try: args.func(args) except AttributeError: parser.print_help() sys.exit(0)
python
{ "resource": "" }
q18964
sales_for_time_period
train
def sales_for_time_period(from_date, to_date): """ Get all sales for a given time period """ sales = Order.objects.filter( Q(payment_date__lte=to_date) & Q(payment_date__gte=from_date) ).exclude(status=Order.CANCELLED) return sales
python
{ "resource": "" }
q18965
capture_payment
train
def capture_payment(request): """ Capture the payment for a basket and create an order request.data should contain: 'address': Dict with the following fields: shipping_name shipping_address_line1 shipping_address_city shipping_address_zip shipping_address_country billing_name billing_address_line1 billing_address_city billing_address_zip billing_address_country 'email': Email address of the customer 'shipping': The shipping rate (in the sites' currency) """ # get request data address = request.data['address'] email = request.data.get('email', None) shipping_option = request.data.get('shipping_option', None) # Capture the payment order = create_order( email, request, addresses=address, shipping_option=shipping_option, capture_payment=True ) response = Response(data={"order_id": order.id}, status=status.HTTP_201_CREATED) return response
python
{ "resource": "" }
q18966
create_order
train
def create_order(email, request, addresses=None, shipping_address=None, billing_address=None, shipping_option=None, capture_payment=False): """ Create an order from a basket and customer infomation """ basket_items, _ = get_basket_items(request) if addresses: # Longclaw < 0.2 used 'shipping_name', longclaw > 0.2 uses a consistent # prefix (shipping_address_xxxx) try: shipping_name = addresses['shipping_name'] except KeyError: shipping_name = addresses['shipping_address_name'] shipping_country = addresses['shipping_address_country'] if not shipping_country: shipping_country = None shipping_address, _ = Address.objects.get_or_create(name=shipping_name, line_1=addresses[ 'shipping_address_line1'], city=addresses[ 'shipping_address_city'], postcode=addresses[ 'shipping_address_zip'], country=shipping_country) shipping_address.save() try: billing_name = addresses['billing_name'] except KeyError: billing_name = addresses['billing_address_name'] billing_country = addresses['shipping_address_country'] if not billing_country: billing_country = None billing_address, _ = Address.objects.get_or_create(name=billing_name, line_1=addresses[ 'billing_address_line1'], city=addresses[ 'billing_address_city'], postcode=addresses[ 'billing_address_zip'], country=billing_country) billing_address.save() else: shipping_country = shipping_address.country ip_address = get_real_ip(request) if shipping_country and shipping_option: site_settings = Configuration.for_site(request.site) shipping_rate = get_shipping_cost( site_settings, shipping_address.country.pk, shipping_option)['rate'] else: shipping_rate = Decimal(0) order = Order( email=email, ip_address=ip_address, shipping_address=shipping_address, billing_address=billing_address, shipping_rate=shipping_rate ) order.save() # Create the order items & compute total total = 0 for item in basket_items: total += item.total() order_item = OrderItem( product=item.variant, quantity=item.quantity, order=order ) order_item.save() if capture_payment: desc = 'Payment from {} for order id #{}'.format(email, order.id) try: transaction_id = GATEWAY.create_payment(request, total + shipping_rate, description=desc) order.payment_date = timezone.now() order.transaction_id = transaction_id # Once the order has been successfully taken, we can empty the basket destroy_basket(request) except PaymentError: order.status = order.FAILURE order.save() return order
python
{ "resource": "" }
q18967
ProductRequestViewSet.create
train
def create(self, request): """Create a new product request """ variant_id = request.data.get("variant_id", None) if variant_id is not None: variant = ProductVariant.objects.get(id=variant_id) product_request = ProductRequest(variant=variant) product_request.save() serializer = self.serializer_class(product_request) response = Response(data=serializer.data, status=status.HTTP_201_CREATED) else: response = Response( {"message": "Missing 'variant_id'"}, status=status.HTTP_400_BAD_REQUEST) return response
python
{ "resource": "" }
q18968
ProductRequestViewSet.requests_for_variant
train
def requests_for_variant(self, request, variant_id=None): """Get all the requests for a single variant """ requests = ProductRequest.objects.filter(variant__id=variant_id) serializer = self.serializer_class(requests, many=True) return Response(data=serializer.data, status=status.HTTP_200_OK)
python
{ "resource": "" }
q18969
AddToBasketForm.clean
train
def clean(self): """ Check user has cookies enabled """ if self.request: if not self.request.session.test_cookie_worked(): raise forms.ValidationError("Cookies must be enabled.") return self.cleaned_data
python
{ "resource": "" }
q18970
OrderModelAdmin.detail_view
train
def detail_view(self, request, instance_pk): """ Instantiates a class-based view to provide 'inspect' functionality for the assigned model. The view class used can be overridden by changing the 'inspect_view_class' attribute. """ kwargs = {'model_admin': self, 'instance_pk': instance_pk} view_class = self.detail_view_class return view_class.as_view(**kwargs)(request)
python
{ "resource": "" }
q18971
StripePayment.get_token
train
def get_token(self, request): """ Create a stripe token for a card """ return stripe.Token.create( card={ "number": request.data["number"], "exp_month": request.data["exp_month"], "exp_year": request.data["exp_year"], "cvc": request.data["cvc"] } )
python
{ "resource": "" }
q18972
Order.total
train
def total(self): """Total cost of the order """ total = 0 for item in self.items.all(): total += item.total return total
python
{ "resource": "" }
q18973
Order.refund
train
def refund(self): """Issue a full refund for this order """ from longclaw.utils import GATEWAY now = datetime.strftime(datetime.now(), "%b %d %Y %H:%M:%S") if GATEWAY.issue_refund(self.transaction_id, self.total): self.status = self.REFUNDED self.status_note = "Refunded on {}".format(now) else: self.status_note = "Refund failed on {}".format(now) self.save()
python
{ "resource": "" }
q18974
Order.cancel
train
def cancel(self, refund=True): """Cancel this order, optionally refunding it """ if refund: self.refund() self.status = self.CANCELLED self.save()
python
{ "resource": "" }
q18975
CatalogQueryRange.attribute_name
train
def attribute_name(self, attribute_name): """ Sets the attribute_name of this CatalogQueryRange. The name of the attribute to be searched. :param attribute_name: The attribute_name of this CatalogQueryRange. :type: str """ if attribute_name is None: raise ValueError("Invalid value for `attribute_name`, must not be `None`") if len(attribute_name) < 1: raise ValueError("Invalid value for `attribute_name`, length must be greater than or equal to `1`") self._attribute_name = attribute_name
python
{ "resource": "" }
q18976
RegisterDomainRequest.domain_name
train
def domain_name(self, domain_name): """ Sets the domain_name of this RegisterDomainRequest. A domain name as described in RFC-1034 that will be registered with ApplePay :param domain_name: The domain_name of this RegisterDomainRequest. :type: str """ if domain_name is None: raise ValueError("Invalid value for `domain_name`, must not be `None`") if len(domain_name) > 255: raise ValueError("Invalid value for `domain_name`, length must be less than `255`") if len(domain_name) < 1: raise ValueError("Invalid value for `domain_name`, length must be greater than or equal to `1`") self._domain_name = domain_name
python
{ "resource": "" }
q18977
CatalogQueryPrefix.attribute_prefix
train
def attribute_prefix(self, attribute_prefix): """ Sets the attribute_prefix of this CatalogQueryPrefix. The desired prefix of the search attribute value. :param attribute_prefix: The attribute_prefix of this CatalogQueryPrefix. :type: str """ if attribute_prefix is None: raise ValueError("Invalid value for `attribute_prefix`, must not be `None`") if len(attribute_prefix) < 1: raise ValueError("Invalid value for `attribute_prefix`, length must be greater than or equal to `1`") self._attribute_prefix = attribute_prefix
python
{ "resource": "" }
q18978
Shift.id
train
def id(self, id): """ Sets the id of this Shift. UUID for this object :param id: The id of this Shift. :type: str """ if id is None: raise ValueError("Invalid value for `id`, must not be `None`") if len(id) > 255: raise ValueError("Invalid value for `id`, length must be less than `255`") self._id = id
python
{ "resource": "" }
q18979
Shift.employee_id
train
def employee_id(self, employee_id): """ Sets the employee_id of this Shift. The ID of the employee this shift belongs to. :param employee_id: The employee_id of this Shift. :type: str """ if employee_id is None: raise ValueError("Invalid value for `employee_id`, must not be `None`") if len(employee_id) < 1: raise ValueError("Invalid value for `employee_id`, length must be greater than or equal to `1`") self._employee_id = employee_id
python
{ "resource": "" }
q18980
Shift.start_at
train
def start_at(self, start_at): """ Sets the start_at of this Shift. RFC 3339; shifted to location timezone + offset. Precision up to the minute is respected; seconds are truncated. :param start_at: The start_at of this Shift. :type: str """ if start_at is None: raise ValueError("Invalid value for `start_at`, must not be `None`") if len(start_at) < 1: raise ValueError("Invalid value for `start_at`, length must be greater than or equal to `1`") self._start_at = start_at
python
{ "resource": "" }
q18981
OrderLineItemTax.percentage
train
def percentage(self, percentage): """ Sets the percentage of this OrderLineItemTax. The percentage of the tax, as a string representation of a decimal number. A value of `7.25` corresponds to a percentage of 7.25%. :param percentage: The percentage of this OrderLineItemTax. :type: str """ if percentage is None: raise ValueError("Invalid value for `percentage`, must not be `None`") if len(percentage) > 10: raise ValueError("Invalid value for `percentage`, length must be less than `10`") self._percentage = percentage
python
{ "resource": "" }
q18982
Order.location_id
train
def location_id(self, location_id): """ Sets the location_id of this Order. The ID of the merchant location this order is associated with. :param location_id: The location_id of this Order. :type: str """ if location_id is None: raise ValueError("Invalid value for `location_id`, must not be `None`") if len(location_id) < 1: raise ValueError("Invalid value for `location_id`, length must be greater than or equal to `1`") self._location_id = location_id
python
{ "resource": "" }
q18983
Order.reference_id
train
def reference_id(self, reference_id): """ Sets the reference_id of this Order. A client specified identifier to associate an entity in another system with this order. :param reference_id: The reference_id of this Order. :type: str """ if reference_id is None: raise ValueError("Invalid value for `reference_id`, must not be `None`") if len(reference_id) > 40: raise ValueError("Invalid value for `reference_id`, length must be less than `40`") self._reference_id = reference_id
python
{ "resource": "" }
q18984
OrderFulfillmentPickupDetails.note
train
def note(self, note): """ Sets the note of this OrderFulfillmentPickupDetails. A general note about the pickup fulfillment. Notes are useful for providing additional instructions and are displayed in Square apps. :param note: The note of this OrderFulfillmentPickupDetails. :type: str """ if note is None: raise ValueError("Invalid value for `note`, must not be `None`") if len(note) > 500: raise ValueError("Invalid value for `note`, length must be less than `500`") self._note = note
python
{ "resource": "" }
q18985
OrderFulfillmentPickupDetails.cancel_reason
train
def cancel_reason(self, cancel_reason): """ Sets the cancel_reason of this OrderFulfillmentPickupDetails. A description of why the pickup was canceled. Max length is 100 characters. :param cancel_reason: The cancel_reason of this OrderFulfillmentPickupDetails. :type: str """ if cancel_reason is None: raise ValueError("Invalid value for `cancel_reason`, must not be `None`") if len(cancel_reason) > 100: raise ValueError("Invalid value for `cancel_reason`, length must be less than `100`") self._cancel_reason = cancel_reason
python
{ "resource": "" }
q18986
AdditionalRecipient.description
train
def description(self, description): """ Sets the description of this AdditionalRecipient. The description of the additional recipient. :param description: The description of this AdditionalRecipient. :type: str """ if description is None: raise ValueError("Invalid value for `description`, must not be `None`") if len(description) > 100: raise ValueError("Invalid value for `description`, length must be less than `100`") if len(description) < 1: raise ValueError("Invalid value for `description`, length must be greater than or equal to `1`") self._description = description
python
{ "resource": "" }
q18987
ModelBreak.break_type_id
train
def break_type_id(self, break_type_id): """ Sets the break_type_id of this ModelBreak. The `BreakType` this `Break` was templated on. :param break_type_id: The break_type_id of this ModelBreak. :type: str """ if break_type_id is None: raise ValueError("Invalid value for `break_type_id`, must not be `None`") if len(break_type_id) < 1: raise ValueError("Invalid value for `break_type_id`, length must be greater than or equal to `1`") self._break_type_id = break_type_id
python
{ "resource": "" }
q18988
ListEmployeeWagesRequest.limit
train
def limit(self, limit): """ Sets the limit of this ListEmployeeWagesRequest. Maximum number of Employee Wages to return per page. Can range between 1 and 200. The default is the maximum at 200. :param limit: The limit of this ListEmployeeWagesRequest. :type: int """ if limit is None: raise ValueError("Invalid value for `limit`, must not be `None`") if limit > 200: raise ValueError("Invalid value for `limit`, must be a value less than or equal to `200`") if limit < 1: raise ValueError("Invalid value for `limit`, must be a value greater than or equal to `1`") self._limit = limit
python
{ "resource": "" }
q18989
AdditionalRecipientReceivableRefund.receivable_id
train
def receivable_id(self, receivable_id): """ Sets the receivable_id of this AdditionalRecipientReceivableRefund. The ID of the receivable that the refund was applied to. :param receivable_id: The receivable_id of this AdditionalRecipientReceivableRefund. :type: str """ if receivable_id is None: raise ValueError("Invalid value for `receivable_id`, must not be `None`") if len(receivable_id) < 1: raise ValueError("Invalid value for `receivable_id`, length must be greater than or equal to `1`") self._receivable_id = receivable_id
python
{ "resource": "" }
q18990
AdditionalRecipientReceivableRefund.refund_id
train
def refund_id(self, refund_id): """ Sets the refund_id of this AdditionalRecipientReceivableRefund. The ID of the refund that is associated to this receivable refund. :param refund_id: The refund_id of this AdditionalRecipientReceivableRefund. :type: str """ if refund_id is None: raise ValueError("Invalid value for `refund_id`, must not be `None`") if len(refund_id) < 1: raise ValueError("Invalid value for `refund_id`, length must be greater than or equal to `1`") self._refund_id = refund_id
python
{ "resource": "" }
q18991
AdditionalRecipientReceivableRefund.transaction_location_id
train
def transaction_location_id(self, transaction_location_id): """ Sets the transaction_location_id of this AdditionalRecipientReceivableRefund. The ID of the location that created the receivable. This is the location ID on the associated transaction. :param transaction_location_id: The transaction_location_id of this AdditionalRecipientReceivableRefund. :type: str """ if transaction_location_id is None: raise ValueError("Invalid value for `transaction_location_id`, must not be `None`") if len(transaction_location_id) < 1: raise ValueError("Invalid value for `transaction_location_id`, length must be greater than or equal to `1`") self._transaction_location_id = transaction_location_id
python
{ "resource": "" }
q18992
ChargeRequest.card_nonce
train
def card_nonce(self, card_nonce): """ Sets the card_nonce of this ChargeRequest. A nonce generated from the `SqPaymentForm` that represents the card to charge. The application that provides a nonce to this endpoint must be the _same application_ that generated the nonce with the `SqPaymentForm`. Otherwise, the nonce is invalid. Do not provide a value for this field if you provide a value for `customer_card_id`. :param card_nonce: The card_nonce of this ChargeRequest. :type: str """ if card_nonce is None: raise ValueError("Invalid value for `card_nonce`, must not be `None`") if len(card_nonce) > 192: raise ValueError("Invalid value for `card_nonce`, length must be less than `192`") self._card_nonce = card_nonce
python
{ "resource": "" }
q18993
ChargeRequest.customer_card_id
train
def customer_card_id(self, customer_card_id): """ Sets the customer_card_id of this ChargeRequest. The ID of the customer card on file to charge. Do not provide a value for this field if you provide a value for `card_nonce`. If you provide this value, you _must_ also provide a value for `customer_id`. :param customer_card_id: The customer_card_id of this ChargeRequest. :type: str """ if customer_card_id is None: raise ValueError("Invalid value for `customer_card_id`, must not be `None`") if len(customer_card_id) > 192: raise ValueError("Invalid value for `customer_card_id`, length must be less than `192`") self._customer_card_id = customer_card_id
python
{ "resource": "" }
q18994
ChargeRequest.customer_id
train
def customer_id(self, customer_id): """ Sets the customer_id of this ChargeRequest. The ID of the customer to associate this transaction with. This field is required if you provide a value for `customer_card_id`, and optional otherwise. :param customer_id: The customer_id of this ChargeRequest. :type: str """ if customer_id is None: raise ValueError("Invalid value for `customer_id`, must not be `None`") if len(customer_id) > 50: raise ValueError("Invalid value for `customer_id`, length must be less than `50`") self._customer_id = customer_id
python
{ "resource": "" }
q18995
OrderLineItem.quantity
train
def quantity(self, quantity): """ Sets the quantity of this OrderLineItem. The quantity purchased, as a string representation of a number. This string must have a positive integer value. :param quantity: The quantity of this OrderLineItem. :type: str """ if quantity is None: raise ValueError("Invalid value for `quantity`, must not be `None`") if len(quantity) > 5: raise ValueError("Invalid value for `quantity`, length must be less than `5`") if len(quantity) < 1: raise ValueError("Invalid value for `quantity`, length must be greater than or equal to `1`") self._quantity = quantity
python
{ "resource": "" }
q18996
OrderLineItem.variation_name
train
def variation_name(self, variation_name): """ Sets the variation_name of this OrderLineItem. The name of the variation applied to this line item. :param variation_name: The variation_name of this OrderLineItem. :type: str """ if variation_name is None: raise ValueError("Invalid value for `variation_name`, must not be `None`") if len(variation_name) > 255: raise ValueError("Invalid value for `variation_name`, length must be less than `255`") self._variation_name = variation_name
python
{ "resource": "" }
q18997
AdditionalRecipientReceivable.transaction_id
train
def transaction_id(self, transaction_id): """ Sets the transaction_id of this AdditionalRecipientReceivable. The ID of the transaction that the additional recipient receivable was applied to. :param transaction_id: The transaction_id of this AdditionalRecipientReceivable. :type: str """ if transaction_id is None: raise ValueError("Invalid value for `transaction_id`, must not be `None`") if len(transaction_id) < 1: raise ValueError("Invalid value for `transaction_id`, length must be greater than or equal to `1`") self._transaction_id = transaction_id
python
{ "resource": "" }
q18998
V1Page.page_index
train
def page_index(self, page_index): """ Sets the page_index of this V1Page. The page's position in the merchant's list of pages. Always an integer between 0 and 6, inclusive. :param page_index: The page_index of this V1Page. :type: int """ if page_index is None: raise ValueError("Invalid value for `page_index`, must not be `None`") if page_index > 6: raise ValueError("Invalid value for `page_index`, must be a value less than or equal to `6`") if page_index < 0: raise ValueError("Invalid value for `page_index`, must be a value greater than or equal to `0`") self._page_index = page_index
python
{ "resource": "" }
q18999
BreakType.break_name
train
def break_name(self, break_name): """ Sets the break_name of this BreakType. A human-readable name for this type of break. Will be displayed to employees in Square products. :param break_name: The break_name of this BreakType. :type: str """ if break_name is None: raise ValueError("Invalid value for `break_name`, must not be `None`") if len(break_name) < 1: raise ValueError("Invalid value for `break_name`, length must be greater than or equal to `1`") self._break_name = break_name
python
{ "resource": "" }