def disable_version(version, request, new_current=None): """Disable a version of the object, then saves it. Args: version: new_current: request: Returns: """ version_manager = get_from_version(version, request=request) # try to delete the current version if version_manager.current == str(version.id): # no version to be current provided if new_current is None: raise exceptions.ApiError("Unable to disable the current version.") # id doesn't match a version if new_current.id not in version_manager.versions: raise exceptions.ApiError( "The id provided to be the next current version, could not be found.", ) # set the new current version version_manager.set_current_version(new_current) # disable the version version_manager.disable_version(version) return upsert(version_manager, request=request)
def init_schema_info(oai_harvester_metadata_format, request=None): """Init schema information for an OaiHarvesterMetadataFormat. Args: oai_harvester_metadata_format: The OaiHarvesterMetadataFormat to init. request: Returns: Init OaiHarvesterMetadataFormat. """ # TODO: refactor send request with cookies (same code in other apps) try: session_id = request.session.session_key except: session_id = None http_response = send_get_request( oai_harvester_metadata_format.schema, cookies={"sessionid": session_id} ) if http_response.status_code == status.HTTP_200_OK: string_xml = http_response.text oai_harvester_metadata_format.xml_schema = string_xml try: oai_harvester_metadata_format.hash = get_hash(string_xml) except exceptions.XSDError: raise exceptions.ApiError( "Impossible to hash the schema for the following " "metadata format: {0}." ) list_template = api_template.get_all_accessible_by_hash( oai_harvester_metadata_format.hash, request=request ) # FIXME: What to do if several templates with the same hash. if len(list_template) == 1: oai_harvester_metadata_format.template = list_template[0] elif len(list_template) > 1: raise exceptions.ApiError( "Several templates have the same hash. " "Impossible to determine a template for the following " "metadata format: {0}.".format( oai_harvester_metadata_format.metadata_prefix ) ) else: raise exceptions.ApiError( "Impossible to init schema information for the following " "metadata format: {0}.".format( oai_harvester_metadata_format.metadata_prefix ) ) return oai_harvester_metadata_format
def upsert(contact_message): """Insert or update a given message Args: contact_message: Returns: """ try: # Check if new contact message if contact_message.id is None: if SEND_EMAIL_WHEN_CONTACT_MESSAGE_IS_RECEIVED: context = {"URI": SERVER_URI} template_path = ( "core_website_app/admin/email/contact_message_for_admin.html" ) send_mail_api.send_mail_to_administrators( subject="New Contact Message", path_to_template=template_path, context=context, ) # save method return self return contact_message.save() except Exception as e: logger.error(str(e)) raise exceptions.ApiError("Save message failed")
def upsert(oai_request_page_object): """Insert or update a given OAIRequestPage object Args: oai_request_page_object: Returns: """ def _generate_token(token_length=16): """Generate a random token of a given length. Args: token_length: Raises: ApiError: Returns: """ return "".join( random.choice(string.ascii_lowercase + string.digits) for _ in range(token_length)) # Loop until OAIRequestPage object is inserted or raise exception if the # maximum retry is reached. for _ in range(constants.MAX_INSERT_RETRIES): try: oai_request_page_object.resumption_token = _generate_token() return oai_request_page_object.save() except Exception as e: logger.warning("Error while saving OAIRequestPage object: %s" % str(e)) raise exceptions.ApiError( "Exceeded number of tries to save OAIRequestPage")
def admin_insert(data, request): """Save the data. Args: data: request: Returns: """ if data.xml_content is None: raise exceptions.ApiError( "Unable to save data: xml_content field is not set.") # initialize times - use values if provided, set now otherwise now = datetime_now() if not data.creation_date: data.creation_date = now if not data.last_modification_date: data.last_modification_date = now if not data.last_change_date: data.last_change_date = now # convert and save the data (do not call convert_and_save that will set the date fields) check_xml_file_is_valid(data, request=request) data.convert_to_file() data.convert_to_dict() return data.save()
def upsert(xsl_transformation): """ Upsert an xsl_transformation. Args: xsl_transformation: XslTransformation. Returns: XslTransformation instance. """ if not is_well_formed_xml(xsl_transformation.content): raise exceptions.ApiError("Uploaded file is not well formatted XSLT.") elif not has_xsl_namespace(xsl_transformation.content): raise exceptions.ApiError( "XSLT namespace not found in the uploaded file.") else: return xsl_transformation.save_object()
def get_by_name(xslt_name): """ Get an XSLT document. Returns: """ try: return XslTransformation.get_by_name(xslt_name) except: raise exceptions.ApiError( "No transformation can be found with the given name")
def set_workspace_private(workspace, user): """Set the workspace to private. Args: workspace user Return: """ if is_workspace_global(workspace): raise exceptions.ApiError( "You can't change the state of the global workspace.") if settings.CAN_SET_PUBLIC_DATA_TO_PRIVATE: workspace.is_public = False workspace.save() else: raise exceptions.ApiError( "You can't change the state of the workspace because of the settings of the website." )
def init_schema_info(oai_harvester_metadata_format): """ Init schema information for an OaiHarvesterMetadataFormat. Args: oai_harvester_metadata_format: The OaiHarvesterMetadataFormat to init. Returns: Init OaiHarvesterMetadataFormat. """ http_response = send_get_request(oai_harvester_metadata_format.schema) if http_response.status_code == status.HTTP_200_OK: string_xml = http_response.text oai_harvester_metadata_format.xml_schema = string_xml try: oai_harvester_metadata_format.hash = get_hash(string_xml) except exceptions.XSDError: raise exceptions.ApiError( "Impossible to hash the schema for the following " "metadata format: {0}.") list_template = api_template.get_all_by_hash( oai_harvester_metadata_format.hash) # FIXME: What to do if several templates with the same hash. if len(list_template) == 1: oai_harvester_metadata_format.template = list_template[0] elif len(list_template) > 1: raise exceptions.ApiError( "Several templates have the same hash. " "Impossible to determine a template for the following " "metadata format: {0}.".format( oai_harvester_metadata_format.metadata_prefix)) else: raise exceptions.ApiError( "Impossible to init schema information for the following " "metadata format: {0}.".format( oai_harvester_metadata_format.metadata_prefix)) return oai_harvester_metadata_format
def delete(contact_message): """Delete a message Args: contact_message: Returns: """ try: contact_message.delete() except Exception as e: logger.error(str(e)) raise exceptions.ApiError("Impossible to delete contact message.")
def set_current(version): """Set the current version of the object, then saves it. Args: version: Returns: """ if custom_resource_api.get_all_by_template(version).count() == 0: raise exceptions.ApiError( "Please set custom resources to template before setting it to current." ) version_manager_api.set_current(version)
def get_from_version(version): """Return a version manager from a version. Args: version: Returns: """ version_managers = VersionManager.get_all() for version_manager in version_managers: if str(version.id) in version_manager.versions: return version_manager raise exceptions.ApiError( "No version manager could be found for this version.")
def get(message_id): """Get a message Args: message_id: Returns: """ try: return ContactMessage.get_by_id(message_id) except Exception as e: logger.error(str(e)) raise exceptions.ApiError( "No message could be found with the given id.")
def upsert(data, request): """Save or update the data. Args: data: request: Returns: """ if data.xml_content is None: raise exceptions.ApiError( "Unable to save data: xml_content field is not set.") check_xml_file_is_valid(data, request=request) return data.convert_and_save()
def set_workspace_public(workspace, user): """Set the workspace to public. Args: workspace user Return: """ if settings.CAN_SET_WORKSPACE_PUBLIC: workspace.is_public = True workspace.save() else: raise exceptions.ApiError( "You can't change the state of the workspace because of the settings of the website." )
def upsert(data, request): """Save or update the data. Args: data: request: Returns: """ if data.dict_content is None: raise exceptions.ApiError( "Unable to save data: dict_content field is not set.") data.last_modification_date = datetime.datetime.now(pytz.utc) validate_json_data(data.dict_content, data.template.content) return _save(data)
def xsl_transform(xml_content, xslt_name): """ Transform an XML file using an XSL transformation. Args: xml_content (str): XML document content, encoded in UTF-8 xslt_name (str): Name of an XslTransformation document Returns: str: Transformed XML string """ xslt_object = get_by_name(xslt_name) try: return xml.xsl_transform(xml_content, xslt_object.content) except Exception: raise exceptions.ApiError( "An unexpected exception happened while transforming the XML")
def upsert(data, user): """ Save or update the data. Args: data: user: Returns: """ if data.xml_content is None: raise exceptions.ApiError( "Unable to save data: xml_content field is not set.") data.last_modification_date = datetime.datetime.now() check_xml_file_is_valid(data) return data.convert_and_save()
def upsert_data(data): """Upsert data Args: data: Returns: """ from core_main_app.components.data.api import check_xml_file_is_valid if data.xml_content is None: raise exceptions.ApiError( "Unable to save data: xml_content field is not set.") check_xml_file_is_valid(data) return data.convert_and_save()
def insert(blob): """ Insert the blob in the blob repository. Args: blob: Returns: """ # if blob is not set if blob.blob is None: raise exceptions.ApiError( "Unable to save the blob: blob field is not set.") # save blob on blob host blob.save_blob() # save blob in database return blob.save()
def upsert(web_page): """Upsert the page content Args: web_page (obj): web page object Returns: content of the web page """ if web_page.type not in list(WEB_PAGE_TYPES.values()): raise exceptions.ApiError("Web page type does not exist") # strip in case of whitespaces only if web_page.content.strip(): # we save the object only if the content is not empty return web_page.save() else: # otherwise it means deletion return delete_by_type(web_page.type)
def set_current(version): """Set the current version of the object, then saves it. Args: version: Returns: """ version_manager = get_from_version(version) # a disabled version cannot be current if str(version.id) in version_manager.get_disabled_versions(): raise exceptions.ApiError( "Unable to set the current version because it is disabled.") version_manager.set_current_version(version) return upsert(version_manager)
def generate_data_items_from_data(data): """ Generate all data items structure. Args: data: Returns: """ try: # In case we are editing a data, need to delete old items relative to it data_item_api.delete_from_data_if_exists(data) # build data_structure root_element = _generate_form(data.template.content, data.xml_content) # build XML renderer and get xml xml_data = XmlTypeRenderer(root_element).render() # build tree and get the root root = XSDTree.build_tree(xml_data).getroot() # generate item from the root generated_items = generate_items(root, root.tag) list_to_insert = [] for generated_item in generated_items: item = Item(path=generated_item['path'], value=generated_item['value']) list_to_insert.append(item) # Upsert DataItem data_item = DataItem(data=data, template=data.template, list_content=list_to_insert, last_modification_date=data.last_modification_date) data_item_api.upsert(data_item) # delete data_structure delete_branch_from_db(root_element.id) except Exception, e: raise exceptions.ApiError('An error occurred during the generation: {0}.'.format(e.message))