def create(self): """ Create a new translation supplied as a string. Returns: A dict with information for the request. Raises: BadRequestError: There was a problem with the request. NoContentError: There was no content string in the request. """ if 'content' not in self.data: raise NoContentError("No content found.") parser = registry.appropriate_handler(self.resource, language=self.language) if parser is None: raise BadRequestError("I18n type is not supported: %s" % i18n_type) file_ = tempfile.NamedTemporaryFile( mode='wb', suffix=registry.extensions_for(self.resource.i18n_method)[0], delete=False, ) try: file_.write(self.data['content'].encode('UTF-8')) file_.close() try: parser.bind_file(file_.name) parser.is_content_valid() except (FileCheckError, ParseError), e: raise BadRequestError(unicode(e)) except Exception, e: logger.error(unicode(e), exc_info=True) raise BadRequestError("A strange error has happened.")
def create(self): """ Create a new translation supplied as a string. Returns: A dict with information for the request. Raises: BadRequestError: There was a problem with the request. NoContentError: There was no content string in the request. """ if 'content' not in self.data: raise NoContentError("No content found.") parser = registry.appropriate_handler( self.resource, language=self.language ) if parser is None: raise BadRequestError("I18n type is not supported: %s" % i18n_type) file_ = tempfile.NamedTemporaryFile( mode='wb', suffix=registry.extensions_for(self.resource.i18n_method)[0], delete=False, ) try: file_.write(self.data['content'].encode('UTF-8')) file_.close() try: parser.bind_file(file_.name) parser.is_content_valid() except (FileCheckError, ParseError), e: raise BadRequestError(unicode(e)) except Exception, e: logger.error(unicode(e), exc_info=True) raise BadRequestError("A strange error has happened.")
def compile_translation(self, pseudo_type=None, mode=None): """Compile the translation for a resource in a specified language. There is some extra care for PO/POT resources. If there is no language specified, return a POT file, otherwise a PO. The argument ``mode`` allows for different handling of a translation, depending on whether it is for *viewing* or *translating it. This is necessary for formats that do not fallback to the source language in case of empty translations. Args: pseudo_type: The pseudo_type (if any). mode: The mode for compiling this translation. Returns: The compiled template. """ if mode is None: mode = Mode.DEFAULT handler = registry.appropriate_handler(resource=self.resource, language=self.language) handler.bind_resource(self.resource) handler.set_language(self.language) content = handler.compile(pseudo=pseudo_type, mode=mode) return content if isinstance(content, basestring) else ''
def update_source_file(self, fake=False): """ Fetch source file from remote url and import it, updating existing entries. """ try: source_file = urllib2.urlopen(self.source_file_url) except: logger.error("Could not pull source file for resource %s (%s)" % (self.resource.full_name, self.source_file_url)) raise filename = '' if source_file.info().has_key('Content-Disposition'): # If the response has Content-Disposition, we try to take # filename from it content = source_file.info()['Content-Disposition'] if 'filename' in content: filename = content.split('filename')[1] filename = filename.replace('"', '').replace("'", "").replace( "=", "").replace('/', '-').strip() if filename == '': parts = urlparse.urlsplit(self.source_file_url) #FIXME: This still might end empty filename = parts.path.split('/')[-1] try: if not self.resource.i18n_method: msg = "No i18n method defined for resource %s" logger.error(msg % self.resource) return parser = registry.appropriate_handler( self.resource, language=self.resource.source_language, filename=filename) language = self.resource.source_language content = source_file.read() parser.bind_content(content) parser.set_language(language) parser.bind_resource(self.resource) parser.is_content_valid() parser.parse_file(is_source=True) strings_added, strings_updated = 0, 0 if not fake: strings_added, strings_updated = parser.save2db(is_source=True) except Exception, e: logger.error( "Error importing source file for resource %s.%s (%s): %s" % (self.resource.project.slug, self.resource.slug, self.source_file_url, str(e))) raise
def update_source_file(self, fake=False): """ Fetch source file from remote url and import it, updating existing entries. """ try: source_file = urllib2.urlopen(self.source_file_url) except: logger.error("Could not pull source file for resource %s (%s)" % (self.resource.full_name, self.source_file_url)) raise filename = '' if source_file.info().has_key('Content-Disposition'): # If the response has Content-Disposition, we try to take # filename from it content = source_file.info()['Content-Disposition'] if 'filename' in content: filename = content.split('filename')[1] filename = filename.replace('"', '').replace("'", "" ).replace("=", "").replace('/', '-').strip() if filename == '': parts = urlparse.urlsplit(self.source_file_url) #FIXME: This still might end empty filename = parts.path.split('/')[-1] try: if not self.resource.i18n_method: msg = "No i18n method defined for resource %s" logger.error(msg % self.resource) return parser = registry.appropriate_handler( self.resource, language=self.resource.source_language, filename=filename ) language = self.resource.source_language content = source_file.read() parser.bind_content(content) parser.set_language(language) parser.bind_resource(self.resource) parser.is_content_valid() parser.parse_file(is_source=True) strings_added, strings_updated = 0, 0 if not fake: strings_added, strings_updated = parser.save2db(is_source=True) except Exception,e: logger.error("Error importing source file for resource %s.%s (%s): %s" % ( self.resource.project.slug, self.resource.slug, self.source_file_url, str(e))) raise
def compile_translation(self, pseudo_type=None): """Compile the translation for a resource in a specified language. There is some extra care for PO/POT resources. If there is no language specified, return a POT file, otherwise a PO. """ handler = registry.appropriate_handler( resource=self.resource, language=self.language ) handler.bind_resource(self.resource) handler.set_language(self.language) if pseudo_type: handler.bind_pseudo_type(pseudo_type) handler.compile() return handler.compiled_template or ''
def create(self): """ Creates a new translation from file. Returns: A dict with information for the translation. Raises: BadRequestError: There was a problem with the request. NoContentError: There was no file in the request. """ if not self.request.FILES: raise NoContentError("No file has been uploaded.") submitted_file = self.request.FILES.values()[0] name = str(submitted_file.name) size = submitted_file.size try: file_ = tempfile.NamedTemporaryFile( mode='wb', suffix=name[name.rfind('.'):], delete=False ) for chunk in submitted_file.chunks(): file_.write(chunk) file_.close() parser = registry.appropriate_handler( self.resource, language=self.language, filename=name ) parser.bind_file(file_.name) if parser is None: raise BadRequestError("Unknown file type") if size == 0: raise BadRequestError("Empty file") try: parser.is_content_valid() logger.debug("Uploaded file %s" % file_.name) except (FileCheckError, ParseError), e: raise BadRequestError("Error uploading file: %s" % e) except Exception, e: logger.error(unicode(e), exc_info=True) raise BadRequestError("A strange error happened.")
def create(self): """ Creates a new translation from file. Returns: A dict with information for the translation. Raises: BadRequestError: There was a problem with the request. NoContentError: There was no file in the request. """ if not self.request.FILES: raise NoContentError("No file has been uploaded.") submitted_file = self.request.FILES.values()[0] name = str(submitted_file.name) size = submitted_file.size try: file_ = tempfile.NamedTemporaryFile(mode='wb', suffix=name[name.rfind('.'):], delete=False) for chunk in submitted_file.chunks(): file_.write(chunk) file_.close() parser = registry.appropriate_handler(self.resource, language=self.language, filename=name) parser.bind_file(file_.name) if parser is None: raise BadRequestError("Unknown file type") if size == 0: raise BadRequestError("Empty file") try: parser.is_content_valid() logger.debug("Uploaded file %s" % file_.name) except (FileCheckError, ParseError), e: raise BadRequestError("Error uploading file: %s" % e) except Exception, e: logger.error(unicode(e), exc_info=True) raise BadRequestError("A strange error happened.")
def compile_translation(self, pseudo_type=None, mode=None): """Compile the translation for a resource in a specified language. There is some extra care for PO/POT resources. If there is no language specified, return a POT file, otherwise a PO. The argument ``mode`` allows for different handling of a translation, depending on whether it is for *viewing* or *translating it. This is necessary for formats that do not fallback to the source language in case of empty translations. Args: pseudo_type: The pseudo_type (if any). mode: The mode for compiling this translation. Returns: The compiled template. """ if mode is None: mode = Mode.DEFAULT handler = registry.appropriate_handler(resource=self.resource, language=self.language) handler.bind_resource(self.resource) handler.set_language(self.language) content = handler.compile(pseudo=pseudo_type, mode=mode) return content if isinstance(content, basestring) else ""
def _get_handler(self, resource, language, filename=None): """Get the appropriate hanlder for the resource.""" return registry.appropriate_handler(resource, language, filename=filename)
def _get_handler(self, resource, language, filename=None): """Get the appropriate hanlder for the resource.""" return registry.appropriate_handler( resource, language, filename=filename )