mirror of
https://github.com/getpelican/pelican.git
synced 2025-10-15 20:28:56 +02:00
PEP8-ify.
Wrap to 80 chars, sanitize imports.
This commit is contained in:
parent
df25dec30a
commit
6cde7fd27a
8 changed files with 142 additions and 110 deletions
|
|
@ -3,7 +3,6 @@ import os
|
|||
import datetime
|
||||
import math
|
||||
import random
|
||||
import urlparse
|
||||
|
||||
from collections import defaultdict
|
||||
from functools import partial
|
||||
|
|
@ -14,10 +13,9 @@ from jinja2 import Environment, FileSystemLoader, PrefixLoader, ChoiceLoader
|
|||
from jinja2.exceptions import TemplateNotFound
|
||||
|
||||
from pelican.contents import Article, Page, Category, is_valid_content
|
||||
from pelican.log import *
|
||||
from pelican.log import warning, error, debug, info
|
||||
from pelican.readers import read_file
|
||||
from pelican.utils import copy, process_translations, open
|
||||
from pelican.utils import slugify
|
||||
|
||||
|
||||
class Generator(object):
|
||||
|
|
@ -33,17 +31,23 @@ class Generator(object):
|
|||
|
||||
# templates cache
|
||||
self._templates = {}
|
||||
self._templates_path = os.path.expanduser(os.path.join(self.theme, 'templates'))
|
||||
simple_loader = FileSystemLoader(os.path.join(os.path.dirname(os.path.abspath(__file__)), "themes", "simple", "templates"))
|
||||
self._templates_path = os.path.expanduser(
|
||||
os.path.join(self.theme, 'templates'))
|
||||
|
||||
theme_path = os.path.join(os.path.dirname(os.path.abspath(__file__)))
|
||||
|
||||
simple_loader = FileSystemLoader(theme_path,
|
||||
"themes", "simple", "templates")
|
||||
self._env = Environment(
|
||||
loader=ChoiceLoader([
|
||||
FileSystemLoader(self._templates_path),
|
||||
simple_loader, # implicit inheritance
|
||||
PrefixLoader({'!simple' : simple_loader}) # explicit inheritance
|
||||
simple_loader, # implicit inheritance
|
||||
PrefixLoader({'!simple': simple_loader}) # explicit one
|
||||
]),
|
||||
extensions=self.settings.get('JINJA_EXTENSIONS', []),
|
||||
)
|
||||
debug('self._env.list_templates(): {0}'.format(self._env.list_templates()))
|
||||
|
||||
debug('template list: {0}'.format(self._env.list_templates()))
|
||||
|
||||
# get custom Jinja filters from user settings
|
||||
custom_filters = self.settings.get('JINJA_FILTERS', {})
|
||||
|
|
@ -58,8 +62,8 @@ class Generator(object):
|
|||
try:
|
||||
self._templates[name] = self._env.get_template(name + '.html')
|
||||
except TemplateNotFound:
|
||||
raise Exception('[templates] unable to load %s.html from %s' % (
|
||||
name, self._templates_path))
|
||||
raise Exception('[templates] unable to load %s.html from %s' \
|
||||
% (name, self._templates_path))
|
||||
return self._templates[name]
|
||||
|
||||
def get_files(self, path, exclude=[], extensions=None):
|
||||
|
|
@ -75,7 +79,7 @@ class Generator(object):
|
|||
|
||||
try:
|
||||
iter = os.walk(path, followlinks=True)
|
||||
except TypeError: # python 2.5 does not support followlinks
|
||||
except TypeError: # python 2.5 does not support followlinks
|
||||
iter = os.walk(path)
|
||||
|
||||
for root, dirs, temp_files in iter:
|
||||
|
|
@ -102,7 +106,7 @@ class ArticlesGenerator(Generator):
|
|||
|
||||
def __init__(self, *args, **kwargs):
|
||||
"""initialize properties"""
|
||||
self.articles = [] # only articles in default language
|
||||
self.articles = [] # only articles in default language
|
||||
self.translations = []
|
||||
self.dates = {}
|
||||
self.tags = defaultdict(list)
|
||||
|
|
@ -138,7 +142,8 @@ class ArticlesGenerator(Generator):
|
|||
|
||||
if 'TAG_FEED_RSS' in self.settings:
|
||||
writer.write_feed(arts, self.context,
|
||||
self.settings['TAG_FEED_RSS'] % tag, feed_type='rss')
|
||||
self.settings['TAG_FEED_RSS'] % tag,
|
||||
feed_type='rss')
|
||||
|
||||
translations_feeds = defaultdict(list)
|
||||
for article in chain(self.articles, self.translations):
|
||||
|
|
@ -149,14 +154,11 @@ class ArticlesGenerator(Generator):
|
|||
writer.write_feed(items, self.context,
|
||||
self.settings['TRANSLATION_FEED'] % lang)
|
||||
|
||||
|
||||
def generate_pages(self, writer):
|
||||
"""Generate the pages on the disk"""
|
||||
|
||||
write = partial(
|
||||
writer.write_file,
|
||||
relative_urls = self.settings.get('RELATIVE_URLS')
|
||||
)
|
||||
write = partial(writer.write_file,
|
||||
relative_urls=self.settings.get('RELATIVE_URLS'))
|
||||
|
||||
# to minimize the number of relative path stuff modification
|
||||
# in writer, articles pass first
|
||||
|
|
@ -171,8 +173,10 @@ class ArticlesGenerator(Generator):
|
|||
paginated = {}
|
||||
if template in PAGINATED_TEMPLATES:
|
||||
paginated = {'articles': self.articles, 'dates': self.dates}
|
||||
write('%s.html' % template, self.get_template(template), self.context,
|
||||
blog=True, paginated=paginated, page_name=template)
|
||||
|
||||
write('%s.html' % template, self.get_template(template),
|
||||
self.context, blog=True, paginated=paginated,
|
||||
page_name=template)
|
||||
|
||||
# and subfolders after that
|
||||
tag_template = self.get_template('tag')
|
||||
|
|
@ -201,15 +205,14 @@ class ArticlesGenerator(Generator):
|
|||
page_name=u'author/%s' % aut)
|
||||
|
||||
for article in self.drafts:
|
||||
write('drafts/%s.html' % article.slug, article_template, self.context,
|
||||
article=article, category=article.category)
|
||||
|
||||
write('drafts/%s.html' % article.slug, article_template,
|
||||
self.context, article=article, category=article.category)
|
||||
|
||||
def generate_context(self):
|
||||
"""change the context"""
|
||||
|
||||
# return the list of files to use
|
||||
files = self.get_files(self.path, exclude=['pages',])
|
||||
files = self.get_files(self.path, exclude=['pages', ])
|
||||
all_articles = []
|
||||
for f in files:
|
||||
try:
|
||||
|
|
@ -224,14 +227,16 @@ class ArticlesGenerator(Generator):
|
|||
if os.path.dirname(f) == self.path:
|
||||
category = self.settings['DEFAULT_CATEGORY']
|
||||
else:
|
||||
category = os.path.basename(os.path.dirname(f)).decode('utf-8')
|
||||
category = os.path.basename(os.path.dirname(f))\
|
||||
.decode('utf-8')
|
||||
|
||||
if category != '':
|
||||
metadata['category'] = Category(category, self.settings)
|
||||
|
||||
if 'date' not in metadata.keys()\
|
||||
and self.settings['FALLBACK_ON_FS_DATE']:
|
||||
metadata['date'] = datetime.datetime.fromtimestamp(os.stat(f).st_ctime)
|
||||
metadata['date'] = datetime.datetime.fromtimestamp(
|
||||
os.stat(f).st_ctime)
|
||||
|
||||
article = Article(content, metadata, settings=self.settings,
|
||||
filename=f)
|
||||
|
|
@ -265,7 +270,7 @@ class ArticlesGenerator(Generator):
|
|||
for tag in getattr(article, 'tags', []):
|
||||
tag_cloud[tag] += 1
|
||||
|
||||
tag_cloud = sorted(tag_cloud.items(), key = itemgetter(1), reverse = True)
|
||||
tag_cloud = sorted(tag_cloud.items(), key=itemgetter(1), reverse=True)
|
||||
tag_cloud = tag_cloud[:self.settings.get('TAG_CLOUD_MAX_ITEMS')]
|
||||
|
||||
tags = map(itemgetter(1), tag_cloud)
|
||||
|
|
@ -277,9 +282,8 @@ class ArticlesGenerator(Generator):
|
|||
self.tag_cloud = [
|
||||
(
|
||||
tag,
|
||||
int(
|
||||
math.floor(steps - (steps - 1) * math.log(count) / (math.log(max_count)or 1))
|
||||
)
|
||||
int(math.floor(steps - (steps - 1) * math.log(count)
|
||||
/ (math.log(max_count)or 1)))
|
||||
)
|
||||
for tag, count in tag_cloud
|
||||
]
|
||||
|
|
@ -290,14 +294,13 @@ class ArticlesGenerator(Generator):
|
|||
|
||||
# order the categories per name
|
||||
self.categories = list(self.categories.items())
|
||||
self.categories.sort(reverse=self.settings.get('REVERSE_CATEGORY_ORDER'))
|
||||
self.categories.sort(reverse=self.settings['REVERSE_CATEGORY_ORDER'])
|
||||
|
||||
self.authors = list(self.authors.items())
|
||||
self.authors.sort()
|
||||
|
||||
self._update_context(('articles', 'dates', 'tags', 'categories', 'tag_cloud', 'authors'))
|
||||
|
||||
|
||||
self._update_context(('articles', 'dates', 'tags', 'categories',
|
||||
'tag_cloud', 'authors'))
|
||||
|
||||
def generate_output(self, writer):
|
||||
self.generate_feeds(writer)
|
||||
|
|
@ -334,7 +337,7 @@ class PagesGenerator(Generator):
|
|||
for page in chain(self.translations, self.pages):
|
||||
writer.write_file(page.save_as, self.get_template('page'),
|
||||
self.context, page=page,
|
||||
relative_urls = self.settings.get('RELATIVE_URLS'))
|
||||
relative_urls=self.settings.get('RELATIVE_URLS'))
|
||||
|
||||
|
||||
class StaticGenerator(Generator):
|
||||
|
|
@ -345,8 +348,8 @@ class StaticGenerator(Generator):
|
|||
final_path=None):
|
||||
"""Copy all the paths from source to destination"""
|
||||
for path in paths:
|
||||
copy(path, source, os.path.join(output_path, destination), final_path,
|
||||
overwrite=True)
|
||||
copy(path, source, os.path.join(output_path, destination),
|
||||
final_path, overwrite=True)
|
||||
|
||||
def generate_output(self, writer):
|
||||
self._copy_paths(self.settings['STATIC_PATHS'], self.path,
|
||||
|
|
@ -356,7 +359,8 @@ class StaticGenerator(Generator):
|
|||
|
||||
# copy all the files needed
|
||||
for source, destination in self.settings['FILES_TO_COPY']:
|
||||
copy(source, self.path, self.output_path, destination, overwrite=True)
|
||||
copy(source, self.path, self.output_path, destination,
|
||||
overwrite=True)
|
||||
|
||||
|
||||
class PdfGenerator(Generator):
|
||||
|
|
@ -365,7 +369,8 @@ class PdfGenerator(Generator):
|
|||
def __init__(self, *args, **kwargs):
|
||||
try:
|
||||
from rst2pdf.createpdf import RstToPdf
|
||||
self.pdfcreator = RstToPdf(breakside=0, stylesheets=['twelvepoint'])
|
||||
self.pdfcreator = RstToPdf(breakside=0,
|
||||
stylesheets=['twelvepoint'])
|
||||
except ImportError:
|
||||
raise Exception("unable to find rst2pdf")
|
||||
super(PdfGenerator, self).__init__(*args, **kwargs)
|
||||
|
|
@ -373,7 +378,7 @@ class PdfGenerator(Generator):
|
|||
def _create_pdf(self, obj, output_path):
|
||||
if obj.filename.endswith(".rst"):
|
||||
filename = obj.slug + ".pdf"
|
||||
output_pdf=os.path.join(output_path, filename)
|
||||
output_pdf = os.path.join(output_path, filename)
|
||||
# print "Generating pdf for", obj.filename, " in ", output_pdf
|
||||
with open(obj.filename) as f:
|
||||
self.pdfcreator.createPdf(text=f, output=output_pdf)
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue