def listar(self, deletado=False): search = False q = request.args.get('q') page, per_page, offset = get_page_args( page_parameter="page", per_page_parameter="per_page" ) params = None sql = "select * from artigo " sql_count = "select count(*) as total from artigo " where = "" if deletado: where += "where deletado = 1 " else: where += "where deletado = 0 " if q: search = True where += "and (titulo like %s or corpo like %s) " params = ("%" + q + "%", "%" + q + "%") sql += where sql_count += where sql += " limit {}, {};".format(offset, per_page) conexao = factory_conexao() artigos = [] try: for registro in query(conexao, sql, params=params): artigo = ArtigoData() artigo.id_artigo = registro["id_artigo"] artigo.titulo = markdown(registro["titulo"]) artigo.corpo = markdown(registro["corpo"]) artigo.data_publicacao = registro["data_publicacao"] artigo.data_edicao = registro["data_edicao"] artigo.tags = registro["tags"] artigos.append(artigo) total = 0 for registro in query(conexao, sql_count, params=params): total = registro['total'] finally: conexao.close() pagination = Pagination( page=page, total=total, search=search, per_page=per_page, record_name="artigos", show_single_page=True, css_framework="bootstrap4", ) return { "template": "index.html", "artigos": artigos, "page": page, "per_page": per_page, "pagination": pagination, }
def load_page(section, recipe): my_recipe = CURR_DIR + '/templates/' + section + '/' + recipe + '/' + recipe + '.md' my_content="" try: with open(my_recipe, "r") as f: my_content = f.read() sections = get_sections('/app/hacker_cookbook/templates') print ('DEBUG: ' + markdown(my_content)) return render_template("index.html", html=markdown(my_content), sections=sections) except: return render_template('404.html'), 404
def load_page(section, recipe): my_recipe = CURR_DIR + '/templates/' + section + '/' + recipe + '/' + recipe + '.md' my_content = "" try: with open(my_recipe, "r") as f: my_content = f.read() sections = get_sections('/app/hacker_cookbook/templates') print('DEBUG: ' + markdown(my_content)) return render_template("index.html", html=markdown(my_content), sections=sections) except: return render_template('404.html'), 404
def test(): md_file = open("static/notes-md/test.md", "r").read() return render_template('test.html', md_file=markdown(md_file, fenced_code=True, math=True, math_explicit=True))
def markdown_discord(value): """Leverage misaka to generate something close to Discords own markdown.""" return markdown(value, autolink=True, fenced_code=True, wrap=True, strikethrough=True)[:-3][3:]
def on_changed_summary(target, value, oldvalue, initiator): allowed_tags = ['a', 'abbr', 'acronym', 'b', 'code', 'blockquote', 'em', 'i', 'strong', 'li', 'ol', 'pre', 'strong', 'ul', 'h1', 'h2', 'h3', 'p', 'hr'] target.summary_html = bleach.linkify(bleach.clean( markdown(value, output_format='html'), tags=allowed_tags, strip=True) )
def editor(pid): try: post = posts.query.filter_by(id=pid).first() tag_string = '' for tag in post._get_tags(): tag_string = tag_string + tag.tag_name + ',' form = post_submit(request.form, title=post.title, sub_title=post.sub_title, date=post.date_time, tags=tag_string, pagedown=post.page_down) if request.method == "POST" and form.validate(): post.title = form.title.data new_title = post.title post.sub_title = form.sub_title.data post.date_time = form.date.data post._set_tags(form.tags.data) post.post_content = markdown(form.pagedown.data) post.page_down = form.pagedown.data db.session.commit() return redirect(url_for('blog.post', post_name=new_title)) else: pass return render_template("panel.html", form=form) except Exception as e: return ('editor page error: ' + str(e))
def render(self, text, **overrides): # this method is a copy of the original one, except the input text is preprocessed preprocessed = [] for word in re.findall(r"[\w%$@#-]+|[^\w]", text): if len(word) > 1: if word.startswith('@'): preprocessed.append('[{0}](/user/{1})'.format( word, word[1:])) elif word.startswith('#'): preprocessed.append('[{0}](/topic/{1})'.format( word, sane_topic_name(word))) elif word.startswith('$'): preprocessed.append('[Law {0}](/law/{0})'.format(word[1:])) elif word.startswith('%'): preprocessed.append('[Proposal {0}](/proposal/{0})'.format( word[1:])) else: preprocessed.append(word) else: preprocessed.append(word) options = self.defaults if overrides: options = flask_misaka.copy(options) options.update(overrides) return flask_misaka.markdown(''.join(preprocessed), self.renderer, **options)
def send_mail(message, to_mail, to_name=None, from_name=None, subject=None, banner=None, title=None, reply_name=None, reply_mail=None, attach_files=None, attach_names=None): if reply_name and not reply_mail: reply_name = None r = Redis(host=REDIS_HOST, port=REDIS_PORT, password=REDIS_PASSWORD) try: r.ping() sender = Queue(connection=r, name=REDIS_MAIL, default_timeout=REDIS_JOB_TIMEOUT) except ConnectionError: print('REDIS NOT WORKING') return False out = ['Subject: %s' % Header(subject).encode() or 'No Title', 'To: %s' % ('%s <%s>' % (Header(to_name).encode(), to_mail) if to_name else to_mail), 'From: %s <%s>' % (Header(from_name or LAB_NAME).encode(), SMTP_MAIL)] if reply_mail: out.append('Reply-To: %s' % ('%s <%s>' % (Header(reply_name).encode(), reply_mail) if reply_name else reply_mail)) msg = MIMEMultipart('alternative') msg.attach(MIMEText(message, 'plain')) msg.attach(MIMEText(render_template('email.html', body=markdown(message, renderer=CustomMisakaRenderer(flags=0 | HTML_ESCAPE), underline=True, math=True, strikethrough=True, superscript=True, tables=True, footnotes=True, autolink=True), banner=banner, title=title), 'html')) if attach_files: tmp = MIMEMultipart('mixed') tmp.attach(msg) msg = tmp if attach_names and len(attach_files) == len(attach_names): names = attach_names else: names = [x.name for x in attach_files] for file, name in zip(attach_files, names): try: with file.open("rb") as f: attach = MIMEApplication(f.read(), name=name) except (FileNotFoundError, PermissionError): print('INVALID ATTACH') return False attach['Content-Disposition'] = 'attachment; filename="%s"' % name msg.attach(attach) if MAIL_INKEY and MAIL_SIGNER: p = Popen(['openssl', 'smime', '-sign', '-inkey', MAIL_INKEY, '-signer', MAIL_SIGNER], stdin=PIPE, stdout=PIPE) out.append(p.communicate(input=msg.as_bytes())[0].decode()) else: out.append(msg.as_string()) try: return sender.enqueue_call('redis_mail.run', args=(to_mail, '\n'.join(out)), result_ttl=60).id except Exception: return False
def visualizar_artigo(self, id_artigo): conexao = factory_conexao() if not self._artigo_existe(id_artigo) or self._artigo_deletado(id_artigo): return {"template": 'indisponivel.html'} try: artigo = ArtigoData() for registro in query( conexao, "select * from artigo where id_artigo = %s", (id_artigo,) ): artigo.titulo = markdown(registro["titulo"]) artigo.corpo = markdown(registro["corpo"]) artigo.id_artigo = registro["id_artigo"] artigo.data_publicacao = registro["data_publicacao"] artigo.data_edicao = registro["data_edicao"] finally: conexao.close() return {"template": "artigo_visualizar.html", "artigo": artigo}
def post(): if request.method == "POST": try: jinja_var = markdown(request.form["jinja_var"]) return render_template(request.template_name["template_name"], jinja_var=jinja_var) except: try: jinja_var = markdown(request.form["jinja_var"]) print(jinja_var) return render_template("post_info.html", jinja_var=jinja_var) except: try: return render_template("post_info.html", jinja_var=request.form["jinja_var"]) except: return render_template("post_info.html")
def on_changed_body(target, value, oldvalue, initiator): allowed_tags = ['a', 'abbr', 'acronym', 'b', 'code', 'em', 'i', 'strong'] target.body_html = bleach.linkify(bleach.clean( markdown(value, output_format='html'), tags=allowed_tags, strip=True ) )
def test_undefined_option(self, html): ext, flags = 0, 0 result = markdown(TEST_MD, fireworks=True) html.assert_called_with(TEST_MD, extensions=ext, render_flags=flags) self.assertIsInstance(result, Markup) self.assertEqual( result, misaka.html(TEST_MD, extensions=ext, render_flags=flags))
def test_inverse_render(self, html): ext, flags = 0, HTML_SKIP_HTML result = markdown(TEST_MD, no_html=True) html.assert_called_with(TEST_MD, extensions=ext, render_flags=flags) self.assertIsInstance(result, Markup) self.assertEqual( result, misaka.html(TEST_MD, extensions=ext, render_flags=flags))
def test_inverse_ext(self, html): ext, flags = EXT_NO_INTRA_EMPHASIS, 0 result = markdown(TEST_MD, intra_emphasis=False) html.assert_called_with(TEST_MD, extensions=ext, render_flags=flags) self.assertIsInstance(result, Markup) self.assertEqual( result, misaka.html(TEST_MD, extensions=ext, render_flags=flags))
def test_defaults(self, html): ext, flags = 0, 0 result = markdown(TEST_MD) html.assert_called_with(TEST_MD, extensions=ext, render_flags=flags) self.assertIsInstance(result, Markup) self.assertEqual(result, misaka.html(TEST_MD, extensions=ext, render_flags=flags))
def test_one_ext_one_render(self, html): ext, flags = EXT_NO_INTRA_EMPHASIS, HTML_SKIP_HTML result = markdown(TEST_MD, no_intra_emphasis=True, no_html=True) html.assert_called_with(TEST_MD, extensions=ext, render_flags=flags) self.assertIsInstance(result, Markup) self.assertEqual( result, misaka.html(TEST_MD, extensions=ext, render_flags=flags))
def test_two_render(self, html): ext, flags = 0, HTML_HARD_WRAP | HTML_ESCAPE result = markdown(TEST_MD, wrap=True, escape=True) html.assert_called_with(TEST_MD, extensions=ext, render_flags=flags) self.assertIsInstance(result, Markup) self.assertEqual( result, misaka.html(TEST_MD, extensions=ext, render_flags=flags))
def test_two_ext(self, html): ext, flags = EXT_FENCED_CODE | EXT_AUTOLINK, 0 result = markdown(TEST_MD, fenced_code=True, autolink=True) html.assert_called_with(TEST_MD, extensions=ext, render_flags=flags) self.assertIsInstance(result, Markup) self.assertEqual( result, misaka.html(TEST_MD, extensions=ext, render_flags=flags))
def test_defaults(self, html): ext, flags = 0, 0 result = markdown(TEST_MD) html.assert_called_with(TEST_MD, extensions=ext, render_flags=flags) self.assertIsInstance(result, Markup) self.assertEqual( result, misaka.html(TEST_MD, extensions=ext, render_flags=flags))
def test_two_render(self, html): ext, flags = 0, HTML_HARD_WRAP | HTML_ESCAPE result = markdown(TEST_MD, wrap=True, escape=True) html.assert_called_with(TEST_MD, extensions=ext, render_flags=flags) self.assertIsInstance(result, Markup) self.assertEqual(result, misaka.html(TEST_MD, extensions=ext, render_flags=flags))
def test_defined_and_undefined_options(self, html): ext, flags = 0, HTML_HARD_WRAP result = markdown(TEST_MD, hard_wrap=True, stupid_hard_wrap=False) html.assert_called_with(TEST_MD, extensions=ext, render_flags=flags) self.assertIsInstance(result, Markup) self.assertEqual( result, misaka.html(TEST_MD, extensions=ext, render_flags=flags))
def test_one_ext_one_render(self, html): ext, flags = EXT_NO_INTRA_EMPHASIS, HTML_SKIP_HTML result = markdown(TEST_MD, no_intra_emphasis=True, no_html=True) html.assert_called_with(TEST_MD, extensions=ext, render_flags=flags) self.assertIsInstance(result, Markup) self.assertEqual(result, misaka.html(TEST_MD, extensions=ext, render_flags=flags))
def test_two_ext(self, html): ext, flags = EXT_FENCED_CODE | EXT_AUTOLINK, 0 result = markdown(TEST_MD, fenced_code=True, autolink=True) html.assert_called_with(TEST_MD, extensions=ext, render_flags=flags) self.assertIsInstance(result, Markup) self.assertEqual(result, misaka.html(TEST_MD, extensions=ext, render_flags=flags))
def test_inverse_ext(self, html): ext, flags = EXT_NO_INTRA_EMPHASIS, 0 result = markdown(TEST_MD, intra_emphasis=False) html.assert_called_with(TEST_MD, extensions=ext, render_flags=flags) self.assertIsInstance(result, Markup) self.assertEqual(result, misaka.html(TEST_MD, extensions=ext, render_flags=flags))
def test_inverse_render(self, html): ext, flags = 0, HTML_SKIP_HTML result = markdown(TEST_MD, no_html=True) html.assert_called_with(TEST_MD, extensions=ext, render_flags=flags) self.assertIsInstance(result, Markup) self.assertEqual(result, misaka.html(TEST_MD, extensions=ext, render_flags=flags))
def test_undefined_option(self, html): ext, flags = 0, 0 result = markdown(TEST_MD, fireworks=True) html.assert_called_with(TEST_MD, extensions=ext, render_flags=flags) self.assertIsInstance(result, Markup) self.assertEqual(result, misaka.html(TEST_MD, extensions=ext, render_flags=flags))
def test_defined_and_undefined_options(self, html): ext, flags = 0, HTML_HARD_WRAP result = markdown(TEST_MD, hard_wrap=True, stupid_hard_wrap=False) html.assert_called_with(TEST_MD, extensions=ext, render_flags=flags) self.assertIsInstance(result, Markup) self.assertEqual(result, misaka.html(TEST_MD, extensions=ext, render_flags=flags))
def sendemail(to=None, from_=None, subject=None, body=None, attachments=None, reply_to=None): """ Send email :param to: receiver :param from_: sender :param subject: subject :param body: Email body :param attachments: Attachments """ if to is None: to = [] if attachments is None: attachments = [] if not subject: subject = "User not recognized" if not body: body = "Please email support at %s" % SUPPORT_EMAIL to = list(set(to)) # no duplicates. sg = sendgrid.SendGridAPIClient(apikey=SENDGRID_API_KEY) from_email = Email(from_ or SUPPORT_EMAIL) if reply_to is not None: from_email = Email(reply_to) to_email = Email(to[0]) content = Content("text/html", markdown(body)) mail = Mail(from_email, subject, to_email, content) if reply_to is not None: mail.reply_to = Email(reply_to) if len(to) > 1: for receiver in to[1:]: mail.personalizations[0].add_to(Email(receiver)) for attachment in attachments: mail.add_attachment(build_attachment(attachment)) try: print('Now trying to send an email') response = sg.client.mail.send.post(request_body=mail.get()) print("Email sent.. %s" % response.status_code) return response.status_code, response.body except Exception as e: print(e) raise e
def markdown(text_md, had_gen=None, **options): ''' Renders markdown text to html Parameters: text_md (str): Text in markdown **options: https://flask-misaka.readthedocs.io/en/latest/#options ''' renderer.set_anchors(had_gen) return flask_misaka.markdown(text_md, renderer=renderer, **options)
def test_two_ext_two_render(self, html): ext = EXT_STRIKETHROUGH | EXT_SUPERSCRIPT flags = HTML_HARD_WRAP | HTML_USE_XHTML result = markdown(TEST_MD, strikethrough=True, superscript=True, hard_wrap=True, use_xhtml=True) html.assert_called_with(TEST_MD, extensions=ext, render_flags=flags) self.assertIsInstance(result, Markup) self.assertEqual(result, misaka.html(TEST_MD, extensions=ext, render_flags=flags))
def index(): try: with open(jp(config['markdown-dir'], 'home.md')) as f: content = markdown(f.read(), smartypants=True) content = render_template_string(content, discord=Markup(config['discord-url']), patreon=Markup(config['patreon-url']), html=True) return render_template('content.html', title='Home', content=content) except OSError: abort(404)
def on_changed_body(target, value, oldvalue, initiator): allowed_tags = ['a', 'abbr', 'acronym', 'b', 'blockquote', 'code', 'em', 'i', 'li', 'ol', 'pre', 'strong', 'ul', 'h1', 'h2', 'h3', 'p', 'img', 'figure', 'src', 'class', 'br', 'hr'] allowed_attrs = {'*': ['class'], 'a': ['href', 'rel'], 'img': ['src', 'alt']} # print(value) target.body_html = bleach.linkify(bleach.clean( markdown(value, output_format='html'), tags=allowed_tags, strip=False, attributes=allowed_attrs))
def parse(self): self.markdown = self.parse_metadata(self.markdown) self.markup = markdown(self.markdown, strikethrough=True, autolink=True, fenced_code=True, highlight=True, quote=True, math=True, superscript=True, tables=True, footnotes=True, smartypants=True)
def on_changed_body(target, value, oldvalue, initiator): renderer = HighlighterRenderer() target.body_html = markdown(value, renderer=HighlighterRenderer(), fenced_code=True, underline=True, highlight=True, disable_indented_code=True, space_headers=True, strikethrough=True, footnotes=True, tables=True, math=True)
def not_found(error): try: # Try and find a custom 404 page with open(jp(config['markdown-dir'], '404.md')) as f: content = markdown(f.read(), smartypants=True) return render_template('content.html', title='404', content=content), 404 except OSError: # If we don't find one use this default ugly one return render_template('content.html', title='404', content='<h1>404 Not Found</h1>'), 404
def render_markdown(path, name=None): try: with open(path) as f: md = f.read() content = markdown(md, fenced_code=True, smartypants=True) # Instantiate an HTML parser so we can extract what's in <h1> class TitleParser(HTMLParser): def __init__(self): super().__init__() self.read_title = False self.read_blurb = False self.title = None self.blurb = None def handle_starttag(self, tag, attrs): if tag == 'h1': self.read_title = True if tag == 'p': self.read_blurb = True def handle_data(self, data): if self.read_title and self.title is None: self.title = data if self.read_blurb and self.blurb is None: self.blurb = data if self.blurb is not None and self.title is not None: # Stop the parser from going through the entire document raise StopIteration() parser = TitleParser() try: parser.feed(content) title = name blurb = None except StopIteration: title = parser.title blurb = parser.blurb if name is None: title = 'Documentation Index' return render_template('content.html', title=title, content=content, blurb=blurb) except OSError: abort(404)
def aboutPage(): readme_file = open("README.md", "r") read_me_html = markdown(readme_file.read(), fenced_code=True) return render_template( "about.html", read_me_html=read_me_html, title="About", ) # @bp.route("/testing") # @login_required # def displayTest(): # return render_template("test.html", title="Test")
def privacy(): try: with open(jp(config['markdown-dir'], 'privacy.md')) as f: content = markdown(f.read(), smartypants=True) content = render_template_string(content, discord=Markup(config['discord-url']), base_url=Markup('https://' + config['hostname']), html=True) return render_template('content.html', title='Privacy Policy', content=content) except OSError: abort(404)
def test_two_ext_two_render(self, html): ext = EXT_STRIKETHROUGH | EXT_SUPERSCRIPT flags = HTML_HARD_WRAP | HTML_USE_XHTML result = markdown(TEST_MD, strikethrough=True, superscript=True, hard_wrap=True, use_xhtml=True) html.assert_called_with(TEST_MD, extensions=ext, render_flags=flags) self.assertIsInstance(result, Markup) self.assertEqual( result, misaka.html(TEST_MD, extensions=ext, render_flags=flags))
def taskpopup(): #Check if user have access to the task first! try: taskid = int(request.args.get('id')) except: flash("Invalid request",'danger') return redirect(url_for('tasks.admin')) task=Task.query.get(taskid) text=task.text if task is None: flash('Unknown task','warning') return redirect(url_for('tasks.admin')) if text is None: tasktext='No description avaliable.' else: tasktext=text.text for img in text.images: tasktext+='\n['+img.keyword+']: '+ url_for('image_files', filename=str(text.id)+'/'+img.filename) #All users for this task taskusers={} ut=UserTasks.query.filter(UserTasks.task_id==task.id).all() taskusers.update({u.user.name:u.priority for u in ut}) ue=UserEquipment.query.filter(UserEquipment.equipment_id==task.equipment_id).all() taskusers.update({u.user.name:u.priority for u in ue}) usrstr=', '.join(["{} [{}]".format(u,p) for (u,p) in taskusers.items()]) view={'title':task.name, 'content':markdown(tasktext) } #details list view['details']=[ ('id',str(task.id)), ('equipment',str(task.equipment.name)), ('facility',str(task.equipment.facility.name)), ('priority',str(task.priority)), ('logging',logtypes(task.logging)), ('cycle',str(task.cycle)+' '+cycletypes(task.cycletype).tblname), ('Due date',str(task.ddate)), ('Users',usrstr) ] return render_template('tasks/task_ajax.html',view=view)
def markdown2html(text: str) -> str: opts = { 'autolink': True, 'underline': True, 'space_headers': False, 'no_intra_emphasis': True, 'tables': True, 'wrap': True, 'escape': False, 'skip_html': False, 'smartypants': True, } m = markdown(text, options=opts) return m
def flcmd(cmd): if cmd == 'all' or cmd == '': return 'Cmds: \n' + '; '.join(enabled_cmd) if cmd not in enabled_cmd: return "Not a valid command: " + cmd, 403 if request.method == 'GET': with open('cmds/%s.sh' % cmd, 'r') as f: pagemd = show_cmd % f.read() output = subprocess.run(["./cmds/%s.sh" % cmd], stderr=subprocess.STDOUT, stdout=subprocess.PIPE, text=True) pagemd += result % output return markdown(pagemd, fenced_code=True) if request.method == 'POST': pass
def index(): sections = get_sections('/app/hacker_cookbook/templates') return render_template("index.html", html=markdown(content), sections=sections)
def json_news(): """ Fetches a single News article for display onscreen. :return: A rendered version of a markdown-formatted news article as json dump. """ return json.dumps(markdown(utils.get_news()))