rem
stringlengths
0
322k
add
stringlengths
0
2.05M
context
stringlengths
8
228k
finish_t = config.get("category_start", DEFAULT_FINISH)
finish_t = config.get("category_finish", DEFAULT_FINISH)
def genCategories(self): config = self._request.getConfiguration() root = config["datadir"]
path_info = []
path_info = data['path_info']
def defaultFileListHandler(self, request): """ This is the default handler for getting entries. It takes the request object in and figures out which entries based on the default behavior that we want to show and generates a list of EntryBase subclass objects which it returns.
filelist = (data['bl_type'] == 'dir' and tools.Walk(data['root_datadir'], int(config['depth'])) or [data['root_datadir']])
if data['bl_type'] == 'dir': filelist = tools.Walk(data['root_datadir'], int(config['depth'])) else: filelist = [data['root_datadir']]
def defaultFileListHandler(self, request): """ This is the default handler for getting entries. It takes the request object in and figures out which entries based on the default behavior that we want to show and generates a list of EntryBase subclass objects which it returns.
if not data['pi_yr'] == '':
if data['pi_yr']:
def defaultFileListHandler(self, request): """ This is the default handler for getting entries. It takes the request object in and figures out which entries based on the default behavior that we want to show and generates a list of EntryBase subclass objects which it returns.
match = re.search(r'\.(\w+)$',data['pi_bl']) probableFile = config['datadir'] + re.sub(r'\.\w+$','',data['pi_bl']) + '.txt' if match and os.path.isfile(probableFile): data['flavour'] = match.groups()[0]
filename, ext = os.path.splitext(data['pi_bl']) probableFile = config['datadir'] + filename + '.txt' if ext and os.path.isfile(probableFile): data['flavour'] = ext[1:]
def run(self): """ Main loop for pyblosxom. """ config = self._request.getConfiguration() data = self._request.getData() pyhttp = self._request.getHttp()
config['blog_title'] += ' : %s' % re.sub(r'/[^/]+\.\w+$','',data['pi_bl'])
config['blog_title'] += ' : %s' % filename
def run(self): """ Main loop for pyblosxom. """ config = self._request.getConfiguration() data = self._request.getData() pyhttp = self._request.getHttp()
recurse = ( recurse > 1 and recurse - 1 or 0) result = result + Walk(fullname, (recurse > 1 and recurse - 1 or 0), pattern, return_folders)
result = result + Walk(fullname, (recurse > 1 and recurse - 1 or 0), pattern, return_folders)
def Walk(root = '.', recurse = 0, pattern = re.compile(r'.*\.txt$'), return_folders = 0 ): """ This function walks a directory tree starting at a specified root folder, and returns a list of all of the files (and optionally folders) that match our pattern(s). Taken from the online Python Cookbook and modified to own ne...
def __init__(self, config, environ, data={}):
def __init__(self, config, environ, data=None):
def __init__(self, config, environ, data={}): """ Sets configuration and environment. Creates the L{Request} object.
self._data = data
if data == None: self._data = dict() else: self._data = data
def __init__(self, config, environ, data): """ Sets configuration and environment. Creates the L{Response} object which handles all output related functionality. @param config: A dict containing the configuration variables. @type config: dict
if isinstance(entry_list, list):
if isinstance(entry_list, list) and len(entry_list) > 0:
def blosxom_handler(request): """ This is the default blosxom handler. """ config = request.getConfiguration() data = request.getData() # go through the renderer callback to see if anyone else # wants to render. this renderer gets stored in the data dict # for downstream processing. r = tools.run_callback('renderer'...
mtime_tuple = time.localtime(mtime) mtime_gmtuple = time.gmtime(mtime) data["date"] = time.strftime('%a, %d %b %Y', mtime_tuple) data["w3cdate"] = time.strftime('%Y-%m-%dT%H:%M:%SZ', mtime_gmtuple) data['rfc822date'] = time.strftime('%a, %d %b %Y %H:%M GMT', mtime_gmtuple)
else: mtime = time.time() mtime_tuple = time.localtime(mtime) mtime_gmtuple = time.gmtime(mtime) data["date"] = time.strftime('%a, %d %b %Y', mtime_tuple) data["w3cdate"] = time.strftime('%Y-%m-%dT%H:%M:%SZ', mtime_gmtuple) data['rfc822date'] = time.strftime('%a, %d %b %Y %H:%M GMT', mtime_gmtuple)
def blosxom_handler(request): """ This is the default blosxom handler. """ config = request.getConfiguration() data = request.getData() # go through the renderer callback to see if anyone else # wants to render. this renderer gets stored in the data dict # for downstream processing. r = tools.run_callback('renderer'...
self._in.write(input.read())
length = int(pyhttp["CONTENT_LENGTH"]) self._in.write(input.read(length))
def buffer_input_stream(self): """ Buffer the input stream in a StringIO instance. This is done to have a known/consistent way of accessing incomming data. For example the input stream passed by mod_python does not offer the same functionallity as sys.stdin. """ # TODO: tests on memory consumption when uploading huge f...
title = lines.pop(0)
title = lines.pop(0).strip()
def blosxom_entry_parser(filename, request): """ Open up a *.txt file and read its contents. The first line becomes the title of the entry. The other lines are the body of the entry. @param filename: A filename to extract data and metadata from @type filename: string @param request: A standard request object @type ...
entryData[meta[0]] = meta[1]
entryData[meta[0].strip()] = meta[1].strip()
def blosxom_entry_parser(filename, request): """ Open up a *.txt file and read its contents. The first line becomes the title of the entry. The other lines are the body of the entry. @param filename: A filename to extract data and metadata from @type filename: string @param request: A standard request object @type ...
cache = cache_driver.BlosxomCache(config.py.get('cacheConfig', ''))
req = Request() cache = cache_driver.BlosxomCache(req, config.py.get('cacheConfig', ''))
def autoping(name): # Load up the cache (You can just import the base cache here) cache_driver = tools.importName('Pyblosxom.cache', config.py.get('cacheDriver', 'base')) cache = cache_driver.BlosxomCache(config.py.get('cacheConfig', '')) try: filename = os.path.join(config.py['datadir'], name) entryData = {} cache.loa...
req = Request() p = PyBlosxom(req) entryData = p.defaultEntryParser(filename,req)
entryData = default_entry_parser(filename,req)
def autoping(name): # Load up the cache (You can just import the base cache here) cache_driver = tools.importName('Pyblosxom.cache', config.py.get('cacheDriver', 'base')) cache = cache_driver.BlosxomCache(config.py.get('cacheConfig', '')) try: filename = os.path.join(config.py['datadir'], name) entryData = {} cache.loa...
today = self._entryList[0]["timetuple"]
if len(self._entryList) > 0: today = self._entryList[0]["timetuple"] else: self._cal = "" return
def generateCalendar(self): """ Generates the calendar. We'd like to walk the archives for things that happen in this month and mark the dates accordingly. And possibly turn this into a table with CSS markup and such. """ root = self._py["datadir"] baseurl = self._py.get("base_url", "") markup = self._py.get("calenda...
lookup = {"Jan": 1, "Feb": 2, "Mar": 3, "Apr": 4, "May": 5, "Jun": 6, "Jul": 7, "Aug": 8, "Sep": 9, "Oct": 10, "Nov": 11, "Dec": 12, "": today[1]}
def generateCalendar(self): """ Generates the calendar. We'd like to walk the archives for things that happen in this month and mark the dates accordingly. And possibly turn this into a table with CSS markup and such. """ root = self._py["datadir"] baseurl = self._py.get("base_url", "") markup = self._py.get("calenda...
today = tuple([today[0]] + [lookup[temp]] + list(today)[2:])
if temp.isdigit(): temp = int(temp) else: if tools.month2num.has_key(temp): temp = tools.month2num[temp] else: temp = today[1] today = tuple([today[0]] + [temp] + list(today)[2:])
def generateCalendar(self): """ Generates the calendar. We'd like to walk the archives for things that happen in this month and mark the dates accordingly. And possibly turn this into a table with CSS markup and such. """ root = self._py["datadir"] baseurl = self._py.get("base_url", "") markup = self._py.get("calenda...
if entry['date'] != current_date:
if entry["date"] and entry['date'] != current_date:
def _processEntry(self, entry, current_date): """ Main workhorse of pyblosxom stories, comments and other miscelany goes here
while dirname != datadir:
while len(dirname) >= len(datadir):
def _getFlavour(self, taste='html'): """ Flavours, or views, or templates, as some may call it, defaults are given, but can be overidden with files on the datadir. Don't like the default html templates, add your own, head.html, story.html etc. """ data = self._request.getData() config = self._request.getConfiguration()
from libs import tools tools.logRequest(py.get('logfile',''), '304') renderer.addHeader(['ETag: "%s"' % entryList[0]['mtime'], 'Last-Modified: %s' % lastModed])
from libs import tools tools.logRequest(config.get('logfile',''), '304') renderer.addHeader(['ETag: "%s"' % entryList[0]['mtime'], 'Last-Modified: %s' % lastModed])
def prepare(args): request = args[0] data = request.getData() entryList = data["entry_list"] renderer = data["renderer"] if entryList: import os, time # Get our first file timestamp for ETag and Last Modified # Last-Modified: Wed, 20 Nov 2002 10:08:12 GMT # ETag: "2bdc4-7b5-3ddb5f0c" lastModed = time.strftime('%a, %d ...
if key.find(item) == 0:
if key.endswith(item) or key.endswith(item + os.sep):
def genitem(self, item): itemlist = item.split(os.sep)
entry.setData(cgi.escape(entry['content']))
entry.setData(cgi.escape(entry.getData()))
def __processEntry(self, entry, current_date): """ Main workhorse of pyblosxom stories, comments and other miscelany goes here
s.feed(entrycontent.getData())
s.feed(entry.getData())
def __processEntry(self, entry, current_date): """ Main workhorse of pyblosxom stories, comments and other miscelany goes here
clist = elistmap.keys() clist.insert(0, "")
clistmap = {} for mem in elistmap.keys(): mem = mem.split(os.sep) for i in range(len(mem)+1): p = os.sep.join(mem[0:i]) clistmap[p] = 0 clist = clistmap.keys()
def genCategories(self): config = self._request.getConfiguration() root = config["datadir"]
def log(str):
def log(*args):
def log(str): f = open(filename, "a") f.write(str + "\n") f.close()
f.write(str + "\n")
for i in args: f.write("%s INFO %s" % (time.asctime(), repr(i))) f.write("\n")
def log(str): f = open(filename, "a") f.write(str + "\n") f.close()
if len(config['datadir']) > 0 and config['datadir'][-1] == os.sep:
if config["datadir"].endswith("\\") or config["datadir"].endswith("/"):
def initialize(self): """ The initialize step further initializes the Request by setting additional information in the _data dict, registering plugins, and entryparsers. """ global VERSION_DATE
def runStaticRenderer(self):
def runStaticRenderer(self, incremental=0):
def runStaticRenderer(self): """ This will go through all possible things in the blog and statically render everything to the "static_dir" specified in the config file.
if smtime < mtime:
if smtime < mtime or not incremental:
def runStaticRenderer(self): """ This will go through all possible things in the blog and statically render everything to the "static_dir" specified in the config file.
renderme.append( (mem, 0) )
renderme.append( (mem, "", 0) )
def runStaticRenderer(self): """ This will go through all possible things in the blog and statically render everything to the "static_dir" specified in the config file.
renderme.append( (mem, 1) )
renderme.append( (mem, "", 1) )
def runStaticRenderer(self): """ This will go through all possible things in the blog and statically render everything to the "static_dir" specified in the config file.
renderme.append( (mem, 0) )
if mem.find("?") != -1: url = mem[:mem.find("?")] query = mem[mem.find("?")+1:] else: url = mem query = "" renderme.append( (url, query, 0) )
def runStaticRenderer(self): """ This will go through all possible things in the blog and statically render everything to the "static_dir" specified in the config file.
for url, i in renderme:
for url, q, i in renderme:
def runStaticRenderer(self): """ This will go through all possible things in the blog and statically render everything to the "static_dir" specified in the config file.
tools.render_entry(self._request, url, "", i)
req = Request() req.addData(self._request.getData()) req.addConfiguration(self._request.getConfiguration()) req.addHttp(self._request.getHttp()) tools.render_entry(req, url, q, i)
def runStaticRenderer(self): """ This will go through all possible things in the blog and statically render everything to the "static_dir" specified in the config file.
email = comment['email'] if email is None:
if comment.has_key('email'): email = comment['email'] else:
def makeXMLField(name, field): return "<"+name+">"+cgi.escape(field[name])+"</"+name+">\n";
'email' : form['email'].value, \
def cb_prepare(args): """ Handle comment related HTTP POST's. @param request: pyblosxom request object @type request: a Pyblosxom request object """ request = args["request"] form = request.getHttp()['form'] config = request.getConfiguration() data = request.getData() if form.has_key("title") and form.has_key("author...
for path in _config['plugin_dirs']:
for path in _config.get('plugin_dirs', []):
def getLogger(log_file=None): """ Creates and retuns a log channel. If no log_file is given the system-wide logfile as defined in config.py is used. If a log_file is given that's where the created logger logs to. @param log_file: optional, the file to log to. @type log_file: C{str} @return: a log channel (Logger insta...
try:
if thismonth in keys:
def generateCalendar(self): """ Generates the calendar. We'd like to walk the archives for things that happen in this month and mark the dates accordingly. After doing that we pass it to a formatting method which turns the thing into HTML. """ config = self._request.getConfiguration() data = self._request.getData() e...
except ValueError:
elif len(keys) == 0 or keys[0] > thismonth:
def generateCalendar(self): """ Generates the calendar. We'd like to walk the archives for things that happen in this month and mark the dates accordingly. After doing that we pass it to a formatting method which turns the thing into HTML. """ config = self._request.getConfiguration() data = self._request.getData() e...
else: index = len(keys) - 1
def generateCalendar(self): """ Generates the calendar. We'd like to walk the archives for things that happen in this month and mark the dates accordingly. After doing that we pass it to a formatting method which turns the thing into HTML. """ config = self._request.getConfiguration() data = self._request.getData() e...
def prepare(args)
def prepare(args):
def prepare(args) """ Populate the L{global py dictionary<py>} with an instance of the L{PyFirstDate} class in the "dayDivClass" key. """ request = args[0] data = request.getData() data["dayDivClass"] = PyFirstDate(py)
data["dayDivClass"] = PyFirstDate(py)
data["dayDivClass"] = PyFirstDate(request)
def prepare(args) """ Populate the L{global py dictionary<py>} with an instance of the L{PyFirstDate} class in the "dayDivClass" key. """ request = args[0] data = request.getData() data["dayDivClass"] = PyFirstDate(py)
<form action="add">
<form action="weblog-add.py">
def genFormPage(): categories=get_blog_dirs() print """\
actual_smtp_keys = []
smtp_keys_defined = []
def verify_installation(request): config = request.getConfiguration() retval = 1 if config.has_key('comment_dir') and not os.path.isdir(config['comment_dir']): print 'The "comment_dir" property in the config file must refer to a directory' retval = 0 actual_smtp_keys = [] smtp_keys=['comment_smtp_server', 'comment_s...
actual_smtp_keys.append(k) if len(k) > 0:
smtp_keys_defined.append(k) if smtp_keys_defined:
def verify_installation(request): config = request.getConfiguration() retval = 1 if config.has_key('comment_dir') and not os.path.isdir(config['comment_dir']): print 'The "comment_dir" property in the config file must refer to a directory' retval = 0 actual_smtp_keys = [] smtp_keys=['comment_smtp_server', 'comment_s...
if i not in actual_smtp_keys:
if i not in smtp_keys_defined:
def verify_installation(request): config = request.getConfiguration() retval = 1 if config.has_key('comment_dir') and not os.path.isdir(config['comment_dir']): print 'The "comment_dir" property in the config file must refer to a directory' retval = 0 actual_smtp_keys = [] smtp_keys=['comment_smtp_server', 'comment_s...
self.outputTemplate(output, entry, 'story')
self.outputTemplate(output, entry, 'story', override=1)
def _processEntry(self, entry, current_date): """ Main workhorse of pyblosxom stories, comments and other miscelany goes here
if self._needs_content_type:
if self._needs_content_type and data['content-type'] !="":
def render(self, header = 1): """ Figures out flavours and such and then renders the content according to which flavour we're using.
def outputTemplate(self, output, entry, flavour_name):
def outputTemplate(self, output, entry, flavour_name, override=0):
def outputTemplate(self, output, entry, flavour_name): """ Find the flavour template for flavour_name, run any blosxom callbacks, substitute entry into it and append the template to the output @param output: @type output: list
@param output:
@param output: list of strings of the output
def outputTemplate(self, output, entry, flavour_name): """ Find the flavour template for flavour_name, run any blosxom callbacks, substitute entry into it and append the template to the output @param output: @type output: list
@param entry:
@param entry: the entry to render with this flavour template
def outputTemplate(self, output, entry, flavour_name): """ Find the flavour template for flavour_name, run any blosxom callbacks, substitute entry into it and append the template to the output @param output: @type output: list
@param flavour_name: - name of the flavour template
@param flavour_name: name of the flavour template
def outputTemplate(self, output, entry, flavour_name): """ Find the flavour template for flavour_name, run any blosxom callbacks, substitute entry into it and append the template to the output @param output: @type output: list
""" template = self.flavour.get(flavour_name, '') args = self._run_callback(flavour_name, {"entry": entry, "template": template })
@param override: whether (1) or not (0) this template can be overriden with the flavour_name property of the entry @type override: boolean """ template = "" if override == 1: actual_flavour_name = entry.get("flavour_name", flavour_name) template = self.flavour.get(actual_flavour_name, '') if not template: template ...
def outputTemplate(self, output, entry, flavour_name): """ Find the flavour template for flavour_name, run any blosxom callbacks, substitute entry into it and append the template to the output @param output: @type output: list
if key == CONTENT_KEY:
if key == CONTENT_KEY or key == CONTENT_KEY + "_escaped":
def has_key(self, key): """ Returns whether a given key is in the metadata dict. If the key is the CONTENT_KEY, then we automatically return true.
'categories':[x['absolute_path']],
'categories':[ fix_path(x['absolute_path'])],
def metaWeblog_getRecentPosts(request, blogid, username, password, numberOfPosts): """ Get the most recent posts Part of the metaWeblog API @param request: the pyblosxom Request instance @type request: Request @param blogid: the id of the blog @type blogid: string @param username: the username @type username: stri...
pass
authenticate(request, username, password) config = request.getConfiguration() name = struct['name'] mimeType = struct['type'] bits = struct['bits'] root = config['xmlrpc_metaweblog_image_dir'] path = os.path.join("%s/%s" % (root, name)) f = None try: f = open(path, 'wb') f.write(bits.data) f.close() except: if f is...
def metaWeblog_newMediaObject(request, blogid, username, password, struct): """ Create a new media object Part of the metaWeblog API @param request: the pyblosxom Request instance @type request: Request @param blogid: the id of the blog @type blogid: string @param username: the username @type username: string @pa...
clist.append("")
clist.append("/")
def walk_filter(arg, dirname, files): if dirname==root: return if not dirname.endswith('CVS') and not dirname.startswith(root+'/comments'): arg.append(dirname.replace(root+'/',''))
if key.endswith(item) or key.endswith(item + os.sep):
if item == '' or key == item or key.startswith(item + os.sep):
def genCategories(self): config = self._request.getConfiguration() root = config["datadir"]
if item == "": d["fullcategory"] = item
d["fullcategory_urlencoded"] = tools.urlencode_text(d["fullcategory"]) d["category_urlencoded"] = tools.urlencode_text(d["category"])
def genCategories(self): config = self._request.getConfiguration() root = config["datadir"]
if self.py['conditionalHTTP'] = 'yes':
if self.py['conditionalHTTP'] == 'yes':
def run(self): """Main loop for pyblosxom""" filelist = (self.py['bl_type'] == 'dir' and tools.Walk(self.py['root_datadir'], int(self.py['depth'])) or [self.py['root_datadir']]) dataList = [] for ourfile in filelist: dataList.append(self.getProperties(ourfile, self.py['root_datadir'])) dataList = tools.sortDictBy(dataL...
data['url'] = '%s/%s' % (config['base_url'], data['pi_bl'])
data['url'] = '%s%s' % (config['base_url'], data['pi_bl'])
def blosxom_process_path_info(args): """ Process HTTP PATH_INFO for URI according to path specifications, fill in data dict accordingly The paths specification looks like this: - C{/foo.html} and C{/cat/foo.html} - file foo.* in / and /cat - C{/cat} - category - C{/2002} - year - C{/2002/Feb} (or 02) - Year and Month ...
email = comment['email']
email = escape_SMTP_commands(clean_author(comment['email']))
def send_email(config, entry, comment, comment_dir, comment_filename): """Send an email to the blog owner on a new comment @param config: configuration as parsed by Pyblosxom @type config: dictionary @param entry: a file entry @type config: dictionary @param comment: comment as generated by readComment @type comment...
absolute_path = self._filename.replace(self._config['datadir'], '')
absolute_path = self._filename.replace(self._root, '')
def __populateBasicMetadata(self): """ Fills the metadata dict with metadata about the given file. This metadata consists of things we pick up from an os.stat call as well as knowledge of the filename and the root directory. The rest of the metadata comes from parsing the file itself which is done with __populateData....
request.addHttp( {"form": cgi.FieldStorage() } )
if not request.getHttp().has_key("form"): request.addHttp( {"form": cgi.FieldStorage() } )
def blosxom_handler(request): """ This is the default blosxom handler. """ import cgi config = request.getConfiguration() data = request.getData() # go through the renderer callback to see if anyone else # wants to render. this renderer gets stored in the data dict # for downstream processing. r = tools.run_callback...
if self._py.has_key('refer_blacklist'): bad_list = string.split(self._py['refer_blacklist'],',')
bad_list = string.split(self._py.get('refer_blacklist',''),',')
def genReferrers(self): """ Generate the list of referring files """ # initialize blacklist if self._py.has_key('refer_blacklist'): bad_list = string.split(self._py['refer_blacklist'],',')
prev = ("%s/%s/%s" % (baseurl, keys[index-1][:4], yearmonth[keys[index-1]]), "<")
prev = ("%s/%s/%s" % (baseurl, keys[index-1][:4], yearmonth[keys[index-1]]), "&lt;")
def generateCalendar(self): """ Generates the calendar. We'd like to walk the archives for things that happen in this month and mark the dates accordingly. After doing that we pass it to a formatting method which turns the thing into HTML. """ config = self._request.getConfiguration() data = self._request.getData() e...
next = ("%s/%s/%s" % (baseurl, keys[index+1][:4], yearmonth[keys[index+1]]), ">")
next = ("%s/%s/%s" % (baseurl, keys[index+1][:4], yearmonth[keys[index+1]]), "&gt;")
def generateCalendar(self): """ Generates the calendar. We'd like to walk the archives for things that happen in this month and mark the dates accordingly. After doing that we pass it to a formatting method which turns the thing into HTML. """ config = self._request.getConfiguration() data = self._request.getData() e...
print repr((root + mem, f))
def Walk(root='.'): """ A really really scaled down version of what we have in tools.py. """ # initialize result = [] # must have at least root folder try: names = os.listdir(root) except os.error: return result # check each file for name in names: if name == "CVS": continue fullname = os.path.normpath(os.path.join(r...
print " print " print "
def Walk(root='.'): """ A really really scaled down version of what we have in tools.py. """ # initialize result = [] # must have at least root folder try: names = os.listdir(root) except os.error: return result # check each file for name in names: if name == "CVS": continue fullname = os.path.normpath(os.path.join(r...
if entryList:
if entryList and entryList[0].has_key('mtime'):
def prepare(args): request = args["request"] data = request.getData() config = request.getConfiguration() entryList = data["entry_list"] renderer = data["renderer"] if entryList: import os, time # Get our first file timestamp for ETag and Last Modified # Last-Modified: Wed, 20 Nov 2002 10:08:12 GMT # ETag: "2bdc4-7b5-...
result = result + Walk( fullname, recurse, pattern, return_folders )
result = result + Walk(fullname, (recurse > 1 and recurse - 1 or 0), pattern, return_folders)
def Walk(root = '.', recurse = 0, pattern = re.compile(r'.*\.txt$'), return_folders = 0 ): """ This function walks a directory tree starting at a specified root folder, and returns a list of all of the files (and optionally folders) that match our pattern(s). Taken from the online Python Cookbook and modified to own ne...
return self._dict.get(key, default)
return self.__getitem__(key, default)
def get(self, key, default=None): return self._dict.get(key, default)
clist = tools.Walk(root, pattern=re.compile('.*'), return_folders=1) clist = [mem[len(root)+1:] for mem in clist] clist.sort() clist.insert(0, "")
def genCategories(self): config = self._request.getConfiguration() root = config["datadir"]
postId = os.path.join(structCategories[0], "%d" % count)
postId = os.path.join(category, "%d" % count)
def _buildPostId(request, blogid, struct): """ Construct the id for the post The algorithm used for constructing the post id is to concatenate the pyblosxom category (directory path, with the datadir prefix removed) with the count of entries. This means that postids are increasing integers. @param request: the HTTP ...
def register(self, func, place=LAST):
def register(self, func, place=MIDDLE):
def register(self, func, place=LAST): """ Registers a function with the callback chain. All functions should take one argument. This argument's contents will depend on the callback chain involved. """ if place == FIRST: self._chain.insert(0, func) else: self._chain.append(func)
""" if place == FIRST: self._chain.insert(0, func) else: self._chain.append(func)
@param func: the function to be called which takes in the argument tuple specified by the callback chain in question @type func: callable @param place: the priority for the function to kick off. 0 is the lowest, 99 is the highest, and we default to 50 if you don't care @type place: int """ self._chain.append((place...
def register(self, func, place=LAST): """ Registers a function with the callback chain. All functions should take one argument. This argument's contents will depend on the callback chain involved. """ if place == FIRST: self._chain.insert(0, func) else: self._chain.append(func)
""" for mem in self._chain: if mem(data) == HANDLED:
This is will stop when one function returns something other than None. It is not guaranteed that every link in the chain will be called. @param data: data is a tuple--refer to the callback chain documentation for what it might hold @type data: tuple of stuff @return: returns whatever is returned by the handler or N...
def executeHandler(self, data): """ Executes a callback chain on a given piece of data. This data could be a string or an object. Consult the documentation for the specific callback chain you're executing.
return
return ret
def executeHandler(self, data): """ Executes a callback chain on a given piece of data. This data could be a string or an object. Consult the documentation for the specific callback chain you're executing.
for mem in self._chain:
chain = self.__getchain__() for mem in chain:
def executeListHandler(self, data): """ Executes a callback chain on a given piece of data. This data could be a string or an object. Consult the documentation for the specific callback chain you're executing.
""" for mem in self._chain:
This is guaranteed to be adjusted by every link in the chain. @param data: data is a tuple--refer to the callback chain documentation for what it might hold @type data: tuple of stuff @returns: the transformed tuple @rtype: varies """ chain = self.__getchain__() for mem in chain:
def executeTransform(self, data): """ Executes a callback chain on a given piece of data. This data could be a string or an object. Consult the documentation for the specific callback chain you're executing.
while re.match(r'^[a-zA-Z0-9]\w*', path_info[0]):
while re.match(r'^[a-zA-Z]\w*', path_info[0]):
def startup(self): self.py['pi_bl'] = '' path_info = []
printout("%s" % cache[filename]['title'])
printout("%s\n" % cache[filename]['title'])
def render(self, header = 1): pyhttp = self._request.getHttp() config = self._request.getConfiguration() data = self._request.getData() printout = self.write
if callbacks != {}:
if methods != {}:
def register_xmlrpc_methods(): return {'system.testing': test, 'system.helloWorld': helloWorld}
def log(str): logger.info(str)
def log(*args): for i in args: logger.info(repr(i))
def log(str): logger.info(str)
self.addHeader(['Content-type: %(content_type)s' % self.flavour])
self.addHeader(['Content-type: %(content-type)s' % data])
def render(self, header = 1): """ Figures out flavours and such and then renders the content according to which flavour we're using.
self._out.write('\n')
self._out.write('\n\n')
def render(self, header = 1): """ Figures out flavours and such and then renders the content according to which flavour we're using.
def cb_start(args): request = args['request'] config = request.getConfiguration() if not config.has_key('comment_dir'): config['comment_dir'] = os.path.join(config['datadir'],'comments') if not config.has_key('comment_ext'): config['comment_ext'] = 'cmt'
def cb_story_end(args): renderer = args['renderer'] entry = args['entry'] template = args['template'] request = args["request"] config = request.getConfiguration() if len(renderer.getContent()) == 1 \ and renderer.flavour.has_key('comment-story') \ and not entry.has_key("nocomments"): output = [] entry['comments'] = re...
sys.path.append(mem)
if os.path.isdir(mem): sys.path.append(mem) else: raise Exception("Plugin directory '%s' does not exist. Please check your config file." % mem)
def initialize_plugins(plugin_dirs, plugin_list): """ Imports and initializes plugins from the directories in the list specified by "plugins_dir". If no such list exists, then we don't load any plugins. If the user specifies a "load_plugins" list of plugins to load, then we explicitly load those plugins in the order ...
pattern = re.compile(r'.+?\.' + taste + '$')
pattern = re.compile(r'.+?\.(?<!config\.)' + taste + '$')
def _getFlavour(self, taste='html'): """ Flavours, or views, or templates, as some may call it, defaults are given, but can be overidden with files on the datadir. Don't like the default html templates, add your own, head.html, story.html etc. """ data = self._request.getData() config = self._request.getConfiguration()
data['path_info'] = path_info
def blosxom_process_path_info(args): """ Process HTTP PATH_INFO for URI according to path specifications, fill in data dict accordingly The paths specification looks like this: - C{/foo.html} and C{/cat/foo.html} - file foo.* in / and /cat - C{/cat} - category - C{/2002} - year - C{/2002/Feb} (or 02) - Year and Month ...
path_info, flav = os.path.splitext(path_info)
path_info, flav = os.path.splitext("/".join(path_info)) path_info = path_info.split("/")
def blosxom_process_path_info(args): """ Process HTTP PATH_INFO for URI according to path specifications, fill in data dict accordingly The paths specification looks like this: - C{/foo.html} and C{/cat/foo.html} - file foo.* in / and /cat - C{/cat} - category - C{/2002} - year - C{/2002/Feb} (or 02) - Year and Month ...
path_info = path_info.split("/")
def blosxom_process_path_info(args): """ Process HTTP PATH_INFO for URI according to path specifications, fill in data dict accordingly The paths specification looks like this: - C{/foo.html} and C{/cat/foo.html} - file foo.* in / and /cat - C{/cat} - category - C{/2002} - year - C{/2002/Feb} (or 02) - Year and Month ...
if args['parser'] == PREFORMATTER_ID:
if args['parser'] == PREFORMATTER_ID and \ args['request'].getData()['flavour'] == "html":
def cb_preformat(args): if args['parser'] == PREFORMATTER_ID: return parse(''.join(args['story']))
file(filename, "w").write('\n'.join(data[4:]))
line = data.pop(0) while line != '': if line == 'Status: 404 Not Found': return line = data.pop(0) file(filename, "w").write('\n'.join(data))
def saveData(filename, document): makepath(filename) print document # Now we disect the document and remove the first few lines data = document.split('\n') file(filename, "w").write('\n'.join(data[4:]))
realfile = py['datadir'] + re.sub('.html', '.txt', pathInfo) if re.match(archiveRoot, redir) and os.path.exists(realfile):
if redir.startswith(archiveRoot):
def saveData(filename, document): makepath(filename) print document # Now we disect the document and remove the first few lines data = document.split('\n') file(filename, "w").write('\n'.join(data[4:]))
p = PyBlosxom(py, xmlrpc)
from libs.pyblosxom import PyBlosxom from libs.Request import Request import os, cgi req = Request() req.addConfiguration(config.py) d = {} for mem in ["PATH_INFO", "SCRIPT_NAME", "REQUEST_METHOD", "HTTP_HOST", "QUERY_STRING", "REQUEST_URI", "HTTP_USER_AGENT", "REMOTE_ADDR"]: d[mem] = os.environ.get(mem, "") req.addH...
def saveData(filename, document): makepath(filename) print document # Now we disect the document and remove the first few lines data = document.split('\n') file(filename, "w").write('\n'.join(data[4:]))
print "Content-Type: text/html\n"
print "Error: 404\nContent-Type: text/html\n"
def saveData(filename, document): makepath(filename) print document # Now we disect the document and remove the first few lines data = document.split('\n') file(filename, "w").write('\n'.join(data[4:]))
return parse(args['story'])
config = args['request'].getConfiguration() baseurl = config.get('genericwiki_baseurl', None) return parse(''.join(args['story']), baseurl)
def cb_preformat(args): """ Preformat callback chain looks for this. @params args: a dict with 'parser' string and a list 'story' @type args: dict """ if args['parser'] == PREFORMATTER_ID: return parse(args['story'])