简体   繁体   中英

Python/Flask: Inject HTML to page

I have a page that gets input from the user and stores it in an object inside a dictionary in server side.

class post:
    def __init__(self, title, content, date, poster, desc):
        self.title = title
        self.content = content
        self.date = date
        self.poster = poster
        self.desc = desc

posts = {}

... 
    if request.method == "POST":
# NOTE: title and description is input, and content is textarea. 
# I only want to input html in content textarea.
                title = request.form["title"]
                content = request.form["content"]
                description = request.form["description"]
                if title in posts:
                    flash("A post with that title already exists!")
                    return redirect(url_for("post_content"))
                else:
                    posts[title] = post(title, content, date, session["user"], description)
                    flash("Posted successfully!")
                    return redirect(url_for("home"))
       
    else:
                return render_template("post.html")
...

I then send the data in posts to another page

@app.route("/post/<title>")
def post_page(title):
    data = posts[title]
    return render_template("content.html", post=data)

This is the template for content.html

{% extends "base.html "%}
{% block title %}{{post.title}}{% endblock %}
{% block content %}
    <h1>{{post.title}}</h1>
    <p>By {{post.poster}}, {{post.date}}</p>
    <p><i>{{post.desc}}</i></p> <br>
    <p>{{post.content}}</p>
{% endblock %}

However, when I try sending HTML, it just shows as it was inputed (<h1>Hello</h1> justs shows as it is instead of making it a heading). Additionally, If I try inputting multiple lines, it just shows as one long line in the output.

How do I display the inputted text as HTML?

Your html is automatically escaped by jinja for security reasons. It's not always a good idea to have {% autoescape %} set to false or {{ something | safe }} unless whatever you are escaping is something you created yourself or someone you trust, otherwise you could put yourself and users under the treat of attacks such as XSS. What you need is a WYSIWYG such as Quill, Summernote, ckeditor or anyone of your choice, and use something such as the bleach package to clean and sanitize whichever parts of the html you are getting.

I have created a Flask-Blog with a WYSIWYG editor, Quill, with the bleach package in the backend for sanitizing. If you'd like to take a look on how they are implemented, refer to this Flask-Blog

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM