本文整理汇总了Python中MoinMoin.action.AttachFile._get_files方法的典型用法代码示例。如果您正苦于以下问题:Python AttachFile._get_files方法的具体用法?Python AttachFile._get_files怎么用?Python AttachFile._get_files使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类MoinMoin.action.AttachFile
的用法示例。
在下文中一共展示了AttachFile._get_files方法的10个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: _index_page
# 需要导入模块: from MoinMoin.action import AttachFile [as 别名]
# 或者: from MoinMoin.action.AttachFile import _get_files [as 别名]
def _index_page(self, writer, page, update):
""" Index a page - assumes that the write lock is acquired
@arg writer: the index writer object
@arg page: a page object
@arg update: False = index in any case, True = index only when changed
"""
pagename = page.page_name
request = page.request
mtime = page.mtime_usecs()
if update:
query = BooleanQuery()
query.add(TermQuery(Term("pagename", pagename)), True, False)
query.add(TermQuery(Term("attachment", "")), True, False)
docs = self._search(query)
updated = len(docs) == 0 or mtime > int(docs[0].get('mtime'))
else:
updated = True
request.log("%s %r" % (pagename, updated))
if updated:
d = document.Document()
d.add(document.Keyword('pagename', pagename))
d.add(document.Keyword('mtime', str(mtime)))
d.add(document.Keyword('attachment', '')) # this is a real page, not an attachment
d.add(document.Text('title', pagename, store=False))
d.add(document.Text('text', page.get_raw_body(), store=False))
links = page.getPageLinks(request)
t = document.Text('links', '', store=False)
t.stringVal = links
d.add(t)
d.add(document.Text('link_text', ' '.join(links), store=False))
writer.addDocument(d)
from MoinMoin.action import AttachFile
attachments = AttachFile._get_files(request, pagename)
for att in attachments:
filename = AttachFile.getFilename(request, pagename, att)
mtime = wikiutil.timestamp2version(os.path.getmtime(filename))
if update:
query = BooleanQuery()
query.add(TermQuery(Term("pagename", pagename)), True, False)
query.add(TermQuery(Term("attachment", att)), True, False)
docs = self._search(query)
updated = len(docs) == 0 or mtime > int(docs[0].get('mtime'))
else:
updated = True
request.log("%s %s %r" % (pagename, att, updated))
if updated:
att_content = self.contentfilter(filename)
d = document.Document()
d.add(document.Keyword('pagename', pagename))
d.add(document.Keyword('mtime', str(mtime)))
d.add(document.Keyword('attachment', att)) # this is an attachment, store its filename
d.add(document.Text('title', att, store=False)) # the filename is the "title" of an attachment
d.add(document.Text('text', att_content, store=False))
writer.addDocument(d)
示例2: nuke_page
# 需要导入模块: from MoinMoin.action import AttachFile [as 别名]
# 或者: from MoinMoin.action.AttachFile import _get_files [as 别名]
def nuke_page(request, pagename):
""" completely delete a page, everything in the pagedir """
attachments = AttachFile._get_files(request, pagename)
for attachment in attachments:
AttachFile.remove_attachment(request, pagename, attachment)
page = PageEditor(request, pagename, do_editor_backup=False)
page.deletePage()
# really get rid of everything there:
fpath = page.getPagePath(check_create=0)
shutil.rmtree(fpath, True)
示例3: _index_page
# 需要导入模块: from MoinMoin.action import AttachFile [as 别名]
# 或者: from MoinMoin.action.AttachFile import _get_files [as 别名]
def _index_page(self, request, connection, pagename, mode="update"):
""" Index a page.
Index all revisions (if wanted by configuration) and all attachments.
@param request: request suitable for indexing
@param connection: the Indexer connection object
@param pagename: a page name
@param mode: 'add' = just add, no checks
'update' = check if already in index and update if needed (mtime)
"""
page = Page(request, pagename)
revlist = page.getRevList() # recent revs first, does not include deleted revs
logging.debug("indexing page %r, %d revs found" % (pagename, len(revlist)))
if not revlist:
# we have an empty revision list, that means the page is not there any more,
# likely it (== all of its revisions, all of its attachments) got either renamed or nuked
wikiname = request.cfg.interwikiname or u"Self"
sc = self.get_search_connection()
docs_to_delete = sc.get_all_documents_with_fields(wikiname=wikiname, pagename=pagename)
# any page rev, any attachment
sc.close()
for doc in docs_to_delete:
connection.delete(doc.id)
logging.debug("page %s (all revs, all attachments) removed from xapian index" % pagename)
else:
if request.cfg.xapian_index_history:
index_revs, remove_revs = revlist, []
else:
if page.exists(): # is current rev not deleted?
index_revs, remove_revs = revlist[:1], revlist[1:]
else:
index_revs, remove_revs = [], revlist
for revno in index_revs:
updated = self._index_page_rev(request, connection, pagename, revno, mode=mode)
logging.debug("updated page %r rev %d (updated==%r)" % (pagename, revno, updated))
if not updated:
# we reached the revisions that are already present in the index
break
for revno in remove_revs:
# XXX remove_revs can be rather long for pages with many revs and
# XXX most page revs usually will be already deleted. optimize?
self._remove_page_rev(request, connection, pagename, revno)
logging.debug("removed page %r rev %d" % (pagename, revno))
from MoinMoin.action import AttachFile
for attachmentname in AttachFile._get_files(request, pagename):
self._index_attachment(request, connection, pagename, attachmentname, mode)
示例4: execute
# 需要导入模块: from MoinMoin.action import AttachFile [as 别名]
# 或者: from MoinMoin.action.AttachFile import _get_files [as 别名]
def execute(pagename, request):
"""
Handle action=IntraFarmCopy
"""
if not request.user.may.read(pagename):
Page(request, pagename).send_page()
return
# Which local farm wiki - assume team for now
to_wiki_url = COPY_TO_WIKI_URL
# New page name
to_wiki_pagename = '%s%s' % (COPY_TO_PREFIX, pagename)
# create page at local wiki if it doesn't exist
to_request = ScriptContext(to_wiki_url)
# login this user remotely
to_uid = user.getUserId(to_request, request.user.name)
to_user = user.User(to_request, id=to_uid, name=request.user.name, password=request.user.password, auth_method="moin")
to_request.user = to_user
try:
page = Page(to_request, to_wiki_pagename)
except:
return action_error(u'Error accessing destination page')
if not page.exists():
pe = PageEditor(to_request, to_wiki_pagename)
# make initial revision pointer to original
try:
pe.saveText(u'[[%s:%s]]' % (request.cfg.interwikiname, pagename), 0, comment="Automated IntraFarmCopy pointing to original page")
except pe.Unchanged:
return action_error(u'Could not save initial page')
except pe.AccessDenied:
return action_error(u'Could not acquire credentials')
# make next revision content of this page
try:
pe.saveText(Page(request, pagename).get_raw_body(), 0, comment="Automated IntraFarmCopy importing contents from original page at [[%s:%s]]" % (request.cfg.interwikiname, pagename))
except pe.Unchanged:
return action_error(u'Could not save destination page text')
# send attachments over
attachments = AttachFile._get_files(request, pagename)
for attachname in attachments:
filename = AttachFile.getFilename(request, pagename, attachname)
if not os.path.isfile(filename):
continue
to_filename = AttachFile.getFilename(to_request, to_wiki_pagename, attachname)
shutil.copyfile(filename, to_filename)
AttachFile._addLogEntry(to_request, 'ATTNEW', to_wiki_pagename, attachname)
# redirect user to view new page in other wiki
request.http_redirect('%s%s' % (to_wiki_url, to_wiki_pagename))
return
else:
return action_error(u'Destination page already exists!')
示例5: sendForm
# 需要导入模块: from MoinMoin.action import AttachFile [as 别名]
# 或者: from MoinMoin.action.AttachFile import _get_files [as 别名]
def sendForm(self):
request = self.request
_ = request.getText
## Begin form
request.write(u'<form method="GET" action="%s">\n' %
actionname(request))
request.write(u'<input type=hidden name=action value="ViewDot">')
request.write(u"<table>\n<tr>\n")
# format
request.write(u"<td>\n" + _('Output format') + u"<br>\n")
for type in self.available_formats:
request.write(u'<input type="radio" name="format" ' +
u'value="%s"%s%s<br>\n' %
(form_escape(type),
type == self.format and " checked>" or ">",
wikiutil.escape(type)))
# graphengine
request.write(u"<td>\n" + _('Output graphengine') + u"<br>\n")
for type in self.available_graphengines:
request.write(u'<input type="radio" name="graphengine" ' +
u'value="%s"%s%s<br>\n' %
(form_escape(type),
type == self.graphengine and " checked>" or ">",
wikiutil.escape(type)))
request.write(_("Dot file") + "<br>\n" +
u'<select name="attachment">\n')
# Use request.rootpage, request.page has weird failure modes
for page in request.rootpage.getPageList():
# Page#getPageList filters out pages to which the user doesn't have
# read access.
files = AttachFile._get_files(request, page)
for file in files:
if file.endswith('.dot') or file.endswith('.gv'):
request.write('<option label="%s" value="%s">%s</option>\n'
% (form_escape(file), form_escape("attachment:%s/%s" % (page, file)),
wikiutil.escape("%s/%s" % (page, file))))
request.write('</select>\n</table>\n')
request.write(u'<input type=submit name=view ' +
'value="%s">\n' % form_escape(_('View')))
request.write(u'<input type=submit name=help ' +
'value="%s"><br>\n' % form_escape(_('Inline')))
request.write(u'</form>\n')
示例6: xmlrpc_listAttachments
# 需要导入模块: from MoinMoin.action import AttachFile [as 别名]
# 或者: from MoinMoin.action.AttachFile import _get_files [as 别名]
def xmlrpc_listAttachments(self, pagename):
""" Get all attachments associated with pagename
Deprecated.
@param pagename: pagename (utf-8)
@rtype: list
@return: a list of utf-8 attachment names
"""
pagename = self._instr(pagename)
# User may read page?
if not self.request.user.may.read(pagename):
return self.notAllowedFault()
result = AttachFile._get_files(self.request, pagename)
return result
示例7: get_attachment_dict
# 需要导入模块: from MoinMoin.action import AttachFile [as 别名]
# 或者: from MoinMoin.action.AttachFile import _get_files [as 别名]
def get_attachment_dict(self, page_name):
""" Returns a dict of attachments
The structure of the dictionary is:
{ file_name : [file_size, get_url], ... }
@param page_name:
@rtype: attachments dictionary
@return: attachments dictionary
"""
attach_dir = AttachFile.getAttachDir(self.request, page_name)
files = AttachFile._get_files(self.request, page_name)
attachments = {}
for file in files:
fsize = float(os.stat(os.path.join(attach_dir,file).encode(config.charset))[6])
get_url = AttachFile.getAttachUrl(page_name, file, self.request, escaped=1)
attachments[file] = [fsize, get_url]
return attachments
示例8: _index_page
# 需要导入模块: from MoinMoin.action import AttachFile [as 别名]
# 或者: from MoinMoin.action.AttachFile import _get_files [as 别名]
def _index_page(self, writer, page, mode='update'):
""" Index a page - assumes that the write lock is acquired
@arg writer: the index writer object
@arg page: a page object
@arg mode: 'add' = just add, no checks
'update' = check if already in index and update if needed (mtime)
"""
request = page.request
wikiname = request.cfg.interwikiname or "Self"
pagename = page.page_name
mtime = page.mtime_usecs()
revision = str(page.get_real_rev())
itemid = "%s:%s:%s" % (wikiname, pagename, revision)
author = page.edit_info().get('editor', '?')
# XXX: Hack until we get proper metadata
language, stem_language = self._get_languages(page)
categories = self._get_categories(page)
domains = tuple(self._get_domains(page))
updated = False
if mode == 'update':
# from #xapian: if you generate a special "unique id" term,
# you can just call database.replace_document(uid_term, doc)
# -> done in xapwrap.index.Index.index()
query = xapidx.RawQuery(xapdoc.makePairForWrite('itemid', itemid))
enq, mset, docs = writer.search(query, valuesWanted=['pagename', 'attachment', 'mtime', 'wikiname', ])
if docs:
doc = docs[0] # there should be only one
uid = doc['uid']
docmtime = long(doc['values']['mtime'])
updated = mtime > docmtime
logging.debug("uid %r: mtime %r > docmtime %r == updated %r" % (uid, mtime, docmtime, updated))
else:
uid = None
updated = True
elif mode == 'add':
updated = True
logging.debug("%s %r" % (pagename, updated))
if updated:
xwname = xapdoc.SortKey('wikiname', wikiname)
xpname = xapdoc.SortKey('pagename', pagename)
xattachment = xapdoc.SortKey('attachment', '') # this is a real page, not an attachment
xmtime = xapdoc.SortKey('mtime', str(mtime))
xrev = xapdoc.SortKey('revision', revision)
xtitle = xapdoc.TextField('title', pagename, True) # prefixed
mimetype = 'text/%s' % page.pi['format'] # XXX improve this
xkeywords = [xapdoc.Keyword('itemid', itemid),
xapdoc.Keyword('lang', language),
xapdoc.Keyword('stem_lang', stem_language),
xapdoc.Keyword('fulltitle', pagename),
xapdoc.Keyword('revision', revision),
xapdoc.Keyword('author', author),
] + \
[xapdoc.Keyword('mimetype', mt) for mt in [mimetype, ] + mimetype.split('/')]
for pagelink in page.getPageLinks(request):
xkeywords.append(xapdoc.Keyword('linkto', pagelink))
for category in categories:
xkeywords.append(xapdoc.Keyword('category', category))
for domain in domains:
xkeywords.append(xapdoc.Keyword('domain', domain))
xcontent = xapdoc.TextField('content', page.get_raw_body())
doc = xapdoc.Document(textFields=(xcontent, xtitle),
keywords=xkeywords,
sortFields=(xpname, xattachment,
xmtime, xwname, xrev),
)
doc.analyzerFactory = getWikiAnalyzerFactory(request,
stem_language)
if mode == 'update':
logging.debug("%s (replace %r)" % (pagename, uid))
doc.uid = uid
id = writer.index(doc)
elif mode == 'add':
logging.debug("%s (add)" % (pagename, ))
id = writer.index(doc)
from MoinMoin.action import AttachFile
attachments = AttachFile._get_files(request, pagename)
for att in attachments:
filename = AttachFile.getFilename(request, pagename, att)
att_itemid = "%s:%s//%s" % (wikiname, pagename, att)
mtime = wikiutil.timestamp2version(os.path.getmtime(filename))
if mode == 'update':
query = xapidx.RawQuery(xapdoc.makePairForWrite('itemid', att_itemid))
enq, mset, docs = writer.search(query, valuesWanted=['pagename', 'attachment', 'mtime', ])
logging.debug("##%r %r" % (filename, docs))
if docs:
doc = docs[0] # there should be only one
uid = doc['uid']
docmtime = long(doc['values']['mtime'])
updated = mtime > docmtime
logging.debug("uid %r: mtime %r > docmtime %r == updated %r" % (uid, mtime, docmtime, updated))
else:
uid = None
updated = True
elif mode == 'add':
#.........这里部分代码省略.........
示例9: execute
# 需要导入模块: from MoinMoin.action import AttachFile [as 别名]
# 或者: from MoinMoin.action.AttachFile import _get_files [as 别名]
def execute(pagename, request):
_ = request.getText
if not request.user or not request.user.isSuperUser():
msg = _('Only superuser is allowed to use this action.')
request.theme.add_msg(msg, "error")
request.page.send_page()
return ''
fmt = request.html_formatter
language_setup_page = 'LanguageSetup'
not_translated_system_pages = 'not_translated_system_pages.zip'
files = AttachFile._get_files(request, language_setup_page)
if not files:
msg = _('No page packages found.')
request.theme.add_msg(msg, "error")
request.page.send_page()
return ''
wiki_languages = list(set([lang_file.split('--')[0] for lang_file in files]) - set(['00_needs_fixing.zip']))
wiki_languages.sort()
lang = request.values.get('language') or 'English'
target = request.values.get('target') or ''
msg = ''
# if target is given it tries to install the package.
if target:
dummy_pagename, dummy_target, targetpath = AttachFile._access_file(language_setup_page, request)
package = packages.ZipPackage(request, targetpath)
if package.isPackage():
if package.installPackage():
msg = _("Attachment '%(filename)s' installed.") % {'filename': target}
else:
msg = _("Installation of '%(filename)s' failed.") % {'filename': target}
else:
msg = _('The file %s is not a MoinMoin package file.') % target
data = TupleDataset()
data.columns = [
Column('page package', label=_('page package')),
Column('action', label=_('install')),
]
label_install = _("install")
for pageset_name in i18n.strings.pagesets:
attachment = "%s--%s.zip" % (lang, pageset_name)
# not_translated_system_pages are in english
if attachment.endswith(not_translated_system_pages):
attachment = 'English_not_translated_system_pages.zip'
install_link = ''
querystr = {'action': 'language_setup', 'target': attachment, 'language': lang}
if AttachFile.exists(request, language_setup_page, attachment):
install_link = request.page.link_to(request, label_install, querystr=querystr)
data.addRow((pageset_name, install_link))
table = DataBrowserWidget(request)
table.setData(data)
page_table = ''.join(table.format(method='GET'))
fmt = request.formatter
lang_links = [request.page.link_to_raw(request, _lang,
querystr={'action': 'language_setup',
'language': _lang,
'pageset': pageset_name, })
for _lang in wiki_languages]
lang_selector = u''.join([fmt.paragraph(1), _("Choose:"), ' ', ' '.join(lang_links), fmt.paragraph(0)])
title = _("Install language packs for '%s'") % wikiutil.escape(lang)
request.theme.add_msg(msg, "info")
request.theme.send_title(title, page=request.page, pagename=pagename)
request.write(request.formatter.startContent("content"))
request.write(lang_selector)
request.write(page_table)
request.write(request.formatter.endContent())
request.theme.send_footer(pagename)
request.theme.send_closing_html()
示例10: macro_FFImageChooser
# 需要导入模块: from MoinMoin.action import AttachFile [as 别名]
# 或者: from MoinMoin.action.AttachFile import _get_files [as 别名]
def macro_FFImageChooser(macro):
data_file = 'data.yml'
request = macro.request
formatter = macro.formatter
pagename = formatter.page.page_name
files = AttachFile._get_files(request, pagename)
attach_dir = AttachFile.getAttachDir(request, pagename)
# vendors
try:
data_idx = files.index(data_file)
except ValueError:
return "Konnte Dateianhang " + data_file + " nicht finden"
data = get_yaml(files[data_idx], attach_dir)
# output
ret = '<div class="download-form">'
for vendor in data['vendors']:
ret += '''
<input type="radio" name="vendor" class="vendor" id="vendor-%(id)s" />
<label for="vendor-%(id)s">%(name)s</label>
<div class="device-list">''' % vendor
for device in vendor['devices']:
extension = device['extension'] if 'extension' in device else 'bin'
ret += '<div class="device-wrap">'
if 'versions' in device:
ret += '''
<input type="radio" name="device" class="device" id="device-%(vendor_id)s-%(device_id)s" />
<label for="device-%(vendor_id)s-%(device_id)s">%(device_name)s</label>
<div class="version-list">
''' % {
'device_id': device['id'], 'device_name': device.get('name', device['id']),
'vendor_id': vendor['id']
}
for version in device['versions']:
ret += '''
<a class="version" href="https://dl.freifunk-kassel.de/images/%(chan)s/factory/gluon-ffks-%(rel)s-%(vendor)s-%(device)s-%(version)s.%(ext)s">
%(text)s
</a>''' % {
'chan': data['channel'], 'rel': data['release'], 'vendor': vendor['id'],
'device': device['id'], 'version': version['id'],
'text': version.get('name', version['id']), 'ext': extension
}
ret += '</div>'
else:
ret += '''
<a class="device" href="https://dl.freifunk-kassel.de/images/%(chan)s/factory/gluon-ffks-%(rel)s-%(vendor)s-%(device)s.%(ext)s">
%(text)s
</a>''' % {
'chan': data['channel'], 'rel': data['release'], 'vendor': vendor['id'],
'device': device['id'], 'text': device.get('name', device['id']),
'ext': extension
}
ret += '</div>'
ret += '</div>'
ret += '<script type="text/javascript" src="/wikistatic/ffks/js/firmware-dl.js"></script>'
return ret