Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to prevent Flask (python) from emitting html?

It appears that Flask assumes that the server is returning html to the client (browser).

Here’s a simple example;

import json
from flask import Flask

app = Flask(__name__)

@app.route("/")
def home():
  msg = ['Hello, world!']
  return json.dumps(msg) + '\n'

This code works as expected and returns the desired json;

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

$ curl -s http://localhost:5000/
["Hello, world!"]

But if I introduce an error;

import json
from flask import Flask

app = Flask(__name__)

@app.route("/")
def home():
  msg = ['Hello, world!']
  return json.dumps(XXmsg) + '\n'

Then Flask emits the error wrapped in several pages worth of html, starting like;

$ curl -s http://localhost:5000/
<!DOCTYPE html>
<html>
  <head>
    <title>NameError: name 'XXmsg' is not defined
 // Werkzeug Debugger</title>
    <link rel="stylesheet" href="?__debugger__=yes&amp;cmd=resource&amp;f=style.css">
    <link rel="shortcut icon"
        href="?__debugger__=yes&amp;cmd=resource&amp;f=console.png">
    <script src="?__debugger__=yes&amp;cmd=resource&amp;f=debugger.js"></script>
    <script>
      var CONSOLE_MODE = false,
          EVALEX = true,
          EVALEX_TRUSTED = false,
          SECRET = "Mq5TSy6QE4OuOHUfvk8b";
    </script>
  </head>
  <body style="background-color: #fff">
    <div class="debugger">

Emitting html makes sense if you’re creating a page load app. But I’m creating an api that only returns json.

Is there anyway to prevent Flask from emitting html at all?

Thanks
Mike

>Solution :

Have a look at the section Returning API Errors as JSON of the Flask docs.

Basically, you have to replace the default error handler with a function that returns the error as json. A very basic example:

@app.errorhandler(HTTPException)
def handle_exception(exception):
    response = exception.get_response()
    response.content_type = "application/json"
    response.data = json.dumps({"code": exception.code})
    return response
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading