I have a view in flask that I want to use to display success when an object from a POST request is successfully committed.
In the controller, I have
us = User(data_that_is_not_valid)
db_session.add(us)
db_session.commit()
As of now, db_commit() throws an exception when the object can't be committed. Is there a more friendly way that just returns true or false to specify whether the object has been added to the database without throwing an error?
EDIT: Added copy of exception
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/local/lib/python2.7/dist-packages/SQLAlchemy-0.8.0-py2.7-linux-x86_64.egg/sqlalchemy/orm/scoping.py", line 149, in do
return getattr(self.registry(), name)(*args, **kwargs)
File "/usr/local/lib/python2.7/dist-packages/SQLAlchemy-0.8.0-py2.7-linux-x86_64.egg/sqlalchemy/orm/session.py", line 719, in commit
self.transaction.commit()
File "/usr/local/lib/python2.7/dist-packages/SQLAlchemy-0.8.0-py2.7-linux-x86_64.egg/sqlalchemy/orm/session.py", line 350, in commit
self._assert_active(prepared_ok=True)
File "/usr/local/lib/python2.7/dist-packages/SQLAlchemy-0.8.0-py2.7-linux-x86_64.egg/sqlalchemy/orm/session.py", line 192, in _assert_active
% self._rollback_exception
sqlalchemy.exc.InvalidRequestError: This Session's transaction has been rolled back due to a previous exception during flush. To begin a new transaction with this Session, first issue Session.rollback(). Original exception was: (IntegrityError) column email is not unique u'INSERT INTO users (name, email, password) VALUES (?, ?, ?)' ('test', 'test#test.com', 'test')
Your data should be prepared anyway. But this case is not data format case
And exception is always good, you just need to catch and use them
You should consider exception as returned False, also you should log the reason for fail for later solving of problem
failed=False
try:
db_session.commit()
except Exception as e:
#log your exception in the way you want -> log to file, log as error with default logging, send by email. It's upon you
db_session.rollback()
db_session.flush() # for resetting non-commited .add()
failed=True
#some use of failed var, specific for your case if you need it
For better understanding of exceptions: Exceptions python docs
As for your specific exception looks like autocommit is your issue. Or not commited some previous SQL operation: Sqlalchemy docs
Related
try:
df1=spark.read.format("delta").load("/abc")
except Exception as ex:
print(ex)
its giving exception as '/abc' is not a Delta table.;
I want to perform a specific operation when the file is not found.
Is there a class already available to catch it separately like FileNoTFoundException - which doesn't seem to work here.
In pyspark 3.x, a nonexisting table will throw the generic pyspark.sql.utils.AnalysisException.
This is translated from the Java/Scala layer. Unfortunately there doesn't exist an exception specific to "File Not Found".
from pyspark.sql.utils import AnalysisException
try:
spark.read.format("delta").load("/abc")
except AnalysisException as ex:
print(ex)
I'm making a custom plugin to query a database for user info to aide customer support. My backend is slack.
Everytime I start the bot command I'm greeted with:
Computer says nooo. See logs for details:
catching classes that do not inherit from BaseException is not allowed
I'm not sure if this is warning me that I'm attempting to catch an exception that isn't a BaseClass in my code or if an unknown exception was raised and caught elsewhere outside of my plugin.
To debug I tried:
try:
do_the_thing()
except (TypeError, ValueError) as e:
return('Something went wrong.')
I also tried:
try:
do_the_thing()
except Exception as e:
return('Something went wrong.')
And I still get the errbot admonition. Note that the command still runs and does the right thing where there is no exception raised by do_the_thing().
It means that:
Somewhere in your code you have an except ... statement where the exception ... (or one of the exceptions in the sequence ...) is not a subclass of BaseException, and
An exception is being thrown that is caught by that except ... statement.
The TypeError can be raised only when an exception is actually thrown because the names you give to except ... must be evaluated for their current values at that time; just because TypeError referenced a particular class at one point in the program's execution doesn't mean it won't be changed later to reference another object (though that would be admittedly perverse).
The Python interpreter should be giving you a full traceback of the exception; the first thing you need to do is find this. It could be occurring in one of two situations. (This is for single-threaded programs; I'm assuming your program is not multithreaded.)
During the execution of your program, in which case the program will be terminated by the exception, or
During finalization of objects (in their __del__(self) functions) in which case the error will be printed to stderr.
In both cases there should be a stack trace, not just the error message; I've confirmed that at least on Python ≥3.4 a stack trace is printed out for case 2.
You then need to follow this stack trace to see where the problem lies. Remember that the names you give to except ... are variables (even things like TypeError) that can be reassigned, so that you could conceivably be dealing with a (perverse) situation like:
TypeError = False
try:
...
except TypeError:
...
But more likely it will be something obvious such as:
class MyException: # Doesn't inherit from Exception
...
try:
...
except MyException:
...
There is one special case you need to be aware of: if you are seeing messages to stderr (case "2. During finalization," above) printed out as your program exits that means that the exception was thrown during cleanup as the interpreter shuts down, where random variables throughout the program may have already been set to None as part of the cleanup process. But in this case your program should still exit successfully.
So I'm new to python and am trying to put some data into a DB using Sqlite.
The data is a JSON with a list of dictionaries. The last entry of every dictinary is another list with dictionaries (see data below for first entry in the file). Pulling the data out of each dictionary in the list is fine except for the last part (that is a list of dictionaries). I can't get the itterating over it right. I put it into a function in my code to be able to call diferent url's (the error message still refers to 'WriteToFactionSpread', the name of the function)
Data: https://eddb.io/archive/v5/systems_populated.json
My code:
uh = urllib.urlopen(url)
input = json.loads(uh.read())
cur.execute('''CREATE TABLE IF NOT EXISTS FactionSpread(minor_faction_id
INTEGER PRIMARY KEY, state_id INTEGER, influence INTEGER, state TEXT)''')
conn.commit()
for i in input:
cur.execute('''INSERT INTO FactionSpread (minor_faction_id, state_id, influence, state )VALUES (?, ?, ?, ?)''', (i['minor_faction_presences'][0]['minor_faction_id'], i['minor_faction_presences'][1]['state_id']
, i['minor_faction_presences'][2]['influence'], i['minor_faction_presences'][3]['state']))
conn.commit()
uh.close()
Error:
Traceback (most recent call last):
File "E:\Python\EliteDangerous\trial.py", line 34, in <module>
WriteToFactionSpread(ab)
File "E:\Python\EliteDangerous\trial.py", line 27, in WriteToFactionSpread
(i['minor_faction_presences'][0]['minor_faction_id']))
ValueError: parameters are of unsupported type
(I hope the formatting isn't too messed up copy/pasting it here, but I think it'll be ok).
I didn't copy paste in the actual data because it would crowd it up a bit but the link goes to a JSON file with data from the game Elite Dangerous.
Tried some different ways but I'm at a loss at the moment, I'm still green.
I have the following code in Erlang, in which I'm mecking an nonexistent module.
In some versions of Erlang/meck this generates an exception that seems uncatchable.
Anyone knows if there is an "uncatchable exception" feature in Erlang ?
try
meck:new(i_dont_exist),
io:format("No exception in this version of Erlang ... :( "),
no_problems
catch
exit:_ -> exit;
error:_ -> error;
throw:_ -> throw;
_:_ -> what_class_is_it
after
io.format("in the after~n")
end.
When I execute this code this is what I get (notice that not even the "after" clause is being executed so it looks more like a bug to me):
** exception exit: {undefined_module,i_dont_exist}
in function meck_proc:resolve_can_expect/3 (src/meck_proc.erl, line 402)
in call from meck_proc:init/1 (src/meck_proc.erl, line 194)
in call from gen_server:init_it/6 (gen_server.erl, line 304)
in call from proc_lib:init_p_do_apply/3 (proc_lib.erl, line 227)
I have also tried with the "catch" expression with the same result:
> catch meck:new(i_dont_exist).
** exception exit: {undefined_module,i_dont_exist}
in function meck_proc:resolve_can_expect/3 (src/meck_proc.erl, line 402)
in call from meck_proc:init/1 (src/meck_proc.erl, line 194)
in call from gen_server:init_it/6 (gen_server.erl, line 304)
in call from proc_lib:init_p_do_apply/3 (proc_lib.erl, line 227)
What's happening here is that meck:new spawns a new process (a gen_server process using the meck_proc callback module), and that process exits with the undefined_module error. (You can get it not to do that by passing the non_strict option to meck:new.) This new process is linked to the calling process, which means that an exit signal will be sent to the calling process, and the calling process will exit as well, without being able to catch the signal.
You can avoid that by making your calling process trap exits:
process_flag(trap_exit, true)
which will turn the exit signal into a message that you can receive; see the manual for more details. However, as a general rule you should avoid trapping exits, as it makes error handling more complicated (as opposed to the default "crash, restart").
I have been bitten by something unexpected recently. I wanted to make something like that:
try :
thing.merge(iterable) # this is an iterable so I add it to the list
except TypeError :
thing.append(iterable) # this is not iterable, so I add it
Well, It was working fine until I passed an object inheriting from Exception which was supposed to be added.
Unfortunetly, an Exception is iterable. The following code does not raise any TypeError:
for x in Exception() :
print 1
Does anybody know why?
Note that what is happening is not related to any kind of implicit string conversion etc, but because the Exception class implements __getitem__ to return the values from the args tuple (ex.args). You can see this by the fact that you get the whole string as your first and only item in the iteration, rather than the character-by-character result you'd get if you iterate over the string.
This surprised me too, but thinking about it, I'm guessing it is for backwards compatibility reasons. Python used to (pre-1.5) lack the current class hierarchy of exceptions. Instead, strings were thrown, with (usually) a tuple argument for any details that should be passed to the handling block, i.e:
try:
raise "something failed", (42, "some other details")
except "something failed", args:
errCode, msg = args
print "something failed. error code %d: %s" % (errCode, msg)
It looks like this behavior was put in to avoid breaking pre-1.5 code expecting a tuple of arguments, rather than a non-iterable exception object. There are a couple of examples of this with IOError in the Fatal Breakage section of the above link
String exceptions have been deprecated for a while, and are gone in Python 3. Exception objects are no longer iterable in Python 3:
>>> list(Exception("test"))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'Exception' object is not iterable
NOT VALID. Check Brian anwser.
Ok, I just got it :
for x in Exception("test") :
print x
....:
....:
test
Don't bother ;-)
Anyway, it's good to know.
EDIT : looking to the comments, I feel like adding some explanations.
An exception contains a message you passed to during instantiation :
raise Exception("test")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
Exception: test
It's fair to say that the message is what defines the Exception the best, so str() returns it :
print Exception("test")
test
Now, it happens that Exceptions are implicitly converted to string when used in something else than an Exception context.
So when I do :
for x in Exception("test") :
print x
I am iterating over the string "test".
And when I do :
for x in Exception() :
print x
I do iterate over an empty string. Tricky. Because when it comes to my issue :
try :
thing.merge(ExceptionLikeObject)
except TypeError :
...
This won't raise anything since ExceptionLikeObject is considered as a string.
Well now, we know the HOW, but I still not the WHY. Maybe the built-in Exception inherit from the built-in String ? Because as far as I know :
adding str does not make any object iterable.
I bypassed the problem by overloding iter, making it raising TypeError !
Not a problem anymore, but still a mystery.