handling of view syntax error vs exceptions in django - python

I am using django 1.2.7 and python 2.6.
If I use this code: (with an identation error on porpuse)
def myview(request):
try:
if x:
print 'x'
except:
return HttpResponseServerError('bazinga')
then I don't get my response. I get django 500 response.
but if I change the code to this:
def myview(request):
try:
if x:
print 'x'
except:
return HttpResponseServerError('bazinga')
now I get my own 500 with the bazinga written.
How can I catch the identation error in the first example ?
Just as my try-except catch the exception in the 2nd example.

Don't try to make Django return a nice response in the case of a syntax error. That will be difficult, and will involve having code of your own just for this case, and that code itself will need to be error-free, etc.
Instead, put that effort into an automated test suite that will make it easy to find those errors before you deploy your code.

Syntax errors can be detected trivially as you don't need to run the code but only to import it.
There's no reason you should try to catch them, just fix them.

You can catch syntax (And Indentation) errors out of your code.
Look here for more info:
How to catch IndentationError

Syntax errors are not run time errors, they occur at compile time. As far as I know, you can't catch them with a try/except block.

Related

How to catch exception clickhouse_driver dbapi?

I want to catch exception while executing scipts/connecting to base using clickhouse_driver-drive dbapi.
Can I catch errors codes and errors message like
errorcodes.lookup(e.pgcode)
and
e.diag.message_primary
from
psycopg2.import errorcodes?
Assuming you're using the most well known clickhouse-driver from here: https://pypi.org/project/clickhouse-driver (GitHub here: https://github.com/mymarilyn/clickhouse-driver), you must catch standard exceptions/errors. Most errors are defined in the clickhouse_driver.connection module, and they include socket errors, EOF errors, and other lower level errors.
Even though the dbapi for that project defines exception classes, none of them are actually used in the code. The driver does not in any way use the errors or error codes from the PostgreSQL psycopg2 project.

How to handle syntax Errors

So, we had instance in the past where code were broken in IOT devices because of syntax errors.
While there is exception handling in the code. I wanted to create a script to check and make sure that the codes compiles and run without syntax error, else the script replace the broken code by an earlier version.
I tried this
from delta_script import get_update
def test_function():
try:
get_update()
except SyntaxError as syntaxError:
replace_script("utility.py", syntaxError)
except Exception as ignored:
pass
However the problem it when it hit a SyntaxError, it just throw it on the screen and replace_script
because the exception happens on delta_script.py from which get_update() was imported.
So what's the solution in this case?
I have also another function
def compile():
try:
for file in compile_list:
py_compile.compile(file)
except Exception as exception:
script_heal(file, exception)
however in this one, it never report any exception, because I go and introduce syntaxError and the code still compile without reporting an error
Any one could help me figure out a better way to solve those two problems?
thanks,
SyntaxErrors occur at compile time, not run time, so you generally can't catch them. There are exceptions, involving run time compilation using eval/exec, but in general, except SyntaxError: is nonsensical; something goes wrong compiling the code before it can run the code that sets up the try/except to catch the error.
The solution is to not write syntactically invalid code, or if you must write it (e.g. to allow newer Python syntax only when supported) to evaluate strings of said code dynamically with eval (often wrapping compile if you need something more complicated than a single expression) or exec.

TransactionManagementError:This is forbidden when an 'atomic' block is active while running unit test cases

I am getting this error while I am trying to run unit test case using pytest.
It works fine in my project but raises an error while running test case.
My code is as following:
def saveEvents(request, request_data):
transaction.set_autocommit(autocommit=False)
try:
# here is my code
except Exception as inst:
transaction.rollback()
# code
transaction.commit()
return something
I read all the solutions of this type of questions, but I am puzzled why its not working with pytest. Please help.
If you are testing code that manually manages transactions, you should mark your test as follows:
#pytest.mark.django_db(transaction=True)
def my_test():
...
See the pytest-django docs for more info.
Note that you may be able to restructure your code and use with transaction.atomic(): inside a try.. except block instead of doing manual transaction management. See the Django docs for examples.

PYPY translate exception

I'm trying to generate from a simple python named test.py script the c code,
the command that I'm using is:
python rpython --source ~/work/test.py.
I don't get what I'm doing wrong because from the exception that I received in the output I don't understand much :
Exception: file '/work/test.py' is not a valid targetxxx.py.
Any idea what should i do to avoid the exception?
I had a similar issue; what fixed it for me was adding the target function to my main script:
def target(*args):
return entry_point, None
hope it helps :)

trapping a MySql warning

In my python script I would like to trap a "Data truncated for column 'xxx'" warning durnig my query using MySql.
I saw some posts suggesting the code below, but it doesn' work.
Do you know if some specific module must be imported or if some option/flag should be called before using this code?
Thanks all
Afeg
import MySQLdb
try:
cursor.execute(some_statement)
# code steps always here: No Warning is trapped
# by the code below
except MySQLdb.Warning, e:
# handle warnings, if the cursor you're using raises them
except Warning, e:
# handle warnings, if the cursor you're using raises them
Warnings are just that: warnings. They get reported to (usually) stderr, but nothing else is done. You can't catch them like exceptions because they aren't being raised.
You can, however, configure what to do with warnings, and turn them off or turn them into exceptions, using the warnings module. For instance, warnings.filterwarnings('error', category=MySQLdb.Warning) to turn MySQLdb.Warning warnings into exceptions (in which case they would be caught using your try/except) or 'ignore' to not show them at all. You can (and probably should) have more fine-grained filters than just the category.
Raise MySQL Warnings as errors:
import warnings, MySQLdb
warnings.filterwarnings('error', category=MySQLdb.Warning)
To ignore instead of raising an error, replace "error" with "ignore".
Handle them in a try-except block like:
try:
# a MySQL DB operation that raises a warning
# for example: a data truncated warning
except Warning as a_warning:
# do something here
I would try first to set the sql_mode. You can do this at the session level. If you execute a:
SET ##sql_mode:=TRADITIONAL;
(you could also set it at the server level, but you need access to the server to do that. and, that setting an still be overridden at the session level, so the bottom line is, always set it at the session level, immediately after establishing the connection)
then many things that are normally warnings become errors. I don't know how those manifest themselves at the python level, but the clear advantage is that the changes are not stored in the database. See: http://dev.mysql.com/doc/refman/5.1/en/server-sql-mode.html#sqlmode_traditional
If you want to trap it to ignore it see "Temporarily suppressing warnings" in Python's documentation:
https://docs.python.org/2/library/warnings.html#temporarily-suppressing-warnings
import warnings
with warnings.catch_warnings():
warnings.simplefilter("ignore")
# Put here your query raising a warning
Else, just read the doc about "warnings" module of Python, you can transform them into exception if you want to catch them later, etc... it's all here: https://docs.python.org/2/library/warnings.html
Just to add to Thomas Wouters reply, there is no need to import the warnings module to turn them into errors. Just run your script with "-W error" (or ignore) as flag for Python.
Have you tried using MySQL's SHOW WARNINGS command?
Stop using MySQLdb. It has such stupid behavior as truncating data and issuing only a warning. Use oursql instead.

Categories