Unable to push test user to SQLite DB

I am trying to add a test user to the user table within my sqlite db that is a part of a website. When trying to add the test user, I get a TypeError shown here:

TypeError: The view function did not return a valid response. The return type must be a string, dict, list, tuple with headers or status, Response instance, or WSGI callable, but it was a TypeError.

Full code is shown here:

from flask import Flask
from flask import render_template
from flask import redirect
from flask import url_for
from flask_sqlalchemy import SQLAlchemy

app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///users_db.db'
app.secret_key = "secret"
db = SQLAlchemy(app)

class User(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(20), unique=False, nullable=False)
    email = db.Column(db.String(), unique=True, nullable=False)
    password = db.Column(db.String(), unique=False, nullable=False)

    def __repr__(self):
        return f"User('{self.username}', '{self.email}', '{self.id}')"


@app.route("https://stackoverflow.com/")
def home():
    return render_template('home.html')

@app.route('/test_db')
def test_db():
    try:
        test_user = User(username="TestUser", email="[email protected]", password='testpassword')
        db.session.add(User(test_user))
        db.session.commit()
        return "Test Passed"
    except Exception as e:
        return e

if __name__ == "__main__":
    with app.app_context():
        db.create_all()
    app.run(debug=False)

  • 1

    What line did the error come from? The error should have included a stack trace.

    – 




  • Trace back point to lines like line 1800, 1506, not sure why ti says that

    – 

  • Scan through the stack trace for your own file. Find the last one before the call stack dives into Flask. Is it perhaps from calling test_db? Is the return e in the stack?

    – 




  • ERROR in app: Exception on /test_db [GET] Traceback (most recent call last): line 2190, in wsgi_app ine 1487, in full_dispatch_request line 1506, in finalize_request line 1837, in make_response

    – 

The problem is

    except Exception as e:
        return e

This is returning the exception object, but this is not a valid type for a route function to return.

The simple fix is to convert the exception to a string:

    except Exception as e:
        return str(e)

However, in a production application you generally shouldn’t expose internal error messages to the user. It would be better to use the logging module to log messages, and return a generic error message string

    except Exception as e:
        logging.error(str(e))
        return 'An internal error occurred'

The error is likely from a call to test_db via flask. It can return an Exception (TypeError is an Exception). Methods implementing Flask routes must return a response, and exceptions aren’t responses.

It’s probably best to just let the exception happen and use its information for debugging, then add real error handling later if necessary.

@app.route('/test_db')
def test_db():
    test_user = User(username="TestUser", email="[email protected]", password='testpassword')
    db.session.add(User(test_user))
    db.session.commit()
    return "Test Passed"

Leave a Comment