本文整理汇总了Python中MoinMoin.PageEditor.PageEditor.exists方法的典型用法代码示例。如果您正苦于以下问题:Python PageEditor.exists方法的具体用法?Python PageEditor.exists怎么用?Python PageEditor.exists使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类MoinMoin.PageEditor.PageEditor
的用法示例。
在下文中一共展示了PageEditor.exists方法的14个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: rename
# 需要导入模块: from MoinMoin.PageEditor import PageEditor [as 别名]
# 或者: from MoinMoin.PageEditor.PageEditor import exists [as 别名]
def rename(self):
""" Rename pagename and return the new page """
_ = self.request.getText
form = self.request.form
# Require a valid ticket. Make outside attacks harder by
# requiring two full HTTP transactions
if not wikiutil.checkTicket(form['ticket'][0]):
self.error = _('Please use the interactive user interface to rename pages!')
return
# Get new name from form and normalize.
comment = form.get('comment', [u''])[0]
newpagename = form.get('newpagename')[0]
newpagename = self.request.normalizePagename(newpagename)
# Name might be empty after normalization. To save translation
# work for this extreme case, we just use "EmptyName".
if not newpagename:
newpagename = "EmptyName"
# Valid new name
newpage = PageEditor(self.request, newpagename)
# Check whether a page with the new name already exists
if newpage.exists(includeDeleted=1):
return self.pageExistsError(newpagename)
# Get old page text
savetext = self.page.get_raw_body()
oldpath = self.page.getPagePath(check_create=0)
newpath = newpage.getPagePath(check_create=0)
# Rename page
# NOTE: might fail if another process created newpagename just
# NOW, while you read this comment. Rename is atomic for files -
# but for directories, rename will fail if the directory
# exists. We should have global edit-lock to avoid this.
# See http://docs.python.org/lib/os-file-dir.html
try:
os.rename(oldpath, newpath)
self.newpage = newpage
self.error = None
# Save page text with a comment about the old name
savetext = u"## page was renamed from %s\n%s" % (self.pagename, savetext)
newpage.saveText(savetext, 0, comment=comment)
except OSError, err:
# Try to understand what happened. Maybe its better to check
# the error code, but I just reused the available code above...
if newpage.exists(includeDeleted=1):
return self.pageExistsError(newpagename)
else:
self.error = _('Could not rename page because of file system'
' error: %s.') % unicode(err)
示例2: mainloop
# 需要导入模块: from MoinMoin.PageEditor import PageEditor [as 别名]
# 或者: from MoinMoin.PageEditor.PageEditor import exists [as 别名]
def mainloop(self):
self.init_request()
request = self.request
request.user.may = IAmRoot()
request.cfg.mail_enabled = False
for root, dirs, files in os.walk(self.options.file_dir):
files.sort()
for filename in files:
pagename = self.options.page + filename_function(filename)
#print "Pushing %r as %r" % (filename, pagename)
p = PageEditor(request, pagename, do_editor_backup=0, uid_override=self.options.author, do_revision_backup=0)
if p.exists():
if filename != files[-1]:
continue
else:
p = PageEditor(request, pagename, do_editor_backup=0, uid_override=self.options.author)
fileObj = open(os.path.join(root, filename), 'rb')
try:
acl = ""
if self.options.acl:
acl = "#acl %s\n" % (self.options.acl, )
p.saveText(acl + "#format irc\n" + decodeLinewise(fileObj.read()), 0)
except PageEditor.Unchanged, e:
pass
except PageEditor.SaveError, e:
print "Got %r" % (e, )
fileObj.close()
示例3: execute
# 需要导入模块: from MoinMoin.PageEditor import PageEditor [as 别名]
# 或者: from MoinMoin.PageEditor.PageEditor import exists [as 别名]
def execute(pagename, request):
request.headers["Content-Type"] = "text/plain; charset=ascii"
if request.environ['REQUEST_METHOD'] != 'POST':
return
form = values_to_form(request.values)
content = form.get('content', [None])[0]
if not content:
sendfault(request, "Missing page content")
return
pagename = normalize_pagename(pagename, request.cfg)
if not pagename:
sendfault(request, "No page name entered")
return
if not request.user.may.write(pagename):
sendfault(request, "You are not allowed to edit this page")
return
page = PageEditor(request, pagename)
if page.exists():
sendfault(request, "Page already exists.")
return
msg = ""
try:
msg = page.saveText(content, 0)
except page.SaveError, msg:
sendfault(request, "Failed to save page: %s" % pagename)
return
示例4: execute
# 需要导入模块: from MoinMoin.PageEditor import PageEditor [as 别名]
# 或者: from MoinMoin.PageEditor.PageEditor import exists [as 别名]
def execute(pagename, request):
_ = request.getText
actname = __name__.split('.')[-1]
# Create a page editor that does not do edior backups, becuase
# delete generate "deleted" version, of the page.
page = PageEditor(request, pagename, do_editor_backup=0)
# be extra paranoid in dangerous actions
if actname in request.cfg.excluded_actions \
or not request.user.may.write(pagename) \
or not request.user.may.delete(pagename):
return page.send_page(request,
msg = _('You are not allowed to delete this page.'))
# check whether page exists at all
if not page.exists():
return page.send_page(request,
msg = _('This page is already deleted or was never created!'))
# check whether the user clicked the delete button
if request.form.has_key('button') and request.form.has_key('ticket'):
# check whether this is a valid deletion request (make outside
# attacks harder by requiring two full HTTP transactions)
if not wikiutil.checkTicket(request.form['ticket'][0]):
return page.send_page(request,
msg = _('Please use the interactive user interface to delete pages!'))
# Delete the page
page.deletePage(request.form.get('comment', [u''])[0])
return page.send_page(request,
msg = _('Page "%s" was successfully deleted!') % (pagename,))
# send deletion form
ticket = wikiutil.createTicket()
querytext = _('Really delete this page?')
button = _('Delete')
comment_label = _("Optional reason for the deletion")
# TODO: this form suck, redesign like RenamePage
formhtml = '''
<form method="post" action="">
<strong>%(querytext)s</strong>
<input type="hidden" name="action" value="%(actname)s">
<input type="hidden" name="ticket" value="%(ticket)s">
<input type="submit" name="button" value="%(button)s">
<p>
%(comment_label)s<br>
<input type="text" name="comment" size="60" maxlength="80">
</form>''' % {
'querytext': querytext,
'actname': actname,
'ticket': ticket,
'button': button,
'comment_label': comment_label,
}
return page.send_page(request, msg=formhtml)
示例5: do_deletepage
# 需要导入模块: from MoinMoin.PageEditor import PageEditor [as 别名]
# 或者: from MoinMoin.PageEditor.PageEditor import exists [as 别名]
def do_deletepage(self, pagename, comment="Deleted by the scripting subsystem."):
""" Marks a page as deleted (like the DeletePage action).
@param pagename: page to delete
@param comment: the related comment (optional)
"""
_ = self.request.getText
page = PageEditor(self.request, pagename, do_editor_backup=0)
if not page.exists():
raise RuntimeScriptException(_("The page %s does not exist.") % pagename)
page.deletePage(comment)
示例6: xmlrpc_mergeDiff
# 需要导入模块: from MoinMoin.PageEditor import PageEditor [as 别名]
# 或者: from MoinMoin.PageEditor.PageEditor import exists [as 别名]
def xmlrpc_mergeDiff(self, pagename, diff, local_rev, delta_remote_rev, last_remote_rev, interwiki_name, normalised_name):
"""
Merges a diff sent by the remote machine and returns the number of the new revision.
Additionally, this method tags the new revision.
@param pagename: The pagename that is currently dealt with.
@param diff: The diff that can be applied to the version specified by delta_remote_rev.
If it is None, the page is deleted.
@param local_rev: The revno of the page on the other wiki system, used for the tag.
@param delta_remote_rev: The revno that the diff is taken against.
@param last_remote_rev: The last revno of the page `pagename` that is known by the other wiki site.
@param interwiki_name: Used to build the interwiki tag.
@param normalised_name: The normalised pagename that is common to both wikis.
@return: Returns the current revision number after the merge was done. Or one of the following errors:
* "SUCCESS" - the page could be merged and tagged successfully.
* "NOT_EXIST" - item does not exist and there was not any content supplied.
* "LASTREV_INVALID" - the page was changed and the revision got invalid
* "INTERNAL_ERROR" - there was an internal error
* "NOT_ALLOWED" - you are not allowed to do the merge operation on the page
"""
from MoinMoin.util.bdiff import decompress, patch
from MoinMoin.wikisync import TagStore, BOTH
from MoinMoin.packages import unpackLine
LASTREV_INVALID = xmlrpclib.Fault("LASTREV_INVALID", "The page was changed")
pagename = self._instr(pagename)
comment = u"Remote Merge - %r" % unpackLine(interwiki_name)[-1]
# User may read page?
if not self.request.user.may.read(pagename) or not self.request.user.may.write(pagename):
return xmlrpclib.Fault("NOT_ALLOWED", "You are not allowed to write to this page.")
# XXX add locking here!
# current version of the page
currentpage = PageEditor(self.request, pagename, do_editor_backup=0)
if last_remote_rev is not None and currentpage.get_real_rev() != last_remote_rev:
return LASTREV_INVALID
if not currentpage.exists() and diff is None:
return xmlrpclib.Fault("NOT_EXIST", "The page does not exist and no diff was supplied.")
if diff is None: # delete the page
try:
currentpage.deletePage(comment)
except PageEditor.AccessDenied, (msg, ):
return xmlrpclib.Fault("NOT_ALLOWED", msg)
return currentpage.get_real_rev()
示例7: do_deletepage
# 需要导入模块: from MoinMoin.PageEditor import PageEditor [as 别名]
# 或者: from MoinMoin.PageEditor.PageEditor import exists [as 别名]
def do_deletepage(self, pagename, comment="Deleted by the scripting subsystem."):
""" Marks a page as deleted (like the DeletePage action).
@param pagename: page to delete
@param comment: the related comment (optional)
"""
if self.request.user.may.write(pagename):
_ = self.request.getText
page = PageEditor(self.request, pagename, do_editor_backup=0)
if not page.exists():
raise RuntimeScriptException(_("The page %s does not exist.") % pagename)
page.deletePage(comment)
else:
self.msg += u"action delete page: not enough rights - nothing done \n"
示例8: delete
# 需要导入模块: from MoinMoin.PageEditor import PageEditor [as 别名]
# 或者: from MoinMoin.PageEditor.PageEditor import exists [as 别名]
def delete(request, pagename, comment = None):
_ = request.getText
# check ACLs
if not request.user.may.delete(pagename):
return xmlrpclib.Fault(1, _("You are not allowed to delete this page"))
# Deletes pages
page = PageEditor(request, pagename, do_editor_backup=0)
if not page.exists():
return xmlrpclib.Fault(1, _('No such page %s' % pagename))
page.deletePage(comment)
return True
示例9: do_renamepage
# 需要导入模块: from MoinMoin.PageEditor import PageEditor [as 别名]
# 或者: from MoinMoin.PageEditor.PageEditor import exists [as 别名]
def do_renamepage(self, pagename, newpagename, author=u"Scripting Subsystem", comment=u"Renamed by the scripting subsystem."):
""" Renames a page.
@param pagename: name of the target page
@param newpagename: name of the new page
@param author: user name of the editor (optional)
@param comment: comment related to this revision (optional)
"""
if self.request.user.may.write(pagename):
_ = self.request.getText
page = PageEditor(self.request, pagename, do_editor_backup=0, uid_override=author)
if not page.exists():
raise RuntimeScriptException(_("The page %s does not exist.") % pagename)
newpage = PageEditor(self.request, newpagename)
page.renamePage(newpage.page_name, comment=u"Renamed from '%s'" % (pagename))
self.msg += u'%(pagename)s renamed to %(newpagename)s\n' % {
"pagename": pagename,
"newpagename": newpagename}
else:
self.msg += u"action rename page: not enough rights - nothing done \n"
示例10: group_rename
# 需要导入模块: from MoinMoin.PageEditor import PageEditor [as 别名]
# 或者: from MoinMoin.PageEditor.PageEditor import exists [as 别名]
def group_rename(request, grouppage, accounts):
_ = request.getText
success, msg = check_grouppage(request, grouppage)
if not success:
raise GroupException(msg + "(%s)" % (grouppage))
check_users(request, accounts[::2])
if len(accounts) % 2:
raise ValueError(_('Wrong number of arguments for rename.'))
page = PageEditor(request, grouppage)
if page.exists():
members = request.groups[grouppage].members
else:
raise GroupException(_('Group does not exist: ') + grouppage)
for uname in accounts[::2]:
if uname not in members:
raise GroupException(_('User not in group: ') + uname)
page = PageEditor(request, grouppage)
pagetext = page.get_raw_body()
newtext = _group_rename(request, pagetext, accounts)
msg = page.saveText(newtext, 0,
comment="Changed group members: " +
' -> '.join(accounts))
newmembers = request.groups[grouppage].members
testmembers = members.copy()
for user1, user2 in zip(accounts[::2], accounts[1::2]):
testmembers.remove(user1)
testmembers.add(user2)
if testmembers != newmembers:
msg = page.saveText(pagetext, 0,
comment="Reverting due to problems in group operation.")
raise GroupException(_('Rename unsuccessful for unknown reasons.'))
return True, msg
示例11: group_add
# 需要导入模块: from MoinMoin.PageEditor import PageEditor [as 别名]
# 或者: from MoinMoin.PageEditor.PageEditor import exists [as 别名]
def group_add(request, grouppage, accounts, create=False, usercheck=True):
_ = request.getText
success, msg = check_grouppage(request, grouppage, createcheck=not create)
if not success:
raise GroupException(msg + "(%s)" % (grouppage))
if usercheck:
check_users(request, accounts)
page = PageEditor(request, grouppage)
if page.exists():
members = request.groups[grouppage].members | request.groups[grouppage].member_groups
elif create:
members = set([])
else:
raise GroupException(_('Group does not exist: ') + grouppage)
for item in accounts:
if item in members:
raise GroupException(item + _(' already in group: ') + grouppage)
pagetext = page.get_raw_body()
if not pagetext:
pagetext = ''
newtext = _group_add(request, pagetext, accounts)
msg = page.saveText(newtext, 0,
comment="Added to group: " + ', '.join(accounts))
newmembers = request.groups[grouppage].members | request.groups[grouppage].member_groups
if not newmembers == members | set(accounts):
msg = page.saveText(pagetext, 0,
comment="Reverting due to problems in group operation.")
raise GroupException(_('Add unsuccessful for unknown reasons.'))
return True, msg
示例12: read_events
# 需要导入模块: from MoinMoin.PageEditor import PageEditor [as 别名]
# 或者: from MoinMoin.PageEditor.PageEditor import exists [as 别名]
def read_events(self, url):
"""
Read events from the given events RSS feed, specified by 'url', creating
new Wiki pages where appropriate.
"""
request = self.request
request.user.may = IAmRoot()
category_pagenames = self.options.categories.split()
# Locate the template for events.
template_page = PageEditor(request, self.options.template)
if not template_page.exists():
print "Template %r cannot be found. Not importing any events!" % self.options.template
return
# Process the feed.
feed = urllib.urlopen(url)
try:
nodes = xml.dom.pulldom.parse(feed)
event_details = {}
in_item = 0
# Read the nodes from the feed.
for node_type, value in nodes:
if node_type == xml.dom.pulldom.START_ELEMENT:
if value.nodeName == "item":
in_item = 1
# Get the value of the important fields.
elif in_item and value.nodeName in self.FIELDS:
nodes.expandNode(value)
event_details[value.nodeName] = self.text(value)
# Where all fields have been read, make a new page.
if reduce(lambda x, y: x and event_details.has_key(y), self.FIELDS, 1):
# Define the page.
title = event_details["title"]
# Use any parent page information.
full_title = EventAggregatorSupport.getFullPageName(self.options.parent, title)
# Find the start and end dates.
dates = EventAggregatorSupport.getDateStrings(title)
# Require one or two dates.
if dates and 1 <= len(dates) <= 2:
# Deduce the end date.
if len(dates) == 2:
start_date, end_date = dates
elif len(dates) == 1:
start_date = end_date = dates[0]
# Load the new page and replace the event details in the body.
new_page = PageEditor(request, full_title,
uid_override=self.options.author)
# Delete the page if requested.
if new_page.exists() and self.options.delete:
try:
new_page.deletePage()
except new_page.AccessDenied:
print "Page %r has not been deleted." % full_title
# Complete the new page.
elif not new_page.exists() or self.options.overwrite:
event_details["summary"] = title
event_details["start"] = start_date
event_details["end"] = end_date
try:
EventAggregatorSupport.fillEventPageFromTemplate(
template_page, new_page, event_details,
category_pagenames)
except new_page.Unchanged:
print "Page %r is not changed." % full_title
else:
print "Not overwriting page %r." % full_title
#.........这里部分代码省略.........
示例13: create_event
# 需要导入模块: from MoinMoin.PageEditor import PageEditor [as 别名]
# 或者: from MoinMoin.PageEditor.PageEditor import exists [as 别名]
def create_event(self, request):
"Create an event page using the 'request'."
_ = request.getText
form = self.get_form()
category_pagenames = form.get("category", [])
description = form.get("description", [None])[0]
location = (form.get("location") or form.get("new-location") or [""])[0]
latitude = form.get("latitude", [None])[0]
longitude = form.get("longitude", [None])[0]
link = form.get("link", [None])[0]
topics = form.get("topics", [])
start_regime = form.get("start-regime", [None])[0]
end_regime = form.get("end-regime", form.get("start-regime", [None]))[0]
start_offset = form.get("start-offset", [None])[0]
end_offset = form.get("end-offset", [None])[0]
start_zone = start_regime or start_offset
end_zone = end_regime or end_offset
page_name = form.get("page-name", [None])[0]
# Validate certain fields.
title = form.get("title", [""])[0].strip()
template = form.get("template", [""])[0].strip()
parent = form.get("parent", [""])[0].strip()
if not title:
return 0, _("No event title specified.")
if not template:
return 0, _("No event template specified.")
try:
start_day = self._get_input(form, "start-day")
start_month = self._get_input(form, "start-month")
start_year = self._get_input(form, "start-year")
if not start_day or not start_month or not start_year:
return 0, _("A start date must be specified.")
end_day = self._get_input(form, "end-day", start_day)
end_month = self._get_input(form, "end-month", start_month)
end_year = self._get_input(form, "end-year", start_year)
except (TypeError, ValueError):
return 0, _("Days and years must be numbers yielding a valid date!")
try:
start_hour = self._get_input(form, "start-hour")
start_minute = self._get_input(form, "start-minute")
start_second = self._get_input(form, "start-second")
end_hour = self._get_input(form, "end-hour")
end_minute = self._get_input(form, "end-minute")
end_second = self._get_input(form, "end-second")
except (TypeError, ValueError):
return 0, _("Hours, minutes and seconds must be numbers yielding a valid time!")
start_date = DateTime(
(start_year, start_month, start_day, start_hour, start_minute, start_second, start_zone)
)
start_date.constrain()
end_date = DateTime(
(end_year, end_month, end_day, end_hour, end_minute, end_second, end_zone)
)
end_date.constrain()
# An elementary date ordering check.
if (start_date.as_date() != end_date.as_date() or start_date.has_time() and end_date.has_time()) and start_date > end_date:
start_date, end_date = end_date, start_date
event_details = {
"start" : str(start_date), "end" : str(end_date),
"title" : title, "summary" : title,
"description" : description, "location" : location, "link" : link,
"topics" : [topic for topic in topics if topic]
}
if latitude and longitude:
event_details["geo"] = latitude, longitude
# Copy the template.
template_page = PageEditor(request, template)
if not template_page.exists():
return 0, _("Event template not available.")
# Use any parent page information.
full_title = getFullPageName(parent, title)
if page_name:
#.........这里部分代码省略.........
示例14: __init__
# 需要导入模块: from MoinMoin.PageEditor import PageEditor [as 别名]
# 或者: from MoinMoin.PageEditor.PageEditor import exists [as 别名]
class RenamePage:
""" Rename page action
Note: the action name is the class name
"""
def __init__(self, pagename, request):
self.request = request
self.pagename = pagename
self.page = PageEditor(request, pagename)
self.newpage = None
self.error = ''
def allowed(self):
""" Check if user is allowed to do this
This could be a standard method of the base action class, doing
the filtering by action class name and cfg.allowed_actions.
"""
may = self.request.user.may
return (self.__class__.__name__ in self.request.cfg.allowed_actions and
may.write(self.pagename) and may.delete(self.pagename))
def render(self):
""" Render action
This action return a wiki page with optional message, or
redirect to new page.
"""
_ = self.request.getText
form = self.request.form
if form.has_key('cancel'):
# User canceled
return self.page.send_page(self.request)
# Validate user rights and page state. If we get error here, we
# return an error message, without the rename form.
error = None
if not self.allowed():
error = _('You are not allowed to rename pages in this wiki!')
elif not self.page.exists():
error = _('This page is already deleted or was never created!')
if error:
# Send page with an error message
return self.page.send_page(self.request, msg=error)
# Try to rename. If we get an error here, we return the error
# message with a rename form.
elif (form.has_key('rename') and form.has_key('newpagename') and
form.has_key('ticket')):
# User replied to the rename form with all required items
self.rename()
if not self.error:
self.request.http_redirect(self.newpage.url(self.request))
return self.request.finish()
# A new form request, or form has missing data, or rename
# failed. Return a new form with optional error.
return self.page.send_page(self.request, msg=self.makeform())
def rename(self):
""" Rename pagename and return the new page """
_ = self.request.getText
form = self.request.form
# Require a valid ticket. Make outside attacks harder by
# requiring two full HTTP transactions
if not wikiutil.checkTicket(form['ticket'][0]):
self.error = _('Please use the interactive user interface to rename pages!')
return
# Get new name from form and normalize.
comment = form.get('comment', [u''])[0]
newpagename = form.get('newpagename')[0]
newpagename = self.request.normalizePagename(newpagename)
# Name might be empty after normalization. To save translation
# work for this extreme case, we just use "EmptyName".
if not newpagename:
newpagename = "EmptyName"
# Valid new name
newpage = PageEditor(self.request, newpagename)
# Check whether a page with the new name already exists
if newpage.exists(includeDeleted=1):
return self.pageExistsError(newpagename)
# Get old page text
savetext = self.page.get_raw_body()
oldpath = self.page.getPagePath(check_create=0)
newpath = newpage.getPagePath(check_create=0)
# Rename page
# NOTE: might fail if another process created newpagename just
# NOW, while you read this comment. Rename is atomic for files -
# but for directories, rename will fail if the directory
# exists. We should have global edit-lock to avoid this.
#.........这里部分代码省略.........