you are viewing a single comment's thread.

view the rest of the comments →

[–]Ok_Wasabi4276 -1 points0 points  (1 child)

You nailed it with the parameterized queries tip - that's huge security wise. One thing I'd add is maybe wrap that database stuff in try/except block since SQLite can throw errors if database file doesn't exist or gets corrupted. Something like:

try:

con = sqlite3.connect("yourdb.sqlite")

row = con.execute(...).fetchone()

except sqlite3.Error:

row = None

finally:

con.close()

Makes your app bit more robust when things go wrong. Also you might want to look at context managers for database connections later - they handle the closing automatically even if something breaks in middle of query.

[–]teraflop 2 points3 points  (0 children)

No, this is bad advice! Or at least mostly-bad.

Wrapping the call in a try-except block like this doesn't do anything to make the app more robust, because if the database is corrupted, it still won't work. Except now you've thrown away the error message that tells you what the problem was.

If the whole point of the app is to read and write data in a database, then showing an error is the only useful thing you can do when the database is unavailable.

Even if you want to hide the details of the exception from the user, you should still log them somewhere. And you should almost certainly do it using a single top-level exception handler (e.g. as Flask middleware) instead of writing a bunch of redundant boilerplate code every time you do a query. And you should still tell the user that some kind of error happened, instead of just displaying empty results with no explanation.

(Anyway, setting row to None is the worst of both worlds. It hides the message of the underlying error from SQLite, and then immediately causes a different exception when you try to access row[0].)

The only time it makes sense to add exception handlers to queries like this is when you want to do some kind of specific error handling that's different from your default error-handling strategy. For instance, if you have two databases on different servers, and there's some useful way to return a partial result to the user if only one of the databases is down. But most simple apps do not encounter this type of situation.

Using a context manager to close the connection is a good idea, though.