当前位置: 首页>>代码示例>>Python>>正文


Python AttachFile.getAttachDir方法代码示例

本文整理汇总了Python中MoinMoin.action.AttachFile.getAttachDir方法的典型用法代码示例。如果您正苦于以下问题:Python AttachFile.getAttachDir方法的具体用法?Python AttachFile.getAttachDir怎么用?Python AttachFile.getAttachDir使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在MoinMoin.action.AttachFile的用法示例。


在下文中一共展示了AttachFile.getAttachDir方法的13个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: setup_class

# 需要导入模块: from MoinMoin.action import AttachFile [as 别名]
# 或者: from MoinMoin.action.AttachFile import getAttachDir [as 别名]
 def setup_class(self):
     request = self.request
     pagename = self.pagename
     become_trusted(request)
     self.page = create_page(request, pagename, u"Foo")
     AttachFile.getAttachDir(request, pagename)
     test_files = [
         ('test.ogg', 'vorbis'),
         ('test.svg', 'SVG'),
         ('test.mpg', 'MPG'),
         ('test.pdf', 'PDF'),
         ('test.mp3', 'MP3'),
     ]
     for filename, filecontent in test_files:
         AttachFile.add_attachment(request, pagename, filename, filecontent, overwrite=0)
开发者ID:Kartstig,项目名称:engineering-inventions-wiki,代码行数:17,代码来源:test_EmbedObject.py

示例2: copypage

# 需要导入模块: from MoinMoin.action import AttachFile [as 别名]
# 或者: from MoinMoin.action.AttachFile import getAttachDir [as 别名]
    def copypage(self, request, rootdir, pagename):
        """ quick and dirty! """
        pagedir = os.path.join(rootdir, 'pages', wikiutil.quoteWikinameFS(pagename))
        os.makedirs(pagedir)

        # write a "current" file with content "00000001"
        revstr = '%08d' % 1
        cf = os.path.join(pagedir, 'current')
        file(cf, 'w').write(revstr+'\n')

        # create a single revision 00000001
        revdir = os.path.join(pagedir, 'revisions')
        os.makedirs(revdir)
        tf = os.path.join(revdir, revstr)
        p = Page(request, pagename)
        text = p.get_raw_body().replace("\n", "\r\n")
        codecs.open(tf, 'wb', config.charset).write(text)

        source_dir = AttachFile.getAttachDir(request, pagename)
        if os.path.exists(source_dir):
            dest_dir = os.path.join(pagedir, "attachments")
            os.makedirs(dest_dir)
            for filename in os.listdir(source_dir):
                source_file = os.path.join(source_dir, filename)
                dest_file = os.path.join(dest_dir, filename)
                shutil.copyfile(source_file, dest_file)
开发者ID:Kartstig,项目名称:engineering-inventions-wiki,代码行数:28,代码来源:reducewiki.py

示例3: save

# 需要导入模块: from MoinMoin.action import AttachFile [as 别名]
# 或者: from MoinMoin.action.AttachFile import getAttachDir [as 别名]
    def save(self):
        request = self.request
        _ = request.getText

        if not wikiutil.checkTicket(request, request.args.get('ticket', '')):
            return _('Please use the interactive user interface to use action %(actionname)s!') % {'actionname': 'anywikidraw.save' }

        pagename = self.pagename
        target = self.target
        if not request.user.may.write(pagename):
            return _('You are not allowed to save a drawing on this page.')
        if not target:
            return _("Empty target name given.")

        file_upload = request.files.get('filepath')
        if not file_upload:
            # This might happen when trying to upload file names
            # with non-ascii characters on Safari.
            return _("No file content. Delete non ASCII characters from the file name and try again.")

        filename = request.form['filename']
        basepath, basename = os.path.split(filename)
        basename, ext = os.path.splitext(basename)

        ci = AttachFile.ContainerItem(request, pagename, target)
        filecontent = file_upload.stream
        content_length = None
        if ext == '.svg': # AnyWikiDraw POSTs this first
            AttachFile._addLogEntry(request, 'ATTDRW', pagename, target)
            ci.truncate()
            filecontent = filecontent.read() # read file completely into memory
            filecontent = filecontent.replace("\r", "")
        elif ext == '.map':
            # touch attachment directory to invalidate cache if new map is saved
            attach_dir = AttachFile.getAttachDir(request, pagename)
            os.utime(attach_dir, None)
            filecontent = filecontent.read() # read file completely into memory
            filecontent = filecontent.strip()
        else:
            #content_length = file_upload.content_length
            # XXX gives -1 for wsgiref :( If this is fixed, we could use the file obj,
            # without reading it into memory completely:
            filecontent = filecontent.read()

        if filecontent:
            ci.put('drawing' + ext, filecontent, content_length)
开发者ID:Glottotopia,项目名称:aagd,代码行数:48,代码来源:anywikidraw.py

示例4: get_attachment_dict

# 需要导入模块: from MoinMoin.action import AttachFile [as 别名]
# 或者: from MoinMoin.action.AttachFile import getAttachDir [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
开发者ID:130s,项目名称:roswiki,代码行数:20,代码来源:explorer.py

示例5: _attachment

# 需要导入模块: from MoinMoin.action import AttachFile [as 别名]
# 或者: from MoinMoin.action.AttachFile import getAttachDir [as 别名]
def _attachment(request, pagename, filename, outputdir, **kw):
	filename = filename.encode(config.charset)
	source_dir = AttachFile.getAttachDir(request, pagename)
	source_file = os.path.join(source_dir, filename)
	dest_dir = os.path.join(outputdir, "attachments", wikiutil.quoteWikinameFS(pagename))
	dest_file = os.path.join(dest_dir, filename)
	dest_url = "attachments/%s/%s" % (wikiutil.quoteWikinameFS(pagename), wikiutil.url_quote(filename))
	if os.access(source_file, os.R_OK):
		if not os.access(dest_dir, os.F_OK):
			try:
				os.makedirs(dest_dir)
			except:
				script.fatal("Cannot create attachment directory '%s'" % dest_dir)
		elif not os.path.isdir(dest_dir):
			script.fatal("'%s' is not a directory" % dest_dir)

		shutil.copyfile(source_file, dest_file)
		script.log('Writing "%s"...' % dest_url)
		return dest_url
	else:
		return ""
开发者ID:djwong,项目名称:rscds,代码行数:23,代码来源:frump.py

示例6: test_add_attachment_for_file_object

# 需要导入模块: from MoinMoin.action import AttachFile [as 别名]
# 或者: from MoinMoin.action.AttachFile import getAttachDir [as 别名]
    def test_add_attachment_for_file_object(self):
        """Test if add_attachment() works with file like object"""

        become_trusted(self.request)

        filename = "AutoCreatedSillyAttachment.png"

        create_page(self.request, self.pagename, u"FooBar!")
        data = "Test content"

        filecontent = StringIO.StringIO(data)

        AttachFile.add_attachment(self.request, self.pagename, filename, filecontent, True)
        exists = AttachFile.exists(self.request, self.pagename, filename)
        path = AttachFile.getAttachDir(self.request, self.pagename)
        imagef = os.path.join(path, filename)
        file_size = os.path.getsize(imagef)

        nuke_page(self.request, self.pagename)

        assert exists and file_size == len(data)
开发者ID:steveyen,项目名称:moingo,代码行数:23,代码来源:test_attachfile.py

示例7: wikirepl

# 需要导入模块: from MoinMoin.action import AttachFile [as 别名]
# 或者: from MoinMoin.action.AttachFile import getAttachDir [as 别名]
    def wikirepl(self, match):
        url = match.group('url')

        if not url.startswith('attachment:'):
           return match.group()

        url = url[11:]

        attname=wikiutil.taintfilename(self.formatter.text(url))
        current_pagename=self.formatter.page.page_name
        attachment_path = os.path.join(AttachFile.getAttachDir(self.request,current_pagename), attname)
        if not os.path.exists(attachment_path):
            import urllib
            linktext = self.request.getText('Upload new attachment "%(filename)s"')
            return  wikiutil.link_tag(self.request,
                                      '%s?action=AttachFile&rename=%s' %
                                      (current_pagename,
                                      urllib.quote_plus(attname)),
                                      linktext % {'filename': attname})

        return ( match.group('pre') +
            AttachFile.getAttachUrl(current_pagename,attname,self.request) +
            match.group('suf'))
开发者ID:blopesvieira,项目名称:MoinMoin-Parser-BibTeX2,代码行数:25,代码来源:bibtex.py

示例8: get

# 需要导入模块: from MoinMoin.action import AttachFile [as 别名]
# 或者: from MoinMoin.action.AttachFile import getAttachDir [as 别名]
    def get(self, formatter, inputtex, prologue, para=False):
        if not self.request.latex_cleanup_done.has_key(formatter.page.page_name):
            self.request.latex_cleanup_done[formatter.page.page_name] = True
            self.cleanup(formatter.page.page_name)
            
        if len(inputtex) == 0: return ''

        if callable(getattr(formatter, 'johill_sidecall_emit_latex', None)):
          return formatter.johill_sidecall_emit_latex(inputtex)

        extra_preamble = ''
        preamble_page = self.request.pragma.get('latex_preamble', None)
        if preamble_page is not None:
          extra_preamble = Page(self.request, preamble_page).get_raw_body()
        extra_preamble = re.sub(re.compile('^#'), '%', extra_preamble)

        tex = latex_template % { 'raw': inputtex, 'prologue': extra_preamble + prologue }
        enctex = tex.encode('utf-8')
        fn = latex_name_template % sha.new(enctex).hexdigest()
        
        attachdir = AttachFile.getAttachDir(self.request, formatter.page.page_name, create=1)
        dst = "%s/%s%%d.png" % (attachdir, fn)
        if not os.access(dst % 1, os.R_OK):
          tmpdir = tempfile.mkdtemp()
          try:
              data = open("%s/%s.tex" % (tmpdir, fn), "w")
              data.write(enctex)
              data.close()
              args = list(latex_args)
              args[-1] = args[-1] % fn
              res = call_command_in_dir(latex, args, tmpdir)
              if not res is None:
                  return formatter.preformatted(1)+formatter.text('latex'+res)+formatter.preformatted(0)
              args = list(dvipng_args)
              args[-1] = args[-1] % fn
              res = call_command_in_dir(dvipng, args, tmpdir)
              if not res is None:
                  return formatter.preformatted(1)+formatter.text('dvipng'+res)+formatter.preformatted(0)

              page = 1
              while os.access("%s/%s%d.png" % (tmpdir, fn, page), os.R_OK):
                  shutil.copyfile ("%s/%s%d.png" % (tmpdir, fn, page), dst % page)
                  page += 1
            
          finally:
              for root,dirs,files in os.walk(tmpdir, topdown=False):
                  for name in files:
                      os.remove(os.path.join(root,name))
                  for name in dirs:
                      os.rmdir(os.path.join(root,name))
              os.rmdir(tmpdir)

        result = ""
        page = 1
        loop = False
        for match in anchor.finditer(inputtex):
            result += formatter.anchordef(match.group(1))
        for match in anchor.finditer(prologue):
            result += formatter.anchordef(match.group(1))
        while os.access(dst % page, os.R_OK):
            url = AttachFile.getAttachUrl(formatter.page.page_name, fn+"%d.png" % page, self.request)
            if loop:
                result += formatter.linebreak(0)+formatter.linebreak(0)
            if para:
                result += formatter.paragraph(1)
            result += formatter.image(src="%s" % url, alt=inputtex, title=inputtex, align="absmiddle")
            if para:
                result += formatter.paragraph(0)
            page += 1
            loop = True
        return result
开发者ID:miguelmarco,项目名称:sage-wiki,代码行数:73,代码来源:latex.py

示例9: cleanup

# 需要导入模块: from MoinMoin.action import AttachFile [as 别名]
# 或者: from MoinMoin.action.AttachFile import getAttachDir [as 别名]
 def cleanup(self, pagename):
     attachdir = AttachFile.getAttachDir(self.request, pagename, create=1)
     for f in os.listdir(attachdir):
         if not latex_attachment.match(f) is None:
             os.remove("%s/%s" % (attachdir, f))
开发者ID:miguelmarco,项目名称:sage-wiki,代码行数:7,代码来源:latex.py

示例10: history

# 需要导入模块: from MoinMoin.action import AttachFile [as 别名]
# 或者: from MoinMoin.action.AttachFile import getAttachDir [as 别名]
    def history(page, pagename, request):
        # show history as default
        _ = request.getText

        # open log for this page
        from MoinMoin.logfile import editlog
        from MoinMoin.util.dataset import TupleDataset, Column

        history = TupleDataset()
        history.columns = [
            Column('rev', label='#', align='right'),
            Column('mtime', label=_('Date'), align='right'),
            Column('size',  label=_('Size'), align='right'),
            Column('diff', label='<input type="submit"           value="%s">' % (_("Diff"))),
            # TODO: translate to English
            # entfernt, nicht 4.01 compliant:          href="%s"   % page.url(request)
            Column('editor', label=_('Editor'), hidden=not request.cfg.show_hosts),
            Column('comment', label=_('Comment')),
            Column('action', label=_('Action')),
            ]

        # generate history list
        revisions = page.getRevList()
        versions = len(revisions)

        may_revert = request.user.may.revert(pagename)
        
        # read in the complete log of this page
        log = editlog.EditLog(request, rootpagename=pagename)
        count = 0
        for line in log.reverse():
            rev = int(line.rev)
            actions = ""
            if line.action in ['SAVE','SAVENEW','SAVE/REVERT',]:
                if count == 0: # latest page
                    actions = '%s&nbsp;%s' % (actions, page.link_to(request,
                        text=_('view'),
                        querystr=''))
                    actions = '%s&nbsp;%s' % (actions, page.link_to(request,
                        text=_('raw'),
                        querystr='action=raw'))
                    actions = '%s&nbsp;%s' % (actions, page.link_to(request,
                        text=_('print'),
                        querystr='action=print'))
                else:
                    actions = '%s&nbsp;%s' % (actions, page.link_to(request,
                        text=_('view'),
                        querystr='action=recall&rev=%d' % rev))
                    actions = '%s&nbsp;%s' % (actions, page.link_to(request,
                        text=_('raw'),
                        querystr='action=raw&rev=%d' % rev))
                    actions = '%s&nbsp;%s' % (actions, page.link_to(request,
                        text=_('print'),
                        querystr='action=print&rev=%d' % rev))
                    if may_revert:
                        actions = '%s&nbsp;%s' % (actions, page.link_to(request,
                            text=_('revert'),
                            querystr='action=revert&rev=%d' % (rev,)))
                if count == 0:
                    rchecked=' checked="checked"'
                    lchecked = ''
                elif count == 1:
                    lchecked=' checked="checked"'
                    rchecked = ''
                else:
                    lchecked = rchecked = ''
                diff = '<input type="radio" name="rev1" value="%d"%s><input type="radio" name="rev2" value="%d"%s>' % (rev,lchecked,rev,rchecked)
      
                comment = line.comment
                if not comment and line.action.find('/REVERT') != -1:
                        comment = _("Revert to revision %(rev)d.") % {'rev': int(line.extra)}
                size = page.size(rev=rev)
            else: # ATT*
                rev = '-'
                diff = '-'
                filename = line.extra
                comment = "%s: %s %s" % (line.action, filename, line.comment)
                size = 0
                if line.action != 'ATTDEL':
                    from MoinMoin.action import AttachFile
                    page_dir = AttachFile.getAttachDir(request, pagename)
                    filepath = os.path.join(page_dir, filename)
                    try:
                        # FIXME, wrong path on non-std names
                        size = os.path.getsize(filepath)
                    except:
                        pass
                    if line.action == 'ATTNEW':
                        actions = '%s&nbsp;%s' % (actions, page.link_to(request,
                            text=_('view'),
                            querystr='action=AttachFile&do=view&target=%s' % filename))
                    elif line.action == 'ATTDRW':
                        actions = '%s&nbsp;%s' % (actions, page.link_to(request,
                            text=_('edit'),
                            querystr='action=AttachFile&drawing=%s' % filename.replace(".draw","")))

                    actions = '%s&nbsp;%s' % (actions, page.link_to(request,
                        text=_('get'),
                        querystr='action=AttachFile&do=get&target=%s' % filename))
                    actions = '%s&nbsp;%s' % (actions, page.link_to(request,
#.........这里部分代码省略.........
开发者ID:mikejamesthompson,项目名称:orgsites,代码行数:103,代码来源:wikiaction.py

示例11: format

# 需要导入模块: from MoinMoin.action import AttachFile [as 别名]
# 或者: from MoinMoin.action.AttachFile import getAttachDir [as 别名]

#.........这里部分代码省略.........
            except StandardError:
                color = 'black'
        else:
            color = 'black'

        if self.background != 'transparent':
            try:
                background = web.Color(str(self.background))
            except StandardError:
                background = 'transparent'
        else:
            background = 'transparent'

        if self.width:
            units = ['%']
            width = self.value_check(self.width, units, 1, 0)
          
        if self.padding:
            units = ['pt', 'pc', 'in', 'mm', 'cm', 'px', 'em', 'ex']
            padding = self.value_check(self.padding, units, 4, 0)

        if self.margin:
            units = ['pt', 'pc', 'in', 'mm', 'cm', 'px', 'em', 'ex']
            margin = self.value_check(self.margin, units, 4, 0)

        if self.text_font_size in ['xx-small', 'x-small', 'small', 'medium', 'large', 'x-large', 'xx-large',
                                   'smaller', 'larger']:
            text_font_size = self.text_font_size
        else:
            units = ['pt', 'pc', 'in', 'mm', 'cm', 'px', 'em', 'ex', '%']
            text_font_size = self.value_check(self.text_font_size, units, 1, '')

        if self.text_color != 'transparent':
            try:
                text_color = web.Color(str(self.text_color))
            except StandardError:
                text_color = 'black'
        else:
            text_color = 'black'

        url = ''
        if self.background_image != None:
            attachment_path = AttachFile.getAttachDir(self.request, pagename)
            file = os.path.join(attachment_path, self.background_image)
            if os.path.exists(file):
                mime_type, enc = mimetypes.guess_type(file)
                if mime_type.startswith('image'):
                    url = AttachFile.getAttachUrl(pagename, self.background_image, self.request)

        if self.background_repeat in ['repeat', 'repeat-x', 'repeat-y', 'no-repeat']:
            background_repeat = self.background_repeat
        else:
            background_repeat = 'no-repeat'

        if self.align in ['left', 'right', 'center', 'justify']:
            div = '<div align="%(align)s" style="border-width:%(thick)s; border-color:%(color)s; border-style:%(style)s; position:%(position)s; padding:%(padding)s; margin:%(margin)s; background-color:%(background)s; font-size:%(text_font_size)s; color:%(text_color)s; background-image:url(%(background_image)s); background-repeat:%(background_repeat)s;" width="%(width)s">' % {
                    "thick": thick,
                    "style": style,
                    "color": color,
                    "position": position,
                    "padding": padding,
                    "margin": margin,
                    "background": background,
                    "width": width,
                    "text_align": text_align,
                    "text_font_size": text_font_size,
                    "text_color": text_color,
                    "background_image": url,
                    "background_repeat": background_repeat,
                    "align": self.align,
                    }
            self.request.write("%(div)s%(result)s</div>" % {
                 "div": div,
                 "result": result})

        if self.align in ['float:left', 'float:right']:
            tab = '<table style="%(align)s; font-size:%(text_font_size)s; color:%(text_color)s; text-align:%(text_align)s; background-image:url(%(background_image)s); background-repeat:%(background_repeat)s; position:%(position)s; padding:%(padding)s; margin:%(margin)s;" width="%(width)s" border="%(thick)s" bgcolor="%(background)s"><tbody><tr><td style="border-style:none;">' % {
                    "align": self.align,
                    "text_font_size": text_font_size,
                    "text_align": text_align,
                    "text_color": text_color,
                    "position": position,
                    "padding": padding,  
                    "margin": margin,
                    "width": width,
                    "thick": thick,
                    "background": background,
                    "background_image": url,
                    "background_repeat": background_repeat,
                }
            self.request.write("%(tab)s%(result)s</td></tr></tbody></table>" % {
                               "tab": tab,
                               "result": result})

        if self.align in ['clear:both', 'clear:left', 'clear:right']:
            self.request.write('<br style=%(align)s;>' % {"align": self.align})


        if self.align == 'clear':
            self.request.write('<br style="clear:both;">')
开发者ID:130s,项目名称:roswiki,代码行数:104,代码来源:frame.py

示例12: macro_FFImageChooser

# 需要导入模块: from MoinMoin.action import AttachFile [as 别名]
# 或者: from MoinMoin.action.AttachFile import getAttachDir [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
开发者ID:freifunkks,项目名称:moinmoin-plugins,代码行数:65,代码来源:FFImageChooser.py

示例13: handle_request

# 需要导入模块: from MoinMoin.action import AttachFile [as 别名]
# 或者: from MoinMoin.action.AttachFile import getAttachDir [as 别名]
	def handle_request(self):
		wiki_page_base = Page(self.request, _wiki_base)
		wiki_page_config = Page(self.request, _wiki_base+'/Config')
		form = self.request.form
		
		#=== Sanity checks: Create required pages if not exist, check if oauth config works ===
		
		#create _wiki_base page, if not exists
		if not Page(self.request, _wiki_base).exists():
			try:
				self.create_default_wikibase_page()
			except Exception as e:
				self.request.theme.add_msg('Could not create page "'+_wiki_base+'": '+pformat(e), 'error')
				Page(self.request, self.pagename).send_page()
				return
		#create Template page, if not exists
		if not Page(self.request, _wiki_base+'/Template').exists():
			try:
				self.create_default_wikitemplate_page()
			except Exception as e:
				self.request.theme.add_msg('Could not create page "'+_wiki_base+'/Template'+'": '+pformat(e), 'error')
				Page(self.request, self.pagename).send_page()
				return
		if wiki_page_config.exists():
			#parse config page and put as dict into self.config
			self.read_config(wiki_page_config)
		else:
			#create Log page, if not exists
			try:
				if not Page(self.request, _wiki_base+'/Log').exists():
					self.create_default_wikilog_page()
			except Exception as e:
				self.request.theme.add_msg('Could not create page "'+_wiki_base+'/Log": '+pformat(e), 'error')
				Page(self.request, self.pagename).send_page()
				return
			#create Config page, if not exists
			try:
				self.create_default_config_page()
			except Exception as e:
				self.request.theme.add_msg('Could not create page "'+_wiki_base+'/Config'+'": '+pformat(e), 'error')
				Page(self.request, self.pagename).send_page()
				return
			
			self.request.theme.add_msg('Welcome to Mendeley2Moin. Pages needed for this plugin have been created.', 'info')
			Page(self.request, _wiki_base+'/Log').send_page()
			return
		
		#Create MendeleyImporter instance and try to login using consumer/secret key and the file with authenticated tokens
		self.mendeley_importer = MendeleyImporter(self.config['consumer_key'], self.config['secret_key'])
		#Check if the user submitted the OAuth verifier
		if self.request.values.has_key('submitVerifier'):
			#parse serialized token and verifier
			try:
				self.mendeley_importer.set_verified_token(self.request.values['token'], self.request.values['verifier'])
			except ValueError as e:
				self.request.theme.add_msg('Could not authenticate tokens: '+pformat(e), 'error')
				Page(self.request, _wiki_base+'/Log').send_page()
				return
			#save tokens as pickled file as attachment to Config page
			self.mendeley_importer.save_keys(AttachFile.getAttachDir(self.request, _wiki_base+'/Config'))
			self.prepend_to_wiki_page(_wiki_base+'/Log', 'OAuth configuration completed', \
				'Access tokens have been saved [[attachment:%s/Config/mendeley_api_keys.pkl | here]]. Click here to run the plugin: [[/|Mendeley2Moin|&action=Mendeley2Moin]]\n'+\
				'\n(Or go to Mendeley2Moin overview page.)\n' % (_wiki_base))
			self.request.theme.add_msg('Tokens verified.' % (wikiutil.escape(self.mendeley_importer.mendeley.request_token)), 'info')
			Page(self.request, _wiki_base+'/Log').send_page()
			return
		#Try to read file with authenticated tokens. They are supposed to be an attachment of the Config page
		attachment = u'mendeley_api_keys.pkl'
		if not AttachFile.exists(self.request, _wiki_base+'/Config', attachment):
			#If file with authenticated tokens does not exist, request URL and write it as Log message to the user
			try:
				auth_url = self.mendeley_importer.get_auth_url()
			except Exception as e:
				self.request.theme.add_msg('Could not request OAuth URL: '+pformat(e), 'error')
				wiki_page_base.send_page()
				return
			self.request.theme.add_msg('Register token on: '+auth_url, 'info')
			try:
				self.prepend_to_wiki_page(_wiki_base+'/Log', 'Step two: Register your OAuth token on mendeley.com', """\
 * If you have a backup of the file {{{mendeley_api_keys.pkl}}}, upload it here [[attachment:%s/Config/mendeley_api_keys.pkl]].
 * Otherwise [[%s|click here]] to register your token on mendeley.com. Then enter the verification code here: 
{{{#!html 
<form action="submit" method="GET">
<input type="hidden" name="action" value="Mendeley2Moin" />
<input type="hidden" name="token" value="%s" />
<input type="text" name="verifier" value="" size="36" />
<input type="submit" name="submitVerifier" value="Submit" />
</form>
}}}
""" % (_wiki_base, auth_url, wikiutil.escape(self.mendeley_importer.mendeley.request_token.to_string())))
			except Exception as e:
				self.request.theme.add_msg('Could not edit page "'+_wiki_base+'/Log": '+pformat(e), 'error')
				Page(self.request, self.pagename).send_page()
				return
			Page(self.request, _wiki_base+'/Log').send_page()
			return
		
		#Get path of file with authenticated tokens and load it.
		self.config['api_keys_pkl_dir'] = AttachFile.getAttachDir(self.request, _wiki_base+'/Config')
		try:
#.........这里部分代码省略.........
开发者ID:rfunke,项目名称:Mendeley2Moin,代码行数:103,代码来源:Mendeley2Moin.py


注:本文中的MoinMoin.action.AttachFile.getAttachDir方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。