def format_message_explicit_emotes(message, emotes, size="1.0"): if not emotes: return Markup(urlize(message).replace('<a ', '<a target="_blank" ')) # emotes format is # <emoteid>:<start>-<end>[,<start>-<end>,...][/<emoteid>:<start>-<end>,.../...] # eg: # 123:0-2/456:3-6,7-10 # means that chars 0-2 (inclusive, 0-based) are emote 123, # and chars 3-6 and 7-10 are two copies of emote 456 parsed_emotes = [] for emote in emotes.split('/'): emoteid, positions = emote.split(':') emoteid = int(emoteid) for position in positions.split(','): start, end = position.split('-') start = int(start) end = int(end) + 1 # make it left-inclusive, to be more consistent with how Python does things parsed_emotes.append((start, end, emoteid)) parsed_emotes.sort(key=lambda x:x[0]) bits = [] prev = 0 for start, end, emoteid in parsed_emotes: if prev < start: bits.append(urlize(message[prev:start]).replace('<a ', '<a target="_blank" ')) url = escape("http://static-cdn.jtvnw.net/emoticons/v1/%d/%s" % (emoteid, size)) command = escape(message[start:end]) bits.append('<img src="%s" alt="%s" title="%s">' % (url, command, command)) prev = end if prev < len(message): bits.append(urlize(message[prev:]).replace('<a ', '<a target="_blank" ')) return Markup(''.join(bits))
def csv_to_Qhtml(parea): """ Open a .csv file and return it in HTML format. :param filepath: Filepath to a .csv file to be read. :return: String of HTML to be published. """ filepath = "INPUT/pdq.csv" pd.set_option('display.max_colwidth', None) df = pd.read_csv(filepath, index_col=0, engine='python') df = df[parea].to_frame() qtext = str(df[parea].iloc[0]) df.drop(df.index[0], inplace=True) df.rename(columns={parea: 'Response'}, inplace=True) #df['Response'] = df['Response'].str.encode('utf-8', 'ignore').str.decode('utf-8') df['Response'] = df['Response'].apply( lambda x: urlize(x, 40, target='_blank')) html = df.to_html(index_names=False, classes=['table-striped', 'table-bordered'], escape=False, table_id="Qtable").replace("\\n", "<br>").replace( "\\t", " ").replace("\\r", "") Qhtml = [qtext, html] return Qhtml
def line_as_html(message): """Given a *message* containing mIRC formatting codes, return an HTML rendering.""" html = '' style = dict() matches = FORMATTING_BOUNDARIES.finditer(message) for first, second in _pairwise(matches): control_code = first.group(0)[:1] if control_code == '\x02': _toggle(style, 'font-weight', 'bold') elif control_code == '\x03': if first.group(1): style['color'] = mirc_color(first.group(1)) if first.group(2): style['background-color'] = mirc_color(first.group(2)) else: style.pop('color', None) style.pop('background-color', None) elif control_code == '\x0F': style.clear() elif control_code == '\x16': _toggle(style, 'font-style', 'italic') elif control_code == '\x1F': _toggle(style, 'text-decoration', 'underline') text = urlize(message[first.end():second.start()]) if text: # Don't output empty <span> tags. if style: css = '; '.join('{}: {}'.format(k, v) for k, v in sorted(style.items())) html += '<span style="{}">{}</span>'.format(css, text) else: html += text return html
def update_book(): book_id = escape(request.form.get('book_id', '')) edit_title = escape(request.form.get('edit_title', '')) edit_desc = escape(request.form.get('edit_desc', '')) if book_id and edit_title and edit_desc: if request.is_xhr: #update the book informations and return html g.db.execute('update books SET title = ?, description = ? WHERE rowid = ?', (edit_title, edit_desc, int(book_id))) g.db.commit() book = g.db.execute('select * from books where id = ?', [int(book_id)]).fetchone() g.db.commit() html = book_html % ( 'finished' if book[3] else 'reading', #book could be finished book[0], #id book[1], #title urlize(book[2]), #desc datetimeformat(convert_date(book[4])), book[0], book[1], book[2], ) return jsonify(success=True, html=html) else: return u"XHR requests only." else: return jsonify(error=u"Missing all the stuffs.")
def add_event(event): event['text'] = cgi.escape(event['title']) event['description'] = urlize(event['description']) event['start_date'] = event['start_date'].strftime('%Y-%m-%d %H:%M:00') event['end_date'] = event['end_date'].strftime('%Y-%m-%d %H:%M:00') event['venue'] = slugify(event['venue']) return event
def add_event(event): event["text"] = html.escape(event["title"]) event["description"] = urlize(event["description"]) event["start_date"] = event["start_date"].strftime("%Y-%m-%d %H:%M:00") event["end_date"] = event["end_date"].strftime("%Y-%m-%d %H:%M:00") event["venue"] = slugify(event["venue"]) return event
def get_nl2br(value, make_urls=True): """ Splits the provided string into paragraph tags based on the line breaks within it and returns the escaped result. Args: value: The string to process. make_urls: If True, will attempt to convert any URLs in the string to full links. Returns: The processed, escaped string. """ # We need to surround each split paragraph with a <p> tag, # because otherwise Jinja ignores the result. See the PR for #254. if make_urls: return u'\n\n'.join( u'<p>%s</p>' % urlize(p, nofollow=True, target='_blank'). replace('\n', Markup('<br>\n')) for p in _paragraph_re.split(escape(value))) else: return u'\n\n'.join( u'<p>%s</p>' % p.replace('\n', Markup('<br>\n')) for p in _paragraph_re.split(escape(value)))
def do_urlize(eval_ctx, value, trim_url_limit=None, nofollow=False, target=None): """Converts URLs in plain text into clickable links. If you pass the filter an additional integer it will shorten the urls to that number. Also a third argument exists that makes the urls "nofollow": .. sourcecode:: jinja {{ mytext|urlize(40, true) }} links are shortened to 40 chars and defined with rel="nofollow" If *target* is specified, the ``target`` attribute will be added to the ``<a>`` tag: .. sourcecode:: jinja {{ mytext|urlize(40, target='_blank') }} .. versionchanged:: 2.8+ The *target* parameter was added. """ rv = urlize(value, trim_url_limit, nofollow, target) if eval_ctx.autoescape: rv = Markup(rv) return rv
def do_urlize(eval_ctx, value, trim_url_limit=None, nofollow=False, target=None, rel=None): """Converts URLs in plain text into clickable links. If you pass the filter an additional integer it will shorten the urls to that number. Also a third argument exists that makes the urls "nofollow": .. sourcecode:: jinja {{ mytext|urlize(40, true) }} links are shortened to 40 chars and defined with rel="nofollow" If *target* is specified, the ``target`` attribute will be added to the ``<a>`` tag: .. sourcecode:: jinja {{ mytext|urlize(40, target='_blank') }} .. versionchanged:: 2.8+ The *target* parameter was added. """ policies = eval_ctx.environment.policies rel = set((rel or '').split() or []) if nofollow: rel.add('nofollow') rel.update((policies['urlize.rel'] or '').split()) if target is None: target = policies['urlize.target'] rel = ' '.join(sorted(rel)) or None rv = urlize(value, trim_url_limit, rel=rel, target=target) if eval_ctx.autoescape: rv = Markup(rv) return rv
def test_escape_urlize_target(self): url = "http://example.org" url2 = "ftp://example.com" target = "<script>" result = urlize(url2, target=target) assert result == ('<a href="ftp://example.com"' ' target="<script>">' 'ftp://example.com</a>')
def walk(node): html="<dl>" for key, item in node.items(): html+="<dt>" + key.capitalize() + "</dt>" if is_dict(item): html+="<dd>" + walk(item) + "</dd>" elif is_list(item): for element in item: if is_dict(element): html+="<dd>" + walk(element) + "</dd>" else: html+="<dd>" + urlize(element) + "</dd>" else: if type(item) is int or type(item) is float: item = str(item) html+="<dd>" + urlize(item) + "</dd>" return html + "</dl>"
def test_escape_urlize_target(self): url = "http://example.org" target = "<script>" assert urlize(url, target=target) == ( '<a href="http://example.org"' ' target="<script>">' "http://example.org</a>" )
def urlize_data(data): """ Returns new data with all values urlized. """ if isinstance(data, list): return [urlize_data(value) for value in data] if isinstance(data, dict): return {key: urlize_data(value) for key, value in data.items()} return urlize(data)
def add_event(event): event['text'] = event['title'] event['description'] = urlize(event['description']) event['start_date'] = event['start_date'].strftime('%Y-%m-%d %H:%M:00') event['end_date'] = event['end_date'].strftime('%Y-%m-%d %H:%M:00') event['venue'] = slugify(event['venue']) if event.get('source', 'ical') == 'database': event['link'] = url_for('.line_up_proposal', proposal_id=event['id']) return event
def __extract_text(self, subject=None, predicate=None, obj=None, language='en'): out = None for i in self._graph[subject:predicate:obj]: if out is None or i.language == language: out = urlize(i).replace('\n', '<br />') return self.__local_anchor_from_iri(out)
def format_message_explicit_emotes(message, emotes, size="1.0"): if not emotes: return Markup(urlize(message).replace('<a ', '<a target="_blank" ')) # emotes format is # <emoteid>:<start>-<end>[,<start>-<end>,...][/<emoteid>:<start>-<end>,.../...] # eg: # 123:0-2/456:3-6,7-10 # means that chars 0-2 (inclusive, 0-based) are emote 123, # and chars 3-6 and 7-10 are two copies of emote 456 parsed_emotes = [] for emote in emotes.split('/'): emoteid, positions = emote.split(':') emoteid = int(emoteid) for position in positions.split(','): start, end = position.split('-') start = int(start) end = int( end ) + 1 # make it left-inclusive, to be more consistent with how Python does things parsed_emotes.append((start, end, emoteid)) parsed_emotes.sort(key=lambda x: x[0]) bits = [] prev = 0 for start, end, emoteid in parsed_emotes: if prev < start: bits.append( urlize(message[prev:start]).replace('<a ', '<a target="_blank" ')) url = escape("http://static-cdn.jtvnw.net/emoticons/v1/%d/%s" % (emoteid, size)) command = escape(message[start:end]) bits.append('<img src="%s" alt="%s" title="%s">' % (url, command, command)) prev = end if prev < len(message): bits.append( urlize(message[prev:]).replace('<a ', '<a target="_blank" ')) return Markup(''.join(bits))
def format_message(message, emotes): ret = "" stack = [(message, "")] while len(stack) != 0: prefix, suffix = stack.pop() for emote in emotes: parts = emote["regex"].split(prefix, 1) if len(parts) >= 3: stack.append((parts[-1], suffix)) stack.append((parts[0], Markup(emote["html"].format(escape(parts[1]))))) break else: ret += Markup(urlize(prefix).replace('<a ', '<a target="_blank" ')) + suffix return ret
def add_book(): title = escape(request.form.get('title', '')) description = escape(request.form.get('description', '')) created = datetime.datetime.now() if title and description: error = None #some basic dupe checking existing = g.db.execute('select * from books where title like (?)', [title]).fetchall() g.db.commit() if existing: error = u"A book with this title already exists! DUN DUN DUN ..." if request.is_xhr: if error: return jsonify(error=error) #create new book g.db.execute( 'insert into books (title, description, created) values (?, ?, ?)', [title, description, created]) g.db.commit() book_id = g.db.execute('select id from books where title like (?)', [title]).fetchone()[0] html = book_html % ( 'reading', #assume book is not finished if just added book_id, title, urlize(description), datetimeformat(created), book_id, title, description, ) return jsonify(html=html) else: return u"XHR requests only." else: return jsonify(error="Missing the stuffs!")
def do_urlize(environment, value, trim_url_limit=None, nofollow=False): """Converts URLs in plain text into clickable links. If you pass the filter an additional integer it will shorten the urls to that number. Also a third argument exists that makes the urls "nofollow": .. sourcecode:: jinja {{ mytext|urlize(40, true) }} links are shortened to 40 chars and defined with rel="nofollow" """ rv = urlize(soft_unicode(value), trim_url_limit, nofollow) if environment.autoescape: rv = Markup(rv) return rv
def do_urlize(eval_ctx, value, trim_url_limit=None, nofollow=False): """Converts URLs in plain text into clickable links. If you pass the filter an additional integer it will shorten the urls to that number. Also a third argument exists that makes the urls "nofollow": .. sourcecode:: jinja {{ mytext|urlize(40, true) }} links are shortened to 40 chars and defined with rel="nofollow" """ rv = urlize(value, trim_url_limit, nofollow) if eval_ctx.autoescape: rv = Markup(rv) return rv
def format_message(message, emotes): ret = "" stack = [(message, "")] while len(stack) != 0: prefix, suffix = stack.pop() for emote in emotes: parts = emote["regex"].split(prefix, 1) if len(parts) >= 3: stack.append((parts[-1], suffix)) stack.append( (parts[0], Markup(emote["html"].format(escape(parts[1]))))) break else: ret += Markup( urlize(prefix).replace('<a ', '<a target="_blank" ')) + suffix return ret
def add_book(): title = escape(request.form.get('title', '')) description = escape(request.form.get('description', '')) created = datetime.datetime.now() if title and description: error = None #some basic dupe checking existing = g.db.execute('select * from books where title like (?)', [title]).fetchall() g.db.commit() if existing: error = u"A book with this title already exists! DUN DUN DUN ..." if request.is_xhr: if error: return jsonify(error=error) #create new book g.db.execute('insert into books (title, description, created) values (?, ?, ?)', [title, description, created]) g.db.commit() book_id = g.db.execute('select id from books where title like (?)', [title]).fetchone()[0] html = book_html % ( 'reading', #assume book is not finished if just added book_id, title, urlize(description), datetimeformat(created), book_id, title, description, ) return jsonify(html=html) else: return u"XHR requests only." else: return jsonify(error="Missing the stuffs!")
def _getMessageCard(self, message, search=None): message = odict(message) image = getUserImage(message.user_id) user_icon = div(img(src=image, width='70px', class_='img-thumbnail'), class_='userIcon') username = div(message.author, class_='messageAuthor') reason = div(message.reason, class_='messageReason') date = div(message.created, class_='messageDate') name_link = a(username, href='//%s/profile.py?u=%s' % (self.conf.baseurl, encrypt_int(message.user_id))) username_and_date = div(name_link + reason + date, class_='usernameAndDate') text = urlize(message.text, trim_url_limit=50, nofollow=True, target='_blank') text = self._highlightKeyTerms(text, search) messageLikes = MessageLikes(message) messageComments = MessageComments(message) footer = \ messageLikes.html_widget(self.page.session.user) + \ messageComments.html_widget() # hack need to instantiate m for each mesage: url_previews = '' for preview in Message(message.id).url_previews: preview2 = copy(preview) preview2['thumbnail_width'] = min(preview2['thumbnail_width'], 500) if not preview2['thumbnail_url']: preview2['thumbnail_url'] = '' url_previews += self.url_preview_html.format(**preview2) o = '' o += user_icon + username_and_date o += div(text, class_='messageText') o += url_previews o += div(footer, class_='messageFooter') o += messageLikes.html_likersSection() o += messageComments.html_commentsSection(self.page.session.user, search=search) return div(o, class_='messageCard', id='message_card_%s' % message.id)
def login(): if request.method == "POST": name = request.form["name"] password = request.form["password"] user = User.query.filter_by(name=name).first() if not user: flash("Credenciais invalidas") return redirect(url_for("login")) if not check_password_hash(user.password, password): flash("Credenciais invalidas") return redirect(url_for("login")) login_user(user) return redirect(urlize("/admin/")) return render_template("login.html")
def process_fb_comment(comment, post_link, graph): fb_dict = {} fb_dict['id'] = comment.get('id') fb_dict['name'] = comment.get('from').get('name') fb_dict['screen_name'] = comment.get('from').get('name') fb_dict['user'] = comment.get('from') fb_dict['author'] = comment.get('from') fb_dict['user_url'] = 'https://www.facebook.com/{}'.format(comment.get('from').get('id')) fb_dict['entities'] = [] fb_dict['created_time'] = comment.get('created_time') created_time = datetime.datetime.strptime(comment.get('created_time').split('+')[0], '%Y-%m-%dT%H:%M:%S') fb_dict['created_at'] = relative_time(created_time) fb_dict['link'] = post_link fb_dict['text'] = add_target_blank(urlize(comment.get('message'))) fb_dict['source'] = 'facebook' user = graph.request('{}/picture'.format(comment.get('from').get('id'))) fb_dict['profile_image'] = user.get('url') return fb_dict
def process_message(message): # NOTE: Working around jinja2.utils.urlize being far too greedy on matches if not message: return "" message = message.replace("\x0f", " \x0f") message = urlize(message) message = message.replace(" \x0f", "\x0f") message = re.sub("\x03(\\d\\d)", r'<span class="color\1">', message) message = message.replace("\x03", "</span>") message = message.replace("\x0f", "</b></em></u></span>") # Nasty. while "\x02" in message: message = message.replace("\x02", "<b>", 1) message = message.replace("\x02", "</b>", 1) while "\x1d" in message: message = message.replace("\x1d", "<em>", 1) message = message.replace("\x1d", "</em>", 1) while "\x1f" in message: message = message.replace("\x1f", "<u>", 1) message = message.replace("\x1f", "</u>", 1) return message
def twitterfy(tweet): tweet = urlize(tweet) # find hashtags pattern = compile(r"(?P<start>.?)#(?P<hashtag>[A-Za-z0-9\-_]+)(?P<end>.?)") # replace with link to search link = (r'\g<start>#<a href="http://search.twitter.com/search?q=\g<hashtag' '>" title="#\g<hashtag> search Twitter">\g<hashtag></a>\g<end>') text = pattern.sub(link, tweet) # find usernames pattern = compile(r"(?P<start>.?)@(?P<user>[A-Za-z0-9_]+)(?P<end>.?)") # replace with link to profile link = (r'\g<start>@<a href="http://twitter.com/\g<user>" title="#\g<user' '> on Twitter">\g<user></a>\g<end>') text = pattern.sub(link, text) return Markup(text)
def process_fb_comment(comment, post_link, graph): fb_dict = {} fb_dict['id'] = comment.get('id') fb_dict['name'] = comment.get('from').get('name') fb_dict['screen_name'] = comment.get('from').get('name') fb_dict['user'] = comment.get('from') fb_dict['author'] = comment.get('from') fb_dict['user_url'] = 'https://www.facebook.com/{}'.format( comment.get('from').get('id')) fb_dict['entities'] = [] fb_dict['created_time'] = comment.get('created_time') created_time = datetime.datetime.strptime( comment.get('created_time').split('+')[0], '%Y-%m-%dT%H:%M:%S') fb_dict['created_at'] = relative_time(created_time) fb_dict['link'] = post_link fb_dict['text'] = add_target_blank(urlize(comment.get('message'))) fb_dict['source'] = 'facebook' user = graph.request('{}/picture'.format(comment.get('from').get('id'))) fb_dict['profile_image'] = user.get('url') return fb_dict
def get_nl2br(value, make_urls=True): """ Splits the provided string into paragraph tags based on the line breaks within it and returns the escaped result. Args: value: The string to process. make_urls: If True, will attempt to convert any URLs in the string to full links. Returns: The processed, escaped string. """ # We need to surround each split paragraph with a <p> tag, # because otherwise Jinja ignores the result. See the PR for #254. if make_urls: return u'\n\n'.join(u'<p>%s</p>' % urlize( p, nofollow=True, target='_blank').replace('\n', Markup('<br>\n')) for p in _paragraph_re.split(escape(value))) else: return u'\n\n'.join(u'<p>%s</p>' % p.replace('\n', Markup('<br>\n')) for p in _paragraph_re.split(escape(value)))
def update_book(): book_id = escape(request.form.get('book_id', '')) edit_title = escape(request.form.get('edit_title', '')) edit_desc = escape(request.form.get('edit_desc', '')) if book_id and edit_title and edit_desc: if request.is_xhr: #update the book informations and return html g.db.execute( 'update books SET title = ?, description = ? WHERE rowid = ?', (edit_title, edit_desc, int(book_id))) g.db.commit() book = g.db.execute('select * from books where id = ?', [int(book_id)]).fetchone() g.db.commit() html = book_html % ( 'finished' if book[3] else 'reading', #book could be finished book[0], #id book[1], #title urlize(book[2]), #desc datetimeformat(convert_date(book[4])), book[0], book[1], book[2], ) return jsonify(success=True, html=html) else: return u"XHR requests only." else: return jsonify(error=u"Missing all the stuffs.")
def html_commentsSection(self, user, search=None): comment_cards = [] # get existing comments for comment in self.comments: image = getUserImage(comment['user_id']) user_icon = div(img(src=image, width='30px', class_='img-thumbnail'), class_='userIcon') who = comment['user_fullname'] text = comment['text'] text = urlize(text, target='_blank') if search: for term in search.split(' '): term2 = r'(%s)(?!=)' % term text =re.sub(term2, r'<span class="search-term">\1</span>', text, flags=re.IGNORECASE) time_ago = cal_time_ago(comment['created']) who_link = a(who, href='//%s/profile.py?u=%s' % (self.conf.baseurl, encrypt_int(comment['user_id']))) comment_card = div(span(user_icon) + ' ' + span(who_link, class_='commenter') + ' ' + span(text, class_='comment-text') + ' ' + span(time_ago, class_='comment-time-ago'), class_='comment-card') comment_cards.append(comment_card) # add new comment field: new_comment_card = open('new-comment.html', 'r').read()\ .format(message_id=self.message.id) comment_cards.append(new_comment_card) comment_cards_html = '\n'.join(comment_cards) return div(comment_cards_html, class_='comments', id='comments_%s' % self.message.id)
class MarkdownField(MarkupField): CUSTOM_RENDERERS = ( ('markdown', render_sanitized_markdown), ('html', sanitize_html), ('plain', lambda markup: linebreaks(urlize(escape(markup)))), ('', lambda markup: markup), ) def __init__(self, **kwargs): kwargs.setdefault('blank', True) kwargs.update( default_markup_type='markdown', markup_choices=MarkdownField.CUSTOM_RENDERERS, ) super(MarkdownField, self).__init__(**kwargs) def get_searchable_content(self, value): return self.get_prep_value(value) def formfield(self, **kwargs): defaults = {'widget': MarkdownTextarea} defaults.update(kwargs) return super(MarkupField, self).formfield(**defaults)
def test_escape_urlize_target(self): url = "http://example.org" target = "<script>" assert urlize(url, target=target) == ('<a href="http://example.org"' ' target="<script>">' 'http://example.org</a>')
def do_urlize(eval_ctx, value, trim_url_limit = None, nofollow = False): rv = urlize(value, trim_url_limit, nofollow) if eval_ctx.autoescape: rv = Markup(rv) return rv
def do_urlize(eval_ctx, value, trim_url_limit=None, nofollow=False): rv = urlize(value, trim_url_limit, nofollow) if eval_ctx.autoescape: rv = Markup(rv) return rv
def _process_text(s): s = escape(s) s = urlize(s) return s.replace('\n', '<br>')
def md_body(value): value = urlize(value,32,True) return markdown(value)
def pretty_text(text): text = text.strip(" \n\r") text = urlize(text, trim_url_limit=40) text = "\n".join(f"<p>{para}</p>" for para in re.split(r"[\r\n]+", text)) return Markup(text)
def md_body(value): value = urlize(value, 32, True) return markdown(value)