def parse(self): self.save_html() self.header = self.header.replace('---', '') post_info = yaml.load(self.header) for item in post_info: ''' If item is date, convert it to datetime object, then save it to post.pub_time. If item is categories, to save it to post.categories as a list. If item is tags, save it to post.tags as a list, too. Sorry for making this such complex. ''' if item == 'date': try: pub_time = datetime.strptime( post_info['date'], "%Y-%m-%d %H:%M") except Exception, e: logger.error("Time data for post '{0}' does not match format '%Y-%m-%d %H:%M'".format(self.filename) + "Use current time instead.") pub_time = datetime.now() setattr(self, 'pub_time', pub_time) elif item == 'categories' or item == 'tags': if isinstance(post_info[item], str) or isinstance(post_info[item], unicode): setattr(self, item, post_info[item].split(',')) elif isinstance(post_info[item], list): setattr(self, item, post_info[item]) else: setattr(self, item, [])
def render(self, file_path, parameter): template = self._template_loader.get_template(file_path) try: return template.render(**parameter) except: logger.error("Template Error: {0}".format(file_path)) return exceptions.html_error_template().render()
def load_config_file(): try: _config_yml = open(settings.CONFIG_PATH, 'r').read() except Exception: logger.error('No "_config.yml" file found for the current directory.') sys.exit() config_dict = yaml.load(_config_yml) for item in config_dict: setattr(settings, item, config_dict[item])
def load_single_file(self, file_path): if os.path.basename(file_path).startswith('.'): return item = self._Model.from_file(file_path, self.config) if item: self.data_mapping[self._name][file_path] = item self._table[file_path] = item.to_db(os.path.join(self.config.base_dir, file_path)) else: logger.error(message="Incorrect file format: {0}".format(file_path))
def from_text(cls, path, config, text): header = re.compile(r'---[\s\S]*?---').findall(text) if header: try: attributes = yaml.load(header[0].replace('---', '')) except yaml.YAMLError, e: logger.error("Wrong format inside the header area: {0}".format(path)) return None attributes['content'] = text.replace(header[0], '', 1) return cls(path, config, **attributes)
def load_modules(self): renderer_path = os.path.join(self.config.base_dir, 'modules', 'renderer.py') if os.path.exists(renderer_path): try: self.Renderer = imp.load_source('renderer', renderer_path).Renderer except IOError: logger.error("Can not import {0}".format(renderer_path)) from crotal import renderer self.Renderer = renderer.Renderer else: from crotal import renderer self.Renderer = renderer.Renderer
def get_template(self, uri): """ Override `get_template` so that it returns a `error template` when lookup failed to locate the template. """ if uri in self._collection: return self._collection[uri] else: error_message = "template not found: {0}, calling by: {1}".format(uri, self.calling_uri) logger.error(error_message) error_template = Template(text=error_message) self.put_template(uri, Template(text=error_message)) return error_template
def create_post(post_title='sample post'): config = Command.load_config() now = datetime.now() date = unicode(now.strftime('%Y-%m-%d %H:%M')) pinyin = PinYin() pinyin.load_word() slug = pinyin.hanzi2pinyin_split(string=post_title, split='-') new_post = POST_SAMPLE.format(post_title.decode('utf8'), date, slug) file_title = "{0}-{1}.markdown".format(unicode(now.strftime('%Y-%m-%d')), post_title.decode('utf8')) absolute_file_path = os.path.join(config.base_dir, (os.path.join(config.posts_dir, file_title))) if not os.path.exists(absolute_file_path): open(os.path.join(config.base_dir, absolute_file_path.encode('utf8')), 'w+').write(new_post.encode('utf8')) else: logger.error("File exists: {0}".format(absolute_file_path))
def create_page(): if not os.path.exists(settings.CONFIG_PATH): logger.error('No "_config.yml" file found for the current directory.') sys.exit() title = logger.info_input('Page Title') url = logger.info_input('Page URL (.e.g, /foo/bar/):') description = logger.info_input('Page Description:') pinyin = PinYin() slug = pinyin.hanzi2pinyin_split(string=title, split="-") now = datetime.now() pub_date = now.strftime("%Y-%m-%d %H:%M") page = PAGE_SAMPLE.format(title, pub_date, url, description) file_path = os.path.join(settings.PAGES_DIR, slug + '.markdown') open(os.path.join(settings.BASE_DIR, file_path), 'w+').write(page) logger.success('You can browse the page by {0} After generating the site.'.format(url))
def create_page(): if not os.path.exists(settings.CONFIG_PATH): logger.error( 'No "_config.yml" file found for the current directory.') sys.exit() title = logger.info_input('Page Title') url = logger.info_input('Page URL (.e.g, /foo/bar/):') description = logger.info_input('Page Description:') pinyin = PinYin() slug = pinyin.hanzi2pinyin_split(string=title, split="-") now = datetime.now() pub_date = now.strftime("%Y-%m-%d %H:%M") page = PAGE_SAMPLE.format(title, pub_date, url, description) file_path = os.path.join(settings.PAGES_DIR, slug + '.markdown') open(os.path.join(settings.BASE_DIR, file_path), 'w+').write(page) logger.success( 'You can browse the page by {0} After generating the site.'.format( url))
def create_post(): if not os.path.exists(settings.CONFIG_PATH): logger.error('No "_config.yml" file found for the current directory.') sys.exit() if len(sys.argv) != 3: logger.error('Please specify the post title.') else: title = sys.argv[2] now = datetime.now() pub_time = now.strftime('%Y-%m-%d %H:%M') pinyin = PinYin() pinyin.load_word() slug = pinyin.hanzi2pinyin_split(string=title, split='-') new_post = POST_SAMPLE.format(title, pub_time, slug) file_title = now.strftime("%Y-%m-%d") + '-' + slug + '.markdown' file_path = os.path.join(settings.POSTS_DIR, file_title) open(os.path.join(settings.BASE_DIR, file_path), 'w+').write(new_post) logger.success(' '.join([file_path, 'created.']))
def __init__(self, path, output=None): if path is None or (not self.check_config(path)): logger.error("Config file '_config.yml' can not be loaded in the current directory and its parents.") sys.exit() self.base_dir = os.path.join(path) self.working_dir = os.getcwd() self.config_path = os.path.join(self.base_dir, '_config.yml') self.posts_dir = os.path.join('source', 'posts') self.pages_dir = os.path.join('source', 'pages') self.static_dir = os.path.join('static') self.db_path = os.path.join(self.base_dir, 'db.json') if output: self.publish_dir = os.path.join(self.base_dir, output) else: self.publish_dir = os.path.join(self.base_dir, 'preview') self.deploy_dir = os.path.join(self.base_dir, 'deploy') self.read_from_file()
def create_post(): if not os.path.exists(settings.CONFIG_PATH): logger.error( 'No "_config.yml" file found for the current directory.') sys.exit() if len(sys.argv) != 3: logger.error('Please specify the post title.') else: title = sys.argv[2] now = datetime.now() pub_time = now.strftime('%Y-%m-%d %H:%M') pinyin = PinYin() pinyin.load_word() slug = pinyin.hanzi2pinyin_split(string=title, split='-') new_post = POST_SAMPLE.format(title, pub_time, slug) file_title = now.strftime("%Y-%m-%d") + '-' + slug + '.markdown' file_path = os.path.join(settings.POSTS_DIR, file_title) open(os.path.join(settings.BASE_DIR, file_path), 'w+').write(new_post) logger.success(' '.join([file_path, 'created.']))
def start(port, path): if not path: logger.error("Not in a crotal site.") sys.exit() site = Site(path) site.generate() config = Config(path) serverThread = ServerThread(config, port) serverThread.daemon = True serverThread.start() observer = Observer() for model in site.models: for path in model.PATH: observer.schedule(ChangeHandler(config, site, ignore_patterns=["*/.DS_Store"]), path=os.path.join(config.base_dir, path), recursive=True) observer.start() while True: try: time.sleep(1) except KeyboardInterrupt: logger.info('Server shutting down.') sys.exit()
text = file(absolute_path, 'r').read().decode('utf8') return cls.from_text(path, config, text) @classmethod def from_text(cls, path, config, text): header = re.compile(r'---[\s\S]*?---').findall(text) if header: try: attributes = yaml.load(header[0].replace('---', '')) except yaml.YAMLError, e: logger.error("Wrong format inside the header area: {0}".format(path)) return None attributes['content'] = text.replace(header[0], '', 1) return cls(path, config, **attributes) else: logger.error("Can not find header area: {0}".format(path)) return None @classmethod def from_db(cls, path, config, row): serial = row['content'].decode('base64') return cPickle.loads(str(serial)) def to_db(self, absolute_path): return { 'content': self.serialize().encode('base64'), 'last_mod_time': os.path.getmtime(absolute_path), } def serialize(self): return cPickle.dumps(self)