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


Python flask.Markup类代码示例

本文整理汇总了Python中flask.Markup的典型用法代码示例。如果您正苦于以下问题:Python Markup类的具体用法?Python Markup怎么用?Python Markup使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。


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

示例1: pretty

def pretty(value):
    if isinstance(value, dict):
        page = markup.page()
        page.ul(_class='dict')
        for k, v in value.items():
            if isinstance(v, list) and v:
                pretty_value = Markup.escape(', '.join(v))
            elif isinstance(v, dict) and v:
                subul = markup.page()
                subul.ul(_class='subdict')
                for subk, subv in v.items():
                    subul.li()
                    subul.span('%s: ' % subk)
                    subul.span(Markup.escape(subv))
                    subul.li.close()
                subul.ul.close()
                pretty_value = subul()
            elif v:
                pretty_value = Markup.escape(v)
            else:
                continue
            page.li()
            page.span('%s:' % k.capitalize().replace('_', ' '))
            page.span(pretty_value)
            page.li.close()
        page.ul.close()
        return page()
    elif isinstance(value, list):
        return Markup.escape(', '.join(value))
    else:
        page = markup.page()
        page.span(Markup.escape(value), _class='simple')
        return page()
开发者ID:eea,项目名称:eea.sanap,代码行数:33,代码来源:utils.py

示例2: slugify

def slugify(value, substitutions=()):
    '''
    Normalizes string, converts to lowercase, removes non-alpha characters,
    and converts spaces to hyphens.

    Took from Django sources.
    '''
    # TODO Maybe steal again from current Django 1.5dev
    value = Markup(value).striptags()
    # value must be unicode per se
    import unicodedata
    from unidecode import unidecode
    # unidecode returns str in Py2 and 3, so in Py2 we have to make
    # it unicode again
    value = unidecode(value)
    if isinstance(value, six.binary_type):
        value = value.decode('ascii')
    # still unicode
    value = unicodedata.normalize('NFKD', value).lower()
    for src, dst in substitutions:
        value = value.replace(src.lower(), dst.lower())
    value = re.sub('[^\w\s-]', '', value).strip()
    value = re.sub('[-\s]+', '-', value)
    # we want only ASCII chars
    value = value.encode('ascii', 'ignore')
    # but Pelican should generally use only unicode
    return value.decode('ascii')
开发者ID:joehand,项目名称:pdx_ulti,代码行数:27,代码来源:utils.py

示例3: lists_edit

def lists_edit(name=None):
	if 'username' not in session: return goto_login(fname(), fparms())
	action = 'delete' if request.args.get('action', request.form.get('action')) == 'delete' else 'add'
	item = request.args.get('item', request.form.get('item'))
	if not name or not action or not item:
		return redirect(url_for('lists'))
	listname = getattr(userlists, name).printedname
	if request.method == 'POST':
		if name == 'whitelist':
			restartstring = '<span class="halflink" onclick="document.getElementById(\'restartform\').submit();">Restart</span> the server to apply your changes.'
		else:
			restartstring = ''
		if action == 'add':
			if getattr(userlists, name).add(item):
				flash('<i>%s</i> added to %s. %s' % (Markup.escape(item), listname, restartstring), 'success')
			else:
				flash('<i>%s</i> is already in %s.' % (Markup.escape(item), listname), 'info')
		elif action == 'delete':
			if getattr(userlists, name).remove(item):
				flash('<i>%s</i> deleted from %s. %s' % (Markup.escape(item), listname, restartstring), 'success')
			else:
				flash('<i>%s</i> is not in %s.' % (Markup.escape(item), listname), 'info')
		returnpage = request.form.get('returnpage', 'lists')
		return redirect(url_for(returnpage, username=item))
	return render_template('lists_delete.html', navigation=get_navi('lists'), name=name, action=action, item=item, listname=listname)
开发者ID:asdil12,项目名称:mcweb,代码行数:25,代码来源:application.py

示例4: new_announcement

def new_announcement():
    """Create new announcement."""
    def respond():
        response = dict(template='admin/new_announcement.html',
                        title=gettext("Write a new post"),
                        form=form)
        return handle_content_type(response)

    form = AnnouncementForm()
    del form.id

    # project_sanitized, owner_sanitized = sanitize_project_owner(project, owner, current_user)

    if request.method != 'POST':
        ensure_authorized_to('create', Announcement())
        return respond()

    if not form.validate():
        flash(gettext('Please correct the errors'), 'error')
        return respond()

    announcement = Announcement(title=form.title.data,
                                body=form.body.data,
                                published=form.published.data,
                                media_url=form.media_url.data,
                                user_id=current_user.id)
    ensure_authorized_to('create', announcement)
    announcement_repo.save(announcement)

    msg_1 = gettext('Annnouncement created!')
    markup = Markup('<i class="icon-ok"></i> {}')
    flash(markup.format(msg_1), 'success')

    return redirect_content_type(url_for('admin.announcement'))
开发者ID:fiorda,项目名称:pybossa,代码行数:34,代码来源:admin.py

示例5: get_killmail_descriptions

def get_killmail_descriptions():
    description = Markup(u"Acceptable Killmail Links:<ul>")
    desc_entry = Markup(u"<li>{}</li>")
    killmail_descs = [desc_entry.format(km.description) for km in\
            current_app.killmail_sources]
    description += Markup(u"").join(killmail_descs)
    description += Markup(u"</ul>")
    return description
开发者ID:boweiliu,项目名称:evesrp,代码行数:8,代码来源:requests.py

示例6: _format_attrs

def _format_attrs(attrs, escape_attrs=True):
    out = []
    for name, value in sorted(attrs.items()):
        if escape_attrs:
            name = Markup.escape(name)
            value = Markup.escape(value)
        out.append(' {name}="{value}"'.format(name=name, value=value))
    return ''.join(out)
开发者ID:plumdog,项目名称:flask_table,代码行数:8,代码来源:html.py

示例7: index

def index():
        li = Markup("""<li><a href="{}">{}</a></li>""")
        results = db.metadata.tables.keys()
        results.sort()
        results = [li.format(url_for("app.view_table", table_name=tbl_name), tbl_name) for tbl_name in results]

        results = Markup("<ul>") + Markup("\n").join(results) + Markup("</ul>")

        return render_template("layout.html", content=results)
开发者ID:blighli,项目名称:Budget-Manager,代码行数:9,代码来源:index.py

示例8: generate_links

 def generate_links(query_list, model=None, model_key=None):
     link = Markup("""<a href="{}">{}</a> - <a href="{}">Delete</a>""")
     model_key = [key.key for key in model_key.columns][0]
     for entry in query_list:
         key = getattr(entry, model_key, 1)
         name = model.__name__
         edit_url = url_for('admin.edit', model_name=name, model_url_key=key)
         delete_url = url_for('admin.delete', model_name=name, model_url_key=key)
         yield link.format(edit_url, entry, delete_url)
开发者ID:blighli,项目名称:Budget-Manager,代码行数:9,代码来源:search.py

示例9: extension_filename

def extension_filename(filename,ext):
    '''
    Añade la extension al nombre de archivo
    '''
    fn = Markup(filename).striptags()[:512]
    #si la extension no viene en el nombre se añade
    if ext and not fn.lower().endswith("."+ext.lower()):
        fn = fn+"."+ext
    return fn
开发者ID:Hermy,项目名称:foofind-web,代码行数:9,代码来源:helpers.py

示例10: safe_non_valid_input_error

def safe_non_valid_input_error(user_input,field_name):
    r"""
    Returns a formatted error message where all non-fixed parameters
    (in particular user input) is escaped.
    """
    msg  = Markup("Error: <span style='color:black'>")+Markup.escape(user_input)
    msg += Markup("</span>")
    msg += Markup(" is not a valid input for <span style='color:black'>")
    msg += Markup.escape(field_name)+Markup("</span>")
    return msg
开发者ID:kedlaya,项目名称:lmfdb,代码行数:10,代码来源:emf_utils.py

示例11: test_permissions_custom_word

def test_permissions_custom_word():
  title = 'Testing custom permission, the word should be "yep"'
  data = {
    "app.access('test_permission_word')": app.access('test_permission_word'),
    "app.access('test_permission_word', word='qwer')": app.access('test_permission_word', word='qwer'),
    "app.access('test_permission_word', word='yep')": app.access('test_permission_word', word='yep')
  }
  data = Markup('<br/>').join(["%s: %s" % (k,v) for k,v in data.items()])
  
  return render_template( 'test/index.html', title=title, data=data )
开发者ID:timur-glushan,项目名称:tt,代码行数:10,代码来源:permissions.py

示例12: delete_announcement

def delete_announcement(id):
    announcement = announcement_repo.get_by(id=id)
    if announcement is None:
        raise abort(404)

    ensure_authorized_to('delete', announcement)
    announcement_repo.delete(announcement)
    msg_1 = gettext('Announcement deleted!')
    markup = Markup('<i class="icon-ok"></i> {}')
    flash(markup.format(msg_1), 'success')
    return redirect_content_type(url_for('admin.announcement'))
开发者ID:fiorda,项目名称:pybossa,代码行数:11,代码来源:admin.py

示例13: play

def play():
    logged = False
    user_log = ''
    if (session):
        if 'logged_in' not in session:
            return redirect(url_for('login'))
        else:
            if session['logged_in']:
                logged = True
                user_log = Markup('<a class="nav-link" href="/profile"> Hello, {0} </a>'.format(session['user_name']))
            else:
                return redirect(url_for('login'))
    else:
        return redirect(url_for('login'))

    difficulty = request.args.get("diff")
    song_id = request.args.get("sg")
    if not song_id or not difficulty:
        # display error page
        pass
    song = get_song_details(song_id)
    word_list = get_words_to_hide(song_id, int(difficulty))
    song_tags = get_tags_for_song(song_id)
    lyrics = song.lyrics.replace('\n', '<br>')
    html_to_replace = Markup('<div class="form-group"> \
                                <div class="input-group"> \
                                    <input type="text" id="{0}" class="missing-word form-control" size="{1}" maxlength="{1}" data-word="{3}"> \
                                    <span class="glyphicon glyphicon-eye-open input-group-addon" data-toggle="tooltip" data-placement="bottom" aria-hidden="true" title="{2}"> \
                                          </span> \
                                </div> \
                      </div>')
    i = 0
    for word in word_list:
        hint = get_hint_for_word(word, int(difficulty))
        lyrics, k = re.subn(r'\s({0})\s'.format(word),
                            html_to_replace.format("word-{0}".format(i), len(word) + 1, hint, word),
                            lyrics, count=max([1, int(difficulty) - 1]))
        i += k

    m, s = divmod(int(song.length), 60)
    song_duration = "%02d:%02d" % (m, s)
    video_url = song.video_url[song.video_url.index('v=') + 2:]
    keep_ids, _ = get_user_keep(session['user_id'])
    keep_next = get_next_keep(session['user_id'], song_id)
    keep_count = get_keep_count_for_song(song_id)
    play_count = get_play_count_for_song(song_id)

    return render_template('play.html', logged_in=logged, profile_login=user_log, user_id=session['user_id'],
                           song_id=song_id, lyrics=lyrics,
                           song_tags=song_tags, song_artist=song.artist,
                           song_title=song.title, release_year=song.release_year, song_duration=song_duration,
                           video_url=video_url, num_of_words=i, difficulty=int(difficulty),
                           keep_ids=keep_ids, keep_next=keep_next, keep_count=keep_count, play_count=play_count)
开发者ID:yotamsch,项目名称:portfolio,代码行数:53,代码来源:app.py

示例14: add_new_language

def add_new_language():
    user = fetch_id_from_userid(current_user.id)
    bcp = request.args.get('bcp', None)
    bcp = str(Markup.escape(bcp))
    iso = request.args.get('iso', None)
    iso = str(Markup.escape(iso))
    name = request.args.get('name', None)
    name = str(Markup.escape(name))
    if bcp and name:
        dbinsert = insert_new_language(bcp, iso, name, user)
        return jsonify(result=dbinsert)
    else:
        return jsonify(result=False)
开发者ID:globalwordnet,项目名称:OMW,代码行数:13,代码来源:__init__.py

示例15: handle_starttag

 def handle_starttag(self, tag, attrs):
     self.container.append("<%s>" % tag)
     attrs_string = ''
     if attrs:
         for attr in attrs:
             str = '%s="%s" ' % (attr[0], attr[1])
             attrs_string = attrs_string + str
         if attrs_string and attrs_string[-1] == " ":
             attrs_string = attrs_string[:-1]
         tag_string =  Markup.escape('<%s %s>' % (tag, attrs_string))
     else:
         tag_string = Markup.escape('<%s>' % tag)
     self.div_wrap = self.div_wrap + Markup('<span class="slack-%s">' % tag) + \
                     tag_string + Markup('</span>')
开发者ID:terrrydactyl,项目名称:slack,代码行数:14,代码来源:slack.py


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