def render(self, value, record=None, bound_column=None): html = u'<button rel="popover" class="btn btn-small" data-content="{content}" data-original-title="{title}" data-placement="bottom">{text}</button>'.format( content=escape(value), title=escape(record.module.replace('<','').replace('>','')), text=escape(bound_column.verbose_name) ) return Markup(html)
def render_link(self, uri, text, attrs=None): attrs = AttributeDict( attrs if attrs is not None else self.attrs.get('a', {})) html = u'<a href="{uri}"{attrs}>{text}</a>'.format( uri=escape(uri), attrs=" %s" % attrs.as_html() if attrs else "", text=escape(text)) return Markup(html)
def render_link(self, uri, text, attrs=None): attrs = AttributeDict(attrs if attrs is not None else self.attrs.get('a', {})) html = u'<a href="{uri}"{attrs}>{text}</a>'.format( uri=escape(uri), attrs=" %s" % attrs.as_html() if attrs else "", text=escape(text) ) return Markup(html)
def contacts(): form = ContactForm(request.form) if form.validate_on_submit(): send_email(str(escape(form.name.data.strip())), str(escape(form.email.data.strip())), str(escape(form.subject.data.strip())), str(escape(form.message.data.strip()))) return redirect(url_for('app.email_success')) return render_template('app/contacts.html', form=form)
def gopher_url_redirect(url): # Use the full_path because it keeps any query params intact url = request.full_path.split(':', 1)[1] # Drop the "/URL:" url = url.rstrip( '?') # Flask adds an ? even if there are no params url = escape(url) return self.URL_REDIRECT_TEMPLATE.format(url=url).strip()
def subscription(): subscription_type = request.args.get('type', SubscriptionForm.JUNIOR) form = SubscriptionForm(request.form) form.subscription_type.data = subscription_type if form.validate_on_submit(): order_data = deepcopy(form.data) order_data.pop('csrf_token') # Save to a DB order info. order = Order(**order_data) db.session.add(order) db.session.commit() # Notify about an order. send_message_to_channel(cid=current_app.config['CHANNEL_ID'], text=create_order_notification_msg( order, order_data)) # Send an invoice to a customer in case of choosing credit card # payment option. if order_data['payment_option'] == SubscriptionForm.CREDIT_CARD: send_invoice(email=str(escape(order_data['email'].strip())), message=create_invoice_msg(order_data), subject='Bevbox Invoice') return redirect(url_for('app.success')) return render_template('app/subscription.html', form=form, subscription_type=subscription_type)
def as_html(self, order=True, **kwargs): new_attrs = self if not order: all_class = new_attrs.pop('class','').replace('orderable','').replace('sortable','') new_attrs['class'] = all_class if kwargs: new_attrs = copy.deepcopy(self) AttributeDict.merge(new_attrs, kwargs) return Markup(' '.join(['%s="%s"' % (k, escape(v)) for k, v in new_attrs.iteritems()]))
def parse_dict_or_json(msg): """If we find some matched brackets, we just assume it's json or python dict literals, and parse them out and highlight it with python.""" start = 0 end = 0 imbalance = 0 for i,c in enumerate(msg): if c == '{' and not start: start = i continue elif c == '{': imbalance += 1 elif c == '}' and not imbalance: end = i break elif c == '}': imbalance -= 1 if start and end: return ''.join(filter(None, [escape(msg[:start]), pygmentize(msg[start:end+1], 'python'), parse_dict_or_json((msg[end+1:]))])) return str(escape(msg))
def create_invoice_msg(order_data: dict) -> str: """Creates a message for an invoice based on a template.""" cost = calculate_subscription_cost(order_data) return render_template('invoice/invoice_msg.html', cost=cost, credit_card=current_app.config['CREDIT_CARD'], name=str(escape(order_data['name'].strip())), subscription_type=get_subscription_name( order_data['subscription_type']))
def as_html(self, **kwargs): add_class = kwargs.get('add_class', None) if add_class: kwargs.pop('add_class') if self.get('class', None): self['class'] = '%s %s' % (self['class'], add_class) else: self['class'] = add_class self.update(kwargs) return Markup(' '.join(['%s="%s"' % (k, escape(v)) for k, v in self.iteritems()]))
def as_html(self, order=True, **kwargs): new_attrs = self if not order: all_class = new_attrs.pop('class', '').replace('orderable', '').replace('sortable', '') new_attrs['class'] = all_class if kwargs: new_attrs = copy.deepcopy(self) AttributeDict.merge(new_attrs, kwargs) return Markup(' '.join( ['%s="%s"' % (k, escape(v)) for k, v in new_attrs.iteritems()]))
def create_order_notification_msg(order: Order, order_data: dict) -> str: """Creates a Telegram notification message from subscription form data.""" # TODO: Move to a template. msg = ( 'Замовлення <b>№{}</b>.\n' 'Клієнт <b>{}</b> з міста <b>{}</b> замовив підписку <b>{}</b> ' 'у відділення "Нової Пошти" <b>№{}</b>.\n' 'Email: <a href="mailto:{email}">{email}</a>\n' 'Телефон: <a href="tel:{tel}">{tel}</a>\n' 'Варіант оплати: <b>{}</b>\n' # 'Варіант доставки: <b>{}</b>\n' # 'Адресса доставки: <b>{}</b>\n' 'Сигара: <b>{}</b>\n' 'Сірники: <b>{}</b>\n' 'Каміньці: <b>{}</b>\n' 'Гільйотина: <b>{}</b>\n' 'Побажання: <b>{}</b>\n' '\n' '<b>Вартість</b>: <i>₴{}</i>' ).format( order.id, str(escape(order_data['name'].strip())), str(escape(order_data['city'].strip())), str(escape(order_data['subscription_type'].strip())), str(escape(order_data['department'])), str(escape(order_data['payment_option'])), # str(escape(order_data['delivery_option'])), # str(escape(order_data.get('delivery_address', '-').strip())), 'ні' if order_data['cigar'] else 'так', 'ні' if order_data['matches'] else 'так', 'ні' if order_data['stones'] else 'так', 'ні' if order_data['guillotine'] else 'так', str( escape(order_data['preferences'] if order_data['preferences'] else 'Немає').strip()), calculate_subscription_cost(order_data), email=str(escape(order_data['email'].strip())), tel=str(escape(order_data['phone'].strip()))) return msg
def nl2br_jinja_filter(value): result = '<br>\n'.join(escape(line) for line in value.split('\n')) return Markup(result)
def _post_to_tumblr(): """ Handles the POST to Tumblr. """ def strip_html(value): """ Strips HTML from a string. """ return re.compile(r'</?\S([^=]*=(\s*"[^"]*"|\s*\'[^\']*\'|\S*)|[^>])*?>', re.IGNORECASE).sub('', value) def strip_breaks(value): """ Converts newlines, returns and other breaks to <br/>. """ value = re.sub(r'\r\n|\r|\n', '\n', value) return value.replace('\n', do_mark_safe('<br/>')) # Request is a global. Import it down here where we need it. from flask import request # These should match the form fields. message = strip_html(request.form.get('message', None)) message = escape(message) message = strip_breaks(message) name = strip_html(request.form.get('signed_name', None)) email = strip_html(request.form.get('email', None)) context = { 'message': message, 'name': name, 'email': email, 'app_config': app_config } caption = render_template('caption.html', **context) secrets = app_config.get_secrets() t = Tumblpy( app_key=secrets['TUMBLR_APP_KEY'], app_secret=secrets['TUMBLR_APP_SECRET'], oauth_token=secrets['TUMBLR_OAUTH_TOKEN'], oauth_token_secret=secrets['TUMBLR_OAUTH_TOKEN_SECRET']) file_path = '/uploads/%s/%s_%s' % ( app_config.PROJECT_SLUG, str(time.mktime(datetime.datetime.now().timetuple())).replace('.', ''), secure_filename(request.files['image'].filename.replace(' ', '-')) ) with open('/var/www%s' % file_path, 'w') as f: f.write(request.files['image'].read()) params = { "type": "photo", "caption": caption, "tags": app_config.TUMBLR_TAGS, "source": "http://%s%s" % (app_config.SERVERS[0], file_path) } try: tumblr_post = t.post('post', blog_url=app_config.TUMBLR_URL, params=params) tumblr_url = u"http://%s/%s" % (app_config.TUMBLR_URL, tumblr_post['id']) logger.info('200 %s reader(%s %s) (times in EST)' % (tumblr_url, name, email)) return redirect(tumblr_url, code=301) except TumblpyError, e: logger.error('%s %s http://%s%s reader(%s %s) (times in EST)' % ( e.error_code, e.msg, app_config.SERVERS[0], file_path, name, email)) return 'TUMBLR ERROR'
try: import unittest2 as unittest except ImportError: import unittest from flask import Flask, url_for from flask_lazyviews import LazyViews from flask_lazyviews.utils import LazyView from jinja2.filters import escape from testapp.app import create_app from testapp.views import page as page_view strong = lambda text: '<strong>{0}</strong>'.format(escape(text)) def create_test_app(name=None, **options): options.update({'DEBUG': True, 'TESTING': True}) app = Flask(name or 'testapp') app.config.update(options) return app class TestCase(unittest.TestCase): def setUp(self): self.app, self._ctx = None, None
def nl2br(value): result = u'\n\n'.join(u'<p>%s</p>' % p.replace(u'\n', u'<br>\n') for p in _paragraph_re.split(unicode(escape(value)))) return Markup(result)
import platform try: import unittest2 as unittest except ImportError: import unittest from flask import Flask, url_for from flask_lazyviews import LazyViews from flask_lazyviews.utils import LazyView from jinja2.filters import escape from testapp.app import create_app from testapp.views import page as page_view strong = lambda text: '<strong>{0}</strong>'.format(escape(text)) def create_test_app(name=None, **options): options.update({'DEBUG': True, 'TESTING': True}) app = Flask(name or 'testapp') app.config.update(options) return app class TestCase(unittest.TestCase): def setUp(self): self.app, self._ctx = None, None
def _parse_caption(cls, photo_dict): # search hashtags in caption and wrap caption = unicode(escape(photo_dict['caption'])) photo_dict['caption'] = re.sub(Photo.tag_re_with_hash, cls._wrap_tag, caption, flags=re.I + re.U) return photo_dict
def _post_to_tumblr(): """ Handles the POST to Tumblr. """ def strip_html(value): """ Strips HTML from a string. """ return re.compile(r'</?\S([^=]*=(\s*"[^"]*"|\s*\'[^\']*\'|\S*)|[^>])*?>', re.IGNORECASE).sub('', value) def strip_breaks(value): """ Converts newlines, returns and other breaks to <br/>. """ value = re.sub(r'\r\n|\r|\n', '\n', value) return value.replace('\n', do_mark_safe('<br/>')) # Request is a global. Import it down here where we need it. from flask import request message = strip_html(request.form.get('message', None)) message = escape(message) message = strip_breaks(message) name = strip_html(request.form.get('signed_name', None)) email = strip_html(request.form.get('email', None)) context = { 'message': message, 'name': name, 'email': email, 'app_config': app_config } caption = render_template('caption.html', **context) t = Tumblpy( app_key=os.environ['TUMBLR_CONSUMER_KEY'], app_secret=os.environ['TUMBLR_APP_SECRET'], oauth_token=os.environ['TUMBLR_OAUTH_TOKEN'], oauth_token_secret=os.environ['TUMBLR_OAUTH_TOKEN_SECRET']) file_path = '/uploads/%s/%s_%s' % ( app_config.PROJECT_SLUG, str(time.mktime(datetime.datetime.now().timetuple())).replace('.', ''), secure_filename(request.files['image'].filename.replace(' ', '-')) ) with open('/var/www%s' % file_path, 'w') as f: f.write(request.files['image'].read()) params = { "type": "photo", "caption": caption, "tags": app_config.TUMBLR_TAGS, "source": "http://%s%s" % (app_config.SERVERS[0], file_path) } try: tumblr_post = t.post('post', blog_url=app_config.TUMBLR_URL, params=params) tumblr_url = u"http://%s/%s" % (app_config.TUMBLR_URL, tumblr_post['id']) logger.info('200 %s reader(%s %s) (times in EST)' % (tumblr_url, name, email)) return redirect(tumblr_url, code=301) except TumblpyError, e: logger.error('%s %s http://%s%s reader(%s %s) (times in EST)' % ( e.error_code, e.msg, app_config.SERVERS[0], file_path, name, email)) return 'TUMBLR ERROR'
def site_export(request, feedtype="atom"): def _zinfo(fname, date_time): zinfo = zipfile.ZipInfo() zinfo.filename = fname zinfo.compress_type = zipfile.ZIP_DEFLATED zinfo.date_time = date_time return zinfo pages = all_pages(request.site._id) if pages: pages.sort(lambda a,b: cmp(a.updated, b.updated)) if feedtype == "atom": feed = AtomFeed( title="%s: Latest changes" % request.site.title and request.site.title or request.site.cname, subtitle=request.site.subtitle, updated = pages[0].updated, feed_url = request.url ) for page in pages: _url = "%s%s" % (request.host_url, url_for("show_page", pagename=page.title.replace(' ', '_'))) feed.add(page.title, escape(page.content), updated=page.updated, url=_url, id=_url, author=page.title.replace(' ', '_') ) return feed.get_response() elif feedtype == "json": json = { 'title': "%s: Latest changes" % request.site.title and request.site.title or request.site.cname, 'subtitle': request.site.subtitle, 'updated':datetime_tojson(pages[0].updated), 'pages': [] } for page in pages: url = url_for("show_page", pagename=page.title.replace(' ', '_') ) json['pages'].append({ 'title': page.title, 'content': page.content, 'url': url, 'updated':datetime_tojson(page.updated), 'id':page.title.replace(' ', '_') }) return send_json(json) elif feedtype == "zip": pages = all_pages(request.site._id) zip_content = StringIO() zfile = zipfile.ZipFile(zip_content, "w", zipfile.ZIP_DEFLATED) import time, codecs for page in pages: zinfo = _zinfo("markdown/%s" % smart_str(page.title.replace(" ", "_")) + ".txt", time.localtime()[:6]) zfile.writestr(zinfo, codecs.BOM_UTF8 + page.content.encode('utf-8')) zinfo = _zinfo("%s" % smart_str(page.title.replace(" ", "_")) + ".html", time.localtime()[:6]) zfile.writestr(zinfo, codecs.BOM_UTF8 + render_template("page/export.html", page=page, request=request, pages=pages).encode( "utf-8" )) zinfo = _zinfo("index.html", time.localtime()[:6]) zfile.writestr(zinfo, codecs.BOM_UTF8 + render_template("page/export_index.html", pages=pages, request=request).encode( "utf-8" )) zfile.close() response = BCResponse(zip_content.getvalue()) response.headers['content-type'] = "application/x-zip-compressed" return response
def render(self, value, record=None, bound_column=None): html = u'<button rel="popover" class="btn btn-small" data-content="{content}" data-original-title="{title}" data-placement="bottom">{text}</button>'.format( content=escape(value), title=escape(record.module.replace('<', '').replace('>', '')), text=escape(bound_column.verbose_name)) return Markup(html)