Output Multi-line strings with Python Flask or other framework Output Multi-line strings with Python Flask or other framework flask flask

Output Multi-line strings with Python Flask or other framework


Both Bottle and Flask can handle multi-line strings just fine. Your issue is that your data is being interpreted as text/html by default and in HTML any combination of whitespace is collapsed into a single space when displayed. In order to ensure that your data comes back exactly as you sent it you'll want to set the Content-Type header to text/plain.

In Flask:

# If you want *all* your responses to be text/plain# then this is what you want@app.after_requestdef treat_as_plain_text(response):    response.headers["content-type"] = "text/plain"    return response# If you want only *this* route to respond# with Content-Type=text/plain@app.route("/plain-text")def a_plain_text_route():    response = make_response(getKickstartFile())    response.headers["content-type"] = "text/plain"    return response

In Bottle:

@route("/plain-text")def plain_text():    response.content_type = "text/plain"    return """This              multi-line string              will show up              just fine"""


Sean's answer is the correct way to go, but if you just want to test something you could use the xmp tag:

@app.route("/"):def hello():    return """<xmp>              Hello,              Multiline!              </xmp>"""

decorator version

You could also create your own decorator for this:

from functools import wrapsdef multiline(fn):    @wraps(fn)    def _fn(*args, **kwargs):        return "<xmp>" + fn(*args, **kwargs) + "</xmp>"    return _fn

Then you can do:

    @app.route("/"):    @multiline    def hello():    return """Hello,              Multiline!"""