text
stringlengths
81
112k
Wrap a view in JSON. This decorator runs the given function and looks out for ajax.AJAXError's, which it encodes into a proper HttpResponse object. If an unknown error is thrown it's encoded as a 500. All errors are then packaged up with an appropriate Content-Type and a JSON body that you can inspect in JavaScript on the client. They look like: { "message": "Error message here.", "code": 500 } Please keep in mind that raw exception messages could very well be exposed to the client if a non-AJAXError is thrown. def json_response(f, *args, **kwargs): """Wrap a view in JSON. This decorator runs the given function and looks out for ajax.AJAXError's, which it encodes into a proper HttpResponse object. If an unknown error is thrown it's encoded as a 500. All errors are then packaged up with an appropriate Content-Type and a JSON body that you can inspect in JavaScript on the client. They look like: { "message": "Error message here.", "code": 500 } Please keep in mind that raw exception messages could very well be exposed to the client if a non-AJAXError is thrown. """ try: result = f(*args, **kwargs) if isinstance(result, AJAXError): raise result except AJAXError as e: result = e.get_response() request = args[0] logger.warn('AJAXError: %d %s - %s', e.code, request.path, e.msg, exc_info=True, extra={ 'status_code': e.code, 'request': request } ) except Http404 as e: result = AJAXError(404, e.__str__()).get_response() except Exception as e: import sys exc_info = sys.exc_info() type, message, trace = exc_info if settings.DEBUG: import traceback tb = [{'file': l[0], 'line': l[1], 'in': l[2], 'code': l[3]} for l in traceback.extract_tb(trace)] result = AJAXError(500, message, traceback=tb).get_response() else: result = AJAXError(500, "Internal server error.").get_response() request = args[0] logger.error('Internal Server Error: %s' % request.path, exc_info=exc_info, extra={ 'status_code': 500, 'request': request } ) result['Content-Type'] = 'application/json' return result
Import a dotted module path and return the attribute/class designated by the last name in the path. Raise ImproperlyConfigured if something goes wrong. This has come straight from Django 1.6 def import_by_path(dotted_path, error_prefix=''): """ Import a dotted module path and return the attribute/class designated by the last name in the path. Raise ImproperlyConfigured if something goes wrong. This has come straight from Django 1.6 """ try: module_path, class_name = dotted_path.rsplit('.', 1) except ValueError: raise ImproperlyConfigured("%s%s doesn't look like a module path" % ( error_prefix, dotted_path)) try: module = import_module(module_path) except ImportError as e: raise ImproperlyConfigured('%sError importing module %s: "%s"' % ( error_prefix, module_path, e)) try: attr = getattr(module, class_name) except AttributeError: raise ImproperlyConfigured( '%sModule "%s" does not define a "%s" attribute/class' % ( error_prefix, module_path, class_name ) ) return attr
Load an AJAX endpoint. This will load either an ad-hoc endpoint or it will load up a model endpoint depending on what it finds. It first attempts to load ``model`` as if it were an ad-hoc endpoint. Alternatively, it will attempt to see if there is a ``ModelEndpoint`` for the given ``model``. def endpoint_loader(request, application, model, **kwargs): """Load an AJAX endpoint. This will load either an ad-hoc endpoint or it will load up a model endpoint depending on what it finds. It first attempts to load ``model`` as if it were an ad-hoc endpoint. Alternatively, it will attempt to see if there is a ``ModelEndpoint`` for the given ``model``. """ if request.method != "POST": raise AJAXError(400, _('Invalid HTTP method used.')) try: module = import_module('%s.endpoints' % application) except ImportError as e: if settings.DEBUG: raise e else: raise AJAXError(404, _('AJAX endpoint does not exist.')) if hasattr(module, model): # This is an ad-hoc endpoint endpoint = getattr(module, model) else: # This is a model endpoint method = kwargs.get('method', 'create').lower() try: del kwargs['method'] except: pass try: model_endpoint = ajax.endpoint.load(model, application, method, **kwargs) if not model_endpoint.authenticate(request, application, method): raise AJAXError(403, _('User is not authorized.')) endpoint = getattr(model_endpoint, method, False) if not endpoint: raise AJAXError(404, _('Invalid method.')) except NotRegistered: raise AJAXError(500, _('Invalid model.')) data = endpoint(request) if isinstance(data, HttpResponse): return data if isinstance(data, EnvelopedResponse): envelope = data.metadata payload = data.data else: envelope = {} payload = data envelope.update({ 'success': True, 'data': payload, }) return HttpResponse(json.dumps(envelope, cls=DjangoJSONEncoder, separators=(',', ':')))
List objects of a model. By default will show page 1 with 20 objects on it. **Usage**:: params = {"items_per_page":10,"page":2} //all params are optional $.post("/ajax/{app}/{model}/list.json"),params) def list(self, request): """ List objects of a model. By default will show page 1 with 20 objects on it. **Usage**:: params = {"items_per_page":10,"page":2} //all params are optional $.post("/ajax/{app}/{model}/list.json"),params) """ max_items_per_page = getattr(self, 'max_per_page', getattr(settings, 'AJAX_MAX_PER_PAGE', 100)) requested_items_per_page = request.POST.get("items_per_page", 20) items_per_page = min(max_items_per_page, requested_items_per_page) current_page = request.POST.get("current_page", 1) if not self.can_list(request.user): raise AJAXError(403, _("Access to this endpoint is forbidden")) objects = self.get_queryset(request) paginator = Paginator(objects, items_per_page) try: page = paginator.page(current_page) except PageNotAnInteger: # If page is not an integer, deliver first page. page = paginator.page(1) except EmptyPage: # If page is out of range (e.g. 9999), return empty list. page = EmptyPageResult() data = [encoder.encode(record) for record in page.object_list] return EnvelopedResponse(data=data, metadata={'total': paginator.count})
Extract data from POST. Handles extracting a vanilla Python dict of values that are present in the given model. This also handles instances of ``ForeignKey`` and will convert those to the appropriate object instances from the database. In other words, it will see that user is a ``ForeignKey`` to Django's ``User`` class, assume the value is an appropriate pk, and load up that record. def _extract_data(self, request): """Extract data from POST. Handles extracting a vanilla Python dict of values that are present in the given model. This also handles instances of ``ForeignKey`` and will convert those to the appropriate object instances from the database. In other words, it will see that user is a ``ForeignKey`` to Django's ``User`` class, assume the value is an appropriate pk, and load up that record. """ data = {} for field, val in six.iteritems(request.POST): if field in self.immutable_fields: continue # Ignore immutable fields silently. if field in self.fields: field_obj = self.model._meta.get_field(field) val = self._extract_value(val) if isinstance(field_obj, models.ForeignKey): if field_obj.null and not val: clean_value = None else: clean_value = field_obj.rel.to.objects.get(pk=val) else: clean_value = field_obj.to_python(val) data[smart_str(field)] = clean_value return data
If the value is true/false/null replace with Python equivalent. def _extract_value(self, value): """If the value is true/false/null replace with Python equivalent.""" return ModelEndpoint._value_map.get(smart_str(value).lower(), value)
Fetch a given record. Handles fetching a record from the database along with throwing an appropriate instance of ``AJAXError`. def _get_record(self): """Fetch a given record. Handles fetching a record from the database along with throwing an appropriate instance of ``AJAXError`. """ if not self.pk: raise AJAXError(400, _('Invalid request for record.')) try: return self.model.objects.get(pk=self.pk) except self.model.DoesNotExist: raise AJAXError(404, _('%s with id of "%s" not found.') % ( self.model.__name__, self.pk))
Authenticate the AJAX request. By default any request to fetch a model is allowed for any user, including anonymous users. All other methods minimally require that the user is already logged in. Most likely you will want to lock down who can edit and delete various models. To do this, just override this method in your child class. def authenticate(self, request, application, method): """Authenticate the AJAX request. By default any request to fetch a model is allowed for any user, including anonymous users. All other methods minimally require that the user is already logged in. Most likely you will want to lock down who can edit and delete various models. To do this, just override this method in your child class. """ return self.authentication.is_authenticated(request, application, method)
Gets all entries of a space. def all(self, query=None): """ Gets all entries of a space. """ if query is None: query = {} if self.content_type_id is not None: query['content_type'] = self.content_type_id normalize_select(query) return super(EntriesProxy, self).all(query=query)
Gets a single entry by ID. def find(self, entry_id, query=None): """ Gets a single entry by ID. """ if query is None: query = {} if self.content_type_id is not None: query['content_type'] = self.content_type_id normalize_select(query) return super(EntriesProxy, self).find(entry_id, query=query)
Creates an entry with a given ID (optional) and attributes. def create(self, resource_id=None, attributes=None, **kwargs): """ Creates an entry with a given ID (optional) and attributes. """ if self.content_type_id is not None: if attributes is None: attributes = {} attributes['content_type_id'] = self.content_type_id return super(EntriesProxy, self).create(resource_id=resource_id, attributes=attributes)
Creates a webhook with given attributes. def create(self, attributes=None, **kwargs): """ Creates a webhook with given attributes. """ return super(WebhooksProxy, self).create(resource_id=None, attributes=attributes)
Returns a camel-cased version of a string. :param a_string: any :class:`str` object. Usage: >>> camel_case('foo_bar') "fooBar" def camel_case(snake_str): """ Returns a camel-cased version of a string. :param a_string: any :class:`str` object. Usage: >>> camel_case('foo_bar') "fooBar" """ components = snake_str.split('_') # We capitalize the first letter of each component except the first one # with the 'title' method and join them together. return components[0] + "".join(x.title() for x in components[1:])
If the query contains the :select operator, we enforce :sys properties. The SDK requires sys.type to function properly, but as other of our SDKs require more parts of the :sys properties, we decided that every SDK should include the complete :sys block to provide consistency accross our SDKs. def normalize_select(query): """ If the query contains the :select operator, we enforce :sys properties. The SDK requires sys.type to function properly, but as other of our SDKs require more parts of the :sys properties, we decided that every SDK should include the complete :sys block to provide consistency accross our SDKs. """ if 'select' not in query: return if isinstance( query['select'], str_type()): query['select'] = [s.strip() for s in query['select'].split(',')] query['select'] = [s for s in query['select'] if not s.startswith('sys.')] if 'sys' not in query['select']: query['select'].append('sys')
Returns the JSON representation of the environment. def to_json(self): """ Returns the JSON representation of the environment. """ result = super(Environment, self).to_json() result.update({ 'name': self.name }) return result
Provides access to content type management methods for content types of an environment. API reference: https://www.contentful.com/developers/docs/references/content-management-api/#/reference/content-types :return: :class:`EnvironmentContentTypesProxy <contentful_management.space_content_types_proxy.EnvironmentContentTypesProxy>` object. :rtype: contentful.space_content_types_proxy.EnvironmentContentTypesProxy Usage: >>> space_content_types_proxy = environment.content_types() <EnvironmentContentTypesProxy space_id="cfexampleapi" environment_id="master"> def content_types(self): """ Provides access to content type management methods for content types of an environment. API reference: https://www.contentful.com/developers/docs/references/content-management-api/#/reference/content-types :return: :class:`EnvironmentContentTypesProxy <contentful_management.space_content_types_proxy.EnvironmentContentTypesProxy>` object. :rtype: contentful.space_content_types_proxy.EnvironmentContentTypesProxy Usage: >>> space_content_types_proxy = environment.content_types() <EnvironmentContentTypesProxy space_id="cfexampleapi" environment_id="master"> """ return EnvironmentContentTypesProxy(self._client, self.space.id, self.id)
Provides access to entry management methods. API reference: https://www.contentful.com/developers/docs/references/content-management-api/#/reference/entries :return: :class:`EnvironmentEntriesProxy <contentful_management.environment_entries_proxy.EnvironmentEntriesProxy>` object. :rtype: contentful.environment_entries_proxy.EnvironmentEntriesProxy Usage: >>> environment_entries_proxy = environment.entries() <EnvironmentEntriesProxy space_id="cfexampleapi" environment_id="master"> def entries(self): """ Provides access to entry management methods. API reference: https://www.contentful.com/developers/docs/references/content-management-api/#/reference/entries :return: :class:`EnvironmentEntriesProxy <contentful_management.environment_entries_proxy.EnvironmentEntriesProxy>` object. :rtype: contentful.environment_entries_proxy.EnvironmentEntriesProxy Usage: >>> environment_entries_proxy = environment.entries() <EnvironmentEntriesProxy space_id="cfexampleapi" environment_id="master"> """ return EnvironmentEntriesProxy(self._client, self.space.id, self.id)
Provides access to asset management methods. API reference: https://www.contentful.com/developers/docs/references/content-management-api/#/reference/assets :return: :class:`EnvironmentAssetsProxy <contentful_management.environment_assets_proxy.EnvironmentAssetsProxy>` object. :rtype: contentful.environment_assets_proxy.EnvironmentAssetsProxy Usage: >>> environment_assets_proxy = environment.assets() <EnvironmentAssetsProxy space_id="cfexampleapi" environment_id="master"> def assets(self): """ Provides access to asset management methods. API reference: https://www.contentful.com/developers/docs/references/content-management-api/#/reference/assets :return: :class:`EnvironmentAssetsProxy <contentful_management.environment_assets_proxy.EnvironmentAssetsProxy>` object. :rtype: contentful.environment_assets_proxy.EnvironmentAssetsProxy Usage: >>> environment_assets_proxy = environment.assets() <EnvironmentAssetsProxy space_id="cfexampleapi" environment_id="master"> """ return EnvironmentAssetsProxy(self._client, self.space.id, self.id)
Provides access to locale management methods. API reference: https://www.contentful.com/developers/docs/references/content-management-api/#/reference/locales :return: :class:`EnvironmentLocalesProxy <contentful_management.environment_locales_proxy.EnvironmentLocalesProxy>` object. :rtype: contentful.environment_locales_proxy.EnvironmentLocalesProxy Usage: >>> environment_locales_proxy = environment.locales() <EnvironmentLocalesProxy space_id="cfexampleapi" environment_id="master"> def locales(self): """ Provides access to locale management methods. API reference: https://www.contentful.com/developers/docs/references/content-management-api/#/reference/locales :return: :class:`EnvironmentLocalesProxy <contentful_management.environment_locales_proxy.EnvironmentLocalesProxy>` object. :rtype: contentful.environment_locales_proxy.EnvironmentLocalesProxy Usage: >>> environment_locales_proxy = environment.locales() <EnvironmentLocalesProxy space_id="cfexampleapi" environment_id="master"> """ return EnvironmentLocalesProxy(self._client, self.space.id, self.id)
Provides access to UI extensions management methods. API reference: https://www.contentful.com/developers/docs/references/content-management-api/#/reference/ui-extensions :return: :class:`EnvironmentUIExtensionsProxy <contentful_management.ui_extensions_proxy.EnvironmentUIExtensionsProxy>` object. :rtype: contentful.ui_extensions_proxy.EnvironmentUIExtensionsProxy Usage: >>> ui_extensions_proxy = environment.ui_extensions() <EnvironmentUIExtensionsProxy space_id="cfexampleapi" environment_id="master"> def ui_extensions(self): """ Provides access to UI extensions management methods. API reference: https://www.contentful.com/developers/docs/references/content-management-api/#/reference/ui-extensions :return: :class:`EnvironmentUIExtensionsProxy <contentful_management.ui_extensions_proxy.EnvironmentUIExtensionsProxy>` object. :rtype: contentful.ui_extensions_proxy.EnvironmentUIExtensionsProxy Usage: >>> ui_extensions_proxy = environment.ui_extensions() <EnvironmentUIExtensionsProxy space_id="cfexampleapi" environment_id="master"> """ return EnvironmentUIExtensionsProxy(self._client, self.space.id, self.id)
Revokes a personal access token. def delete(self, token_id, *args, **kwargs): """ Revokes a personal access token. """ return self.client._put( "{0}/revoked".format( self._url(token_id) ), None, *args, **kwargs )
Revokes a personal access token. def revoke(self, token_id, *args, **kwargs): """ Revokes a personal access token. """ return self.delete(token_id, *args, **kwargs)
Returns the URI for the resource. def base_url(klass, space_id='', resource_id=None, environment_id=None, **kwargs): """ Returns the URI for the resource. """ url = "spaces/{0}".format( space_id) if environment_id is not None: url = url = "{0}/environments/{1}".format(url, environment_id) url = "{0}/{1}".format( url, base_path_for(klass.__name__) ) if resource_id: url = "{0}/{1}".format(url, resource_id) return url
Attributes for resource creation. def create_attributes(klass, attributes, previous_object=None): """ Attributes for resource creation. """ result = {} if previous_object is not None: result = {k: v for k, v in previous_object.to_json().items() if k != 'sys'} result.update(attributes) return result
Deletes the resource. def delete(self): """ Deletes the resource. """ return self._client._delete( self.__class__.base_url( self.sys['space'].id, self.sys['id'], environment_id=self._environment_id ) )
Updates the resource with attributes. def update(self, attributes=None): """ Updates the resource with attributes. """ if attributes is None: attributes = {} headers = self.__class__.create_headers(attributes) headers.update(self._update_headers()) result = self._client._put( self._update_url(), self.__class__.create_attributes(attributes, self), headers=headers ) self._update_from_resource(result) return self
Reloads the resource. def reload(self, result=None): """ Reloads the resource. """ if result is None: result = self._client._get( self.__class__.base_url( self.sys['space'].id, self.sys['id'], environment_id=self._environment_id ) ) self._update_from_resource(result) return self
Returns a link for the resource. def to_link(self): """ Returns a link for the resource. """ link_type = self.link_type if self.type == 'Link' else self.type return Link({'sys': {'linkType': link_type, 'id': self.sys.get('id')}}, client=self._client)
Returns the JSON representation of the resource. def to_json(self): """ Returns the JSON representation of the resource. """ result = { 'sys': {} } for k, v in self.sys.items(): if k in ['space', 'content_type', 'created_by', 'updated_by', 'published_by']: v = v.to_json() if k in ['created_at', 'updated_at', 'deleted_at', 'first_published_at', 'published_at', 'expires_at']: v = v.isoformat() result['sys'][camel_case(k)] = v return result
Attributes for resource creation. def create_attributes(klass, attributes, previous_object=None): """ Attributes for resource creation. """ if 'fields' not in attributes: if previous_object is None: attributes['fields'] = {} else: attributes['fields'] = previous_object.to_json()['fields'] return {'fields': attributes['fields']}
Get fields with locales per field. def fields_with_locales(self): """ Get fields with locales per field. """ result = {} for locale, fields in self._fields.items(): for k, v in fields.items(): real_field_id = self._real_field_id_for(k) if real_field_id not in result: result[real_field_id] = {} result[real_field_id][locale] = self._serialize_value(v) return result
Returns the JSON Representation of the resource. def to_json(self): """ Returns the JSON Representation of the resource. """ result = super(FieldsResource, self).to_json() result['fields'] = self.fields_with_locales() return result
Checks if a resource has been updated since last publish. Returns False if resource has not been published before. def is_updated(self): """ Checks if a resource has been updated since last publish. Returns False if resource has not been published before. """ if not self.is_published: return False return sanitize_date(self.sys['published_at']) < sanitize_date(self.sys['updated_at'])
Unpublishes the resource. def unpublish(self): """ Unpublishes the resource. """ self._client._delete( "{0}/published".format( self.__class__.base_url( self.sys['space'].id, self.sys['id'], environment_id=self._environment_id ), ), headers=self._update_headers() ) return self.reload()
Archives the resource. def archive(self): """ Archives the resource. """ self._client._put( "{0}/archived".format( self.__class__.base_url( self.sys['space'].id, self.sys['id'], environment_id=self._environment_id ), ), {}, headers=self._update_headers() ) return self.reload()
Resolves link to a specific resource. def resolve(self, space_id=None, environment_id=None): """ Resolves link to a specific resource. """ proxy_method = getattr( self._client, base_path_for(self.link_type) ) if self.link_type == 'Space': return proxy_method().find(self.id) elif environment_id is not None: return proxy_method(space_id, environment_id).find(self.id) else: return proxy_method(space_id).find(self.id)
Returns a formatted URL for the asset's File with serialized parameters. Usage: >>> my_asset.url() "//images.contentful.com/spaces/foobar/..." >>> my_asset.url(w=120, h=160) "//images.contentful.com/spaces/foobar/...?w=120&h=160" def url(self, **kwargs): """ Returns a formatted URL for the asset's File with serialized parameters. Usage: >>> my_asset.url() "//images.contentful.com/spaces/foobar/..." >>> my_asset.url(w=120, h=160) "//images.contentful.com/spaces/foobar/...?w=120&h=160" """ url = self.fields(self._locale()).get('file', {}).get('url', '') args = ['{0}={1}'.format(k, v) for k, v in kwargs.items()] if args: url += '?{0}'.format('&'.join(args)) return url
Calls the process endpoint for all locales of the asset. API reference: https://www.contentful.com/developers/docs/references/content-management-api/#/reference/assets/asset-processing def process(self): """ Calls the process endpoint for all locales of the asset. API reference: https://www.contentful.com/developers/docs/references/content-management-api/#/reference/assets/asset-processing """ for locale in self._fields.keys(): self._client._put( "{0}/files/{1}/process".format( self.__class__.base_url( self.space.id, self.id, environment_id=self._environment_id ), locale ), {}, headers=self._update_headers() ) return self.reload()
Returns the JSON Representation of the UI extension. def to_json(self): """ Returns the JSON Representation of the UI extension. """ result = super(UIExtension, self).to_json() result.update({ 'extension': self.extension }) return result
Attributes for resource creation. def create_attributes(klass, attributes, previous_object=None): """ Attributes for resource creation. """ return { 'name': attributes.get( 'name', previous_object.name if previous_object is not None else '' ), 'description': attributes.get( 'description', previous_object.description if previous_object is not None else '' ), 'environments': attributes.get( 'environments', [e.to_json() for e in previous_object.environments] if previous_object is not None else [] # Will default to master if empty ) }
Returns the JSON representation of the API key. def to_json(self): """ Returns the JSON representation of the API key. """ result = super(ApiKey, self).to_json() result.update({ 'name': self.name, 'description': self.description, 'accessToken': self.access_token, 'environments': [e.to_json() for e in self.environments] }) return result
Gets all api usages by type for a given period an api. def all(self, usage_type, usage_period_id, api, query=None, *args, **kwargs): """ Gets all api usages by type for a given period an api. """ if query is None: query = {} mandatory_query = { 'filters[usagePeriod]': usage_period_id, 'filters[metric]': api } mandatory_query.update(query) return self.client._get( self._url(usage_type), mandatory_query, headers={ 'x-contentful-enable-alpha-feature': 'usage-insights' } )
Returns the URI for the content type. def base_url(klass, space_id, resource_id=None, public=False, environment_id=None, **kwargs): """ Returns the URI for the content type. """ if public: environment_slug = "" if environment_id is not None: environment_slug = "/environments/{0}".format(environment_id) return "spaces/{0}{1}/public/content_types".format(space_id, environment_slug) return super(ContentType, klass).base_url( space_id, resource_id=resource_id, environment_id=environment_id, **kwargs )
Attributes for content type creation. def create_attributes(klass, attributes, previous_object=None): """ Attributes for content type creation. """ result = super(ContentType, klass).create_attributes(attributes, previous_object) if 'fields' not in result: result['fields'] = [] return result
Returns the JSON representation of the content type. def to_json(self): """ Returns the JSON representation of the content type. """ result = super(ContentType, self).to_json() result.update({ 'name': self.name, 'description': self.description, 'displayField': self.display_field, 'fields': [f.to_json() for f in self.fields] }) return result
Provides access to entry management methods for the given content type. API reference: https://www.contentful.com/developers/docs/references/content-management-api/#/reference/entries :return: :class:`ContentTypeEntriesProxy <contentful_management.content_type_entries_proxy.ContentTypeEntriesProxy>` object. :rtype: contentful.content_type_entries_proxy.ContentTypeEntriesProxy Usage: >>> content_type_entries_proxy = content_type.entries() <ContentTypeEntriesProxy space_id="cfexampleapi" environment_id="master" content_type_id="cat"> def entries(self): """ Provides access to entry management methods for the given content type. API reference: https://www.contentful.com/developers/docs/references/content-management-api/#/reference/entries :return: :class:`ContentTypeEntriesProxy <contentful_management.content_type_entries_proxy.ContentTypeEntriesProxy>` object. :rtype: contentful.content_type_entries_proxy.ContentTypeEntriesProxy Usage: >>> content_type_entries_proxy = content_type.entries() <ContentTypeEntriesProxy space_id="cfexampleapi" environment_id="master" content_type_id="cat"> """ return ContentTypeEntriesProxy(self._client, self.space.id, self._environment_id, self.id)
Provides access to editor interface management methods for the given content type. API reference: https://www.contentful.com/developers/docs/references/content-management-api/#/reference/editor-interface :return: :class:`ContentTypeEditorInterfacesProxy <contentful_management.content_type_editor_interfaces_proxy.ContentTypeEditorInterfacesProxy>` object. :rtype: contentful.content_type_editor_interfaces_proxy.ContentTypeEditorInterfacesProxy Usage: >>> content_type_editor_interfaces_proxy = content_type.editor_interfaces() <ContentTypeEditorInterfacesProxy space_id="cfexampleapi" environment_id="master" content_type_id="cat"> def editor_interfaces(self): """ Provides access to editor interface management methods for the given content type. API reference: https://www.contentful.com/developers/docs/references/content-management-api/#/reference/editor-interface :return: :class:`ContentTypeEditorInterfacesProxy <contentful_management.content_type_editor_interfaces_proxy.ContentTypeEditorInterfacesProxy>` object. :rtype: contentful.content_type_editor_interfaces_proxy.ContentTypeEditorInterfacesProxy Usage: >>> content_type_editor_interfaces_proxy = content_type.editor_interfaces() <ContentTypeEditorInterfacesProxy space_id="cfexampleapi" environment_id="master" content_type_id="cat"> """ return ContentTypeEditorInterfacesProxy(self._client, self.space.id, self._environment_id, self.id)
Provides access to snapshot management methods for the given content type. API reference: https://www.contentful.com/developers/docs/references/content-management-api/#/reference/snapshots/content-type-snapshots-collection :return: :class:`ContentTypeSnapshotsProxy <contentful_management.content_type_snapshots_proxy.ContentTypeSnapshotsProxy>` object. :rtype: contentful.content_type_snapshots_proxy.ContentTypeSnapshotsProxy Usage: >>> content_type_snapshots_proxy = content_type.entries() <ContentTypeSnapshotsProxy space_id="cfexampleapi" environment_id="master" content_type_id="cat"> def snapshots(self): """ Provides access to snapshot management methods for the given content type. API reference: https://www.contentful.com/developers/docs/references/content-management-api/#/reference/snapshots/content-type-snapshots-collection :return: :class:`ContentTypeSnapshotsProxy <contentful_management.content_type_snapshots_proxy.ContentTypeSnapshotsProxy>` object. :rtype: contentful.content_type_snapshots_proxy.ContentTypeSnapshotsProxy Usage: >>> content_type_snapshots_proxy = content_type.entries() <ContentTypeSnapshotsProxy space_id="cfexampleapi" environment_id="master" content_type_id="cat"> """ return ContentTypeSnapshotsProxy(self._client, self.space.id, self._environment_id, self.id)
Gets all organizations. def all(self, query=None, **kwargs): """ Gets all organizations. """ return super(OrganizationsProxy, self).all(query=query)
Returns the URI for the webhook call. def base_url(klass, space_id, webhook_id, resource_id=None): """ Returns the URI for the webhook call. """ return "spaces/{0}/webhooks/{1}/calls/{2}".format( space_id, webhook_id, resource_id if resource_id is not None else '' )
Attributes for space creation. def create_attributes(klass, attributes, previous_object=None): """Attributes for space creation.""" if previous_object is not None: return {'name': attributes.get('name', previous_object.name)} return { 'name': attributes.get('name', ''), 'defaultLocale': attributes['default_locale'] }
Reloads the space. def reload(self): """ Reloads the space. """ result = self._client._get( self.__class__.base_url( self.sys['id'] ) ) self._update_from_resource(result) return self
Deletes the space def delete(self): """ Deletes the space """ return self._client._delete( self.__class__.base_url( self.sys['id'] ) )
Returns the JSON representation of the space. def to_json(self): """ Returns the JSON representation of the space. """ result = super(Space, self).to_json() result.update({'name': self.name}) return result
Gets all spaces. def all(self, query=None, **kwargs): """ Gets all spaces. """ return super(SpacesProxy, self).all(query=query)
Gets a space by ID. def find(self, space_id, query=None, **kwargs): """ Gets a space by ID. """ try: self.space_id = space_id return super(SpacesProxy, self).find(space_id, query=query) finally: self.space_id = None
Creates a space with given attributes. def create(self, attributes=None, **kwargs): """ Creates a space with given attributes. """ if attributes is None: attributes = {} if 'default_locale' not in attributes: attributes['default_locale'] = self.client.default_locale return super(SpacesProxy, self).create(resource_id=None, attributes=attributes)
Deletes a space by ID. def delete(self, space_id): """ Deletes a space by ID. """ try: self.space_id = space_id return super(SpacesProxy, self).delete(space_id) finally: self.space_id = None
Provides access to editor interfaces management methods. API reference: https://www.contentful.com/developers/docs/references/content-management-api/#/reference/editor-interface :return: :class:`EditorInterfacesProxy <contentful_management.editor_interfaces_proxy.EditorInterfacesProxy>` object. :rtype: contentful.editor_interfaces_proxy.EditorInterfacesProxy Usage: >>> editor_interfaces_proxy = client.editor_interfaces('cfexampleapi', 'master', 'cat') <EditorInterfacesProxy space_id="cfexampleapi" environment_id="master" content_type_id="cat"> def editor_interfaces(self, space_id, environment_id, content_type_id): """ Provides access to editor interfaces management methods. API reference: https://www.contentful.com/developers/docs/references/content-management-api/#/reference/editor-interface :return: :class:`EditorInterfacesProxy <contentful_management.editor_interfaces_proxy.EditorInterfacesProxy>` object. :rtype: contentful.editor_interfaces_proxy.EditorInterfacesProxy Usage: >>> editor_interfaces_proxy = client.editor_interfaces('cfexampleapi', 'master', 'cat') <EditorInterfacesProxy space_id="cfexampleapi" environment_id="master" content_type_id="cat"> """ return EditorInterfacesProxy(self, space_id, environment_id, content_type_id)
Provides access to snapshot management methods. API reference: https://www.contentful.com/developers/docs/references/content-management-api/#/reference/snapshots :return: :class:`SnapshotsProxy <contentful_management.snapshots_proxy.SnapshotsProxy>` object. :rtype: contentful.snapshots_proxy.SnapshotsProxy Usage: >>> entry_snapshots_proxy = client.snapshots('cfexampleapi', 'master', 'nyancat') <SnapshotsProxy[entries] space_id="cfexampleapi" environment_id="master" parent_resource_id="nyancat"> >>> content_type_snapshots_proxy = client.snapshots('cfexampleapi', 'master', 'cat', 'content_types') <SnapshotsProxy[content_types] space_id="cfexampleapi" environment_id="master" parent_resource_id="cat"> def snapshots(self, space_id, environment_id, resource_id, resource_kind='entries'): """ Provides access to snapshot management methods. API reference: https://www.contentful.com/developers/docs/references/content-management-api/#/reference/snapshots :return: :class:`SnapshotsProxy <contentful_management.snapshots_proxy.SnapshotsProxy>` object. :rtype: contentful.snapshots_proxy.SnapshotsProxy Usage: >>> entry_snapshots_proxy = client.snapshots('cfexampleapi', 'master', 'nyancat') <SnapshotsProxy[entries] space_id="cfexampleapi" environment_id="master" parent_resource_id="nyancat"> >>> content_type_snapshots_proxy = client.snapshots('cfexampleapi', 'master', 'cat', 'content_types') <SnapshotsProxy[content_types] space_id="cfexampleapi" environment_id="master" parent_resource_id="cat"> """ return SnapshotsProxy(self, space_id, environment_id, resource_id, resource_kind)
Provides access to entry snapshot management methods. API reference: https://www.contentful.com/developers/docs/references/content-management-api/#/reference/snapshots :return: :class:`SnapshotsProxy <contentful_management.snapshots_proxy.SnapshotsProxy>` object. :rtype: contentful.snapshots_proxy.SnapshotsProxy Usage: >>> entry_snapshots_proxy = client.entry_snapshots('cfexampleapi', 'master', 'nyancat') <SnapshotsProxy[entries] space_id="cfexampleapi" environment_id="master" parent_resource_id="nyancat"> def entry_snapshots(self, space_id, environment_id, entry_id): """ Provides access to entry snapshot management methods. API reference: https://www.contentful.com/developers/docs/references/content-management-api/#/reference/snapshots :return: :class:`SnapshotsProxy <contentful_management.snapshots_proxy.SnapshotsProxy>` object. :rtype: contentful.snapshots_proxy.SnapshotsProxy Usage: >>> entry_snapshots_proxy = client.entry_snapshots('cfexampleapi', 'master', 'nyancat') <SnapshotsProxy[entries] space_id="cfexampleapi" environment_id="master" parent_resource_id="nyancat"> """ return SnapshotsProxy(self, space_id, environment_id, entry_id, 'entries')
Provides access to content type snapshot management methods. API reference: https://www.contentful.com/developers/docs/references/content-management-api/#/reference/snapshots :return: :class:`SnapshotsProxy <contentful_management.snapshots_proxy.SnapshotsProxy>` object. :rtype: contentful.snapshots_proxy.SnapshotsProxy Usage: >>> content_type_snapshots_proxy = client.content_type_snapshots('cfexampleapi', 'master', 'cat') <SnapshotsProxy[content_types] space_id="cfexampleapi" environment_id="master" parent_resource_id="cat"> def content_type_snapshots(self, space_id, environment_id, content_type_id): """ Provides access to content type snapshot management methods. API reference: https://www.contentful.com/developers/docs/references/content-management-api/#/reference/snapshots :return: :class:`SnapshotsProxy <contentful_management.snapshots_proxy.SnapshotsProxy>` object. :rtype: contentful.snapshots_proxy.SnapshotsProxy Usage: >>> content_type_snapshots_proxy = client.content_type_snapshots('cfexampleapi', 'master', 'cat') <SnapshotsProxy[content_types] space_id="cfexampleapi" environment_id="master" parent_resource_id="cat"> """ return SnapshotsProxy(self, space_id, environment_id, content_type_id, 'content_types')
Validates that required parameters are present. def _validate_configuration(self): """ Validates that required parameters are present. """ if not self.access_token: raise ConfigurationException( 'You will need to initialize a client with an Access Token' ) if not self.api_url: raise ConfigurationException( 'The client configuration needs to contain an API URL' ) if not self.default_locale: raise ConfigurationException( 'The client configuration needs to contain a Default Locale' ) if not self.api_version or self.api_version < 1: raise ConfigurationException( 'The API Version must be a positive number' )
Sets the X-Contentful-User-Agent header. def _contentful_user_agent(self): """ Sets the X-Contentful-User-Agent header. """ header = {} from . import __version__ header['sdk'] = { 'name': 'contentful-management.py', 'version': __version__ } header['app'] = { 'name': self.application_name, 'version': self.application_version } header['integration'] = { 'name': self.integration_name, 'version': self.integration_version } header['platform'] = { 'name': 'python', 'version': platform.python_version() } os_name = platform.system() if os_name == 'Darwin': os_name = 'macOS' elif not os_name or os_name == 'Java': os_name = None elif os_name and os_name not in ['macOS', 'Windows']: os_name = 'Linux' header['os'] = { 'name': os_name, 'version': platform.release() } def format_header(key, values): header = "{0} {1}".format(key, values['name']) if values['version'] is not None: header = "{0}/{1}".format(header, values['version']) return "{0};".format(header) result = [] for k, values in header.items(): if not values['name']: continue result.append(format_header(k, values)) return ' '.join(result)
Creates the request URL. def _url(self, url, file_upload=False): """ Creates the request URL. """ host = self.api_url if file_upload: host = self.uploads_api_url protocol = 'https' if self.https else 'http' if url.endswith('/'): url = url[:-1] return '{0}://{1}/{2}'.format( protocol, host, url )
Performs the requested HTTP request. def _http_request(self, method, url, request_kwargs=None): """ Performs the requested HTTP request. """ kwargs = request_kwargs if request_kwargs is not None else {} headers = self._request_headers() headers.update(self.additional_headers) if 'headers' in kwargs: headers.update(kwargs['headers']) kwargs['headers'] = headers if self._has_proxy(): kwargs['proxies'] = self._proxy_parameters() request_url = self._url( url, file_upload=kwargs.pop('file_upload', False) ) request_method = getattr(requests, method) response = request_method(request_url, **kwargs) if response.status_code == 429: raise RateLimitExceededError(response) return response
Performs the HTTP GET request. def _http_get(self, url, query, **kwargs): """ Performs the HTTP GET request. """ self._normalize_query(query) kwargs.update({'params': query}) return self._http_request('get', url, kwargs)
Performs the HTTP POST request. def _http_post(self, url, data, **kwargs): """ Performs the HTTP POST request. """ if not kwargs.get('file_upload', False): data = json.dumps(data) kwargs.update({'data': data}) return self._http_request('post', url, kwargs)
Performs the HTTP PUT request. def _http_put(self, url, data, **kwargs): """ Performs the HTTP PUT request. """ kwargs.update({'data': json.dumps(data)}) return self._http_request('put', url, kwargs)
Wrapper for the HTTP requests, rate limit backoff is handled here, responses are processed with ResourceBuilder. def _request(self, method, url, query_or_data=None, **kwargs): """ Wrapper for the HTTP requests, rate limit backoff is handled here, responses are processed with ResourceBuilder. """ if query_or_data is None: query_or_data = {} request_method = getattr(self, '_http_{0}'.format(method)) response = retry_request(self)(request_method)(url, query_or_data, **kwargs) if self.raw_mode: return response if response.status_code >= 300: error = get_error(response) if self.raise_errors: raise error return error # Return response object on NoContent if response.status_code == 204 or not response.text: return response return ResourceBuilder( self, self.default_locale, response.json() ).build()
Wrapper for the HTTP GET request. def _get(self, url, query=None, **kwargs): """ Wrapper for the HTTP GET request. """ return self._request('get', url, query, **kwargs)
Wrapper for the HTTP POST request. def _post(self, url, attributes=None, **kwargs): """ Wrapper for the HTTP POST request. """ return self._request('post', url, attributes, **kwargs)
Wrapper for the HTTP PUT request. def _put(self, url, attributes=None, **kwargs): """ Wrapper for the HTTP PUT request. """ return self._request('put', url, attributes, **kwargs)
Wrapper for the HTTP DELETE request. def _delete(self, url, **kwargs): """ Wrapper for the HTTP DELETE request. """ response = retry_request(self)(self._http_delete)(url, **kwargs) if self.raw_mode: return response if response.status_code >= 300: error = get_error(response) if self.raise_errors: raise error return error return response
Returns the JSON representation of the locale. def to_json(self): """ Returns the JSON representation of the locale. """ result = super(Locale, self).to_json() result.update({ 'code': self.code, 'name': self.name, 'fallbackCode': self.fallback_code, 'optional': self.optional, 'contentDeliveryApi': self.content_delivery_api, 'contentManagementApi': self.content_management_api }) return result
Gets all assets of a space. def all(self, query=None, **kwargs): """ Gets all assets of a space. """ if query is None: query = {} normalize_select(query) return super(AssetsProxy, self).all(query, **kwargs)
Gets a single asset by ID. def find(self, asset_id, query=None, **kwargs): """ Gets a single asset by ID. """ if query is None: query = {} normalize_select(query) return super(AssetsProxy, self).find(asset_id, query=query, **kwargs)
Provides access to snapshot management methods for the given entry. API reference: https://www.contentful.com/developers/docs/references/content-management-api/#/reference/snapshots :return: :class:`EntrySnapshotsProxy <contentful_management.entry_snapshots_proxy.EntrySnapshotsProxy>` object. :rtype: contentful.entry_snapshots_proxy.EntrySnapshotsProxy Usage: >>> entry_snapshots_proxy = entry.snapshots() <EntrySnapshotsProxy space_id="cfexampleapi" environment_id="master" entry_id="nyancat"> def snapshots(self): """ Provides access to snapshot management methods for the given entry. API reference: https://www.contentful.com/developers/docs/references/content-management-api/#/reference/snapshots :return: :class:`EntrySnapshotsProxy <contentful_management.entry_snapshots_proxy.EntrySnapshotsProxy>` object. :rtype: contentful.entry_snapshots_proxy.EntrySnapshotsProxy Usage: >>> entry_snapshots_proxy = entry.snapshots() <EntrySnapshotsProxy space_id="cfexampleapi" environment_id="master" entry_id="nyancat"> """ return EntrySnapshotsProxy(self._client, self.sys['space'].id, self._environment_id, self.sys['id'])
Updates the entry with attributes. def update(self, attributes=None): """ Updates the entry with attributes. """ if attributes is None: attributes = {} attributes['content_type_id'] = self.sys['content_type'].id return super(Entry, self).update(attributes)
Gets resource collection for _resource_class. def all(self, query=None): """ Gets resource collection for _resource_class. """ if query is None: query = {} return self.client._get( self._url(), query )
Gets a single resource. def find(self, resource_id, query=None, **kwargs): """Gets a single resource.""" if query is None: query = {} return self.client._get( self._url(resource_id), query, **kwargs )
Creates a resource with the given ID (optional) and attributes. def create(self, resource_id=None, attributes=None): """ Creates a resource with the given ID (optional) and attributes. """ if attributes is None: attributes = {} result = None if not resource_id: result = self.client._post( self._url(resource_id), self._resource_class.create_attributes(attributes), headers=self._resource_class.create_headers(attributes) ) else: result = self.client._put( self._url(resource_id), self._resource_class.create_attributes(attributes), headers=self._resource_class.create_headers(attributes) ) return result
Deletes a resource by ID. def delete(self, resource_id, **kwargs): """ Deletes a resource by ID. """ return self.client._delete(self._url(resource_id), **kwargs)
Returns the JSON representation of the role. def to_json(self): """ Returns the JSON representation of the role. """ result = super(Role, self).to_json() result.update({ 'name': self.name, 'description': self.description, 'permissions': self.permissions, 'policies': self.policies }) return result
Returns the JSON representation of the space membership. def to_json(self): """ Returns the JSON representation of the space membership. """ result = super(SpaceMembership, self).to_json() result.update({ 'admin': self.admin, 'roles': self.roles }) return result
Creates an upload for the given file or path. def create(self, file_or_path, **kwargs): """ Creates an upload for the given file or path. """ opened = False if isinstance(file_or_path, str_type()): file_or_path = open(file_or_path, 'rb') opened = True elif not getattr(file_or_path, 'read', False): raise Exception("A file or path to a file is required for this operation.") try: return self.client._post( self._url(), file_or_path, headers=self._resource_class.create_headers({}), file_upload=True ) finally: if opened: file_or_path.close()
Finds an upload by ID. def find(self, upload_id, **kwargs): """ Finds an upload by ID. """ return super(UploadsProxy, self).find(upload_id, file_upload=True)
Deletes an upload by ID. def delete(self, upload_id): """ Deletes an upload by ID. """ return super(UploadsProxy, self).delete(upload_id, file_upload=True)
Returns the JSON Representation of the content type field. def to_json(self): """ Returns the JSON Representation of the content type field. """ result = { 'name': self.name, 'id': self._real_id(), 'type': self.type, 'localized': self.localized, 'omitted': self.omitted, 'required': self.required, 'disabled': self.disabled, 'validations': [v.to_json() for v in self.validations] } if self.type == 'Array': result['items'] = self.items if self.type == 'Link': result['linkType'] = self.link_type return result
Coerces value to location hash. def coerce(self, value): """ Coerces value to location hash. """ return { 'lat': float(value.get('lat', value.get('latitude'))), 'lon': float(value.get('lon', value.get('longitude'))) }
Returns the URI for the snapshot. def base_url(klass, space_id, parent_resource_id, resource_url='entries', resource_id=None, environment_id=None): """ Returns the URI for the snapshot. """ return "spaces/{0}{1}/{2}/{3}/snapshots/{4}".format( space_id, '/environments/{0}'.format(environment_id) if environment_id is not None else '', resource_url, parent_resource_id, resource_id if resource_id is not None else '' )
Returns the JSON representation of the snapshot. def to_json(self): """ Returns the JSON representation of the snapshot. """ result = super(Snapshot, self).to_json() result.update({ 'snapshot': self.snapshot.to_json(), }) return result
Gets all usage periods. def all(self, *args, **kwargs): """ Gets all usage periods. """ return self.client._get( self._url(), {}, headers={ 'x-contentful-enable-alpha-feature': 'usage-insights' } )
Attributes for webhook creation. def create_attributes(klass, attributes, previous_object=None): """ Attributes for webhook creation. """ result = super(Webhook, klass).create_attributes(attributes, previous_object) if 'topics' not in result: raise Exception("Topics ('topics') must be provided for this operation.") return result
Provides access to call overview for the given webhook. API reference: https://www.contentful.com/developers/docs/references/content-management-api/#/reference/webhook-calls :return: :class:`WebhookWebhooksCallProxy <contentful_management.webhook_webhooks_call_proxy.WebhookWebhooksCallProxy>` object. :rtype: contentful.webhook_webhooks_call_proxy.WebhookWebhooksCallProxy Usage: >>> webhook_webhooks_call_proxy = webhook.calls() <WebhookWebhooksCallProxy space_id="cfexampleapi" webhook_id="my_webhook"> def calls(self): """ Provides access to call overview for the given webhook. API reference: https://www.contentful.com/developers/docs/references/content-management-api/#/reference/webhook-calls :return: :class:`WebhookWebhooksCallProxy <contentful_management.webhook_webhooks_call_proxy.WebhookWebhooksCallProxy>` object. :rtype: contentful.webhook_webhooks_call_proxy.WebhookWebhooksCallProxy Usage: >>> webhook_webhooks_call_proxy = webhook.calls() <WebhookWebhooksCallProxy space_id="cfexampleapi" webhook_id="my_webhook"> """ return WebhookWebhooksCallProxy(self._client, self.sys['space'].id, self.sys['id'])
Provides access to health overview for the given webhook. API reference: https://www.contentful.com/developers/docs/references/content-management-api/#/reference/webhook-calls/webhook-health :return: :class:`WebhookWebhooksHealthProxy <contentful_management.webhook_webhooks_health_proxy.WebhookWebhooksHealthProxy>` object. :rtype: contentful.webhook_webhooks_health_proxy.WebhookWebhooksHealthProxy Usage: >>> webhook_webhooks_health_proxy = webhook.health() <WebhookWebhooksHealthProxy space_id="cfexampleapi" webhook_id="my_webhook"> def health(self): """ Provides access to health overview for the given webhook. API reference: https://www.contentful.com/developers/docs/references/content-management-api/#/reference/webhook-calls/webhook-health :return: :class:`WebhookWebhooksHealthProxy <contentful_management.webhook_webhooks_health_proxy.WebhookWebhooksHealthProxy>` object. :rtype: contentful.webhook_webhooks_health_proxy.WebhookWebhooksHealthProxy Usage: >>> webhook_webhooks_health_proxy = webhook.health() <WebhookWebhooksHealthProxy space_id="cfexampleapi" webhook_id="my_webhook"> """ return WebhookWebhooksHealthProxy(self._client, self.sys['space'].id, self.sys['id'])
Returns the JSON representation of the webhook. def to_json(self): """ Returns the JSON representation of the webhook. """ result = super(Webhook, self).to_json() result.update({ 'name': self.name, 'url': self.url, 'topics': self.topics, 'httpBasicUsername': self.http_basic_username, 'headers': self.headers }) if self.filters: result.update({'filters': self.filters}) if self.transformation: result.update({'transformation': self.transformation}) return result
Returns the URI for the editor interface. def base_url(self, space_id, content_type_id, environment_id=None, **kwargs): """ Returns the URI for the editor interface. """ return "spaces/{0}{1}/content_types/{2}/editor_interface".format( space_id, '/environments/{0}'.format(environment_id) if environment_id is not None else '', content_type_id )
Returns the JSON representation of the editor interface. def to_json(self): """ Returns the JSON representation of the editor interface. """ result = super(EditorInterface, self).to_json() result.update({'controls': self.controls}) return result
Returns the JSON Representation of the content type field validation. def to_json(self): """ Returns the JSON Representation of the content type field validation. """ result = {} for k, v in self._data.items(): result[camel_case(k)] = v return result