I am trying to save all exceptions thrown by a python service (running hidden on Windows 7/10) into a sqlite3 database file. In addition to other things(traceback, date, etc) I want to save the error message too.
My Problem is that there are some error messages that I cannot convert to unicode (Especially some WindowsErrors and errors with a german 'Umlaut': ä, ö, ü). As I don't know every possible error in advance I want to have a function that can handle ALL errors and convert their message to unicode.
Can someone tell me what the convertToUnicode-function has to look like?
# -*- coding: utf-8 -*-
def someErrorneousFunction():
raise RuntimeError('Not a unicode string. But with a german Umlaut: ä!')
def saveExceptionToDBThatOnlyAcceptsUnicode(msg):
"""SQL INSERT SOME STUFF... + THE UNICODE ERROR MESSAGE!"""
pass
def convertToUnicode(e):
""" What to do here ??? """
pass
try:
someErrorneousFunction()
except Exception as e:
unicode_error_msg = convertToUnicode(e)
saveExceptionToDBThatOnlyAcceptsUnicode(unicode_error_msg)
Note: I found that some Exceptions have an attribute called .msg or .str, but not all of them!
Does this method make sense at all? I know its bad practice to catch ALL exceptions with no distinction but as my software occasionally is in testmode somewhere else and I want to get the exception database per mail it seemed meaningful to me. Furthermore I distinguish the errors I know from those I don't know in advance.
I would appreciate any advise!
Thank you!
Sebastian
If, as your demo shows, the source file is known to be in UTF-8, then this should work:
# -*- coding: utf-8 -*-
import traceback
def someErrorneousFunction():
raise RuntimeError('Not a unicode string. But with a german Umlaut: ä!')
def saveExceptionToDBThatOnlyAcceptsUnicode(msg):
print type(msg)
print msg
def convertToUnicode(e):
return traceback.format_exc(e).decode('utf8')
try:
someErrorneousFunction()
except Exception as e:
unicode_error_msg = convertToUnicode(e)
saveExceptionToDBThatOnlyAcceptsUnicode(unicode_error_msg)
Output:
<type 'unicode'>
Traceback (most recent call last):
File "C:\test.py", line 15, in <module>
someErrorneousFunction()
File "C:\test.py", line 5, in someErrorneousFunction
raise RuntimeError('Not a unicode string. But with a german Umlaut: ä!')
RuntimeError: Not a unicode string. But with a german Umlaut: ä!
Related
I try to use TLorentz vector in uproot4.
But I found that methods in "uproot_methods" module are now worked with Awkward High level array.
Error message # -------------------------------------------->
Traceback (most recent call last):
File "/home/jwkim/anaconda3/lib/python3.8/site-packages/awkward/array/base.py", line 389, in _util_toarray
return cls.numpy.frombuffer(value, dtype=getattr(value, "dtype", defaultdtype)).reshape(getattr(value, "shape", -1))
TypeError: a bytes-like object is required, not 'Array'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "anal.py", line 19, in
Electron_T2vec = TVector2Array.from_polar(Electron_pt,Electron_phi)
File "/home/jwkim/anaconda3/lib/python3.8/site-packages/awkward/util.py", line 112, in func_wrapper
wrap, arrays = unwrap_jagged(cls, awkcls, _normalize_arrays(cls, arrays))
File "/home/jwkim/anaconda3/lib/python3.8/site-packages/awkward/util.py", line 84, in _normalize_arrays
arrays[i] = cls.awkward.util.toarray(arrays[i], cls.awkward.numpy.float64)
File "/home/jwkim/anaconda3/lib/python3.8/site-packages/awkward/util.py", line 32, in toarray
return awkward.array.base.AwkwardArray._util_toarray(value, defaultdtype, passthrough=passthrough)
File "/home/jwkim/anaconda3/lib/python3.8/site-packages/awkward/array/base.py", line 394, in _util_toarray
return cls.numpy.array(value, copy=False)
File "/home/jwkim/anaconda3/lib/python3.8/site-packages/awkward1/highlevel.py", line 1310, in array
return awkward1._connect._numpy.convert_to_array(self._layout, args, kwargs)
File "/home/jwkim/anaconda3/lib/python3.8/site-packages/awkward1/_connect/_numpy.py", line 16, in convert_to_array
out = awkward1.operations.convert.to_numpy(layout, allow_missing=False)
File "/home/jwkim/anaconda3/lib/python3.8/site-packages/awkward1/operations/convert.py", line 313, in to_numpy
return to_numpy(array.toRegularArray(), allow_missing=allow_missing)
ValueError: in ListOffsetArray64, cannot convert to RegularArray because subarray lengths are not regular
--------------------------------------------------> ##
It seems that "uproot_method" only support the awkward.array.jagged.JaggedArray.
Is there any other way to use the TLorentz vector in uproot4 (awkward high level array)?
I'm trying to convert this uproot3 and awkward0 based code to uproot4 and awkward1 based code.
https://github.com/JW-corp/J.W_Analysis/blob/main/Uproot/anal.py
Thank youy!
The uproot-methods package only works with Uproot 3.x and therefore Awkward Array 0.x. In the Uproot 4/Awkward 1 world, the methods for ROOT objects that uproot-methods once provided are now handled by Uproot itself (the "community contributed project" didn't work out, so this functionality is moving back into Uproot), except for Lorentz vectors.
The eventual home for Lorentz vector handling is the vector project, which I'll be contributing to in March. Here it is, almost March, and so that will be happening soon. (I have one last task before working on that.)
In the meantime, the excellent Coffea project has a module for Lorentz-vector handling: coffea.nanoevents.methods.vector. To get started with Lorentz vectors now, I recommend that.
(The standalone vector package would become Uproot's default vector handler, as in, if you read a TLorentzVector from a ROOT file, it will have vector methods automatically—when vector is finished, that is.)
I'm having trouble deploying a flask app to the Google app engine. It works fine when I run it locally but as soon as it's deployed to the app engine it fails. With two exceptions (I'm always getting both, I'm unsure which one comes first).
Traceback (most recent call last):
File "/opt/python3.7/lib/python3.7/logging/handlers.py", line 1008, in emit
smtp = smtplib.SMTP(self.mailhost, port, timeout=self.timeout)
File "/opt/python3.7/lib/python3.7/smtplib.py", line 251, in __init__
(code, msg) = self.connect(host, port)
File "/opt/python3.7/lib/python3.7/smtplib.py", line 338, in connect
(code, msg) = self.getreply()
File "/opt/python3.7/lib/python3.7/smtplib.py", line 391, in getreply
+ str(e))
smtplib.SMTPServerDisconnected: Connection unexpectedly closed: timed out
and
Traceback (most recent call last):
File "/opt/python3.7/lib/python3.7/smtplib.py", line 387, in getreply
line = self.file.readline(_MAXLINE + 1)
File "/opt/python3.7/lib/python3.7/socket.py", line 589, in readinto
return self._sock.recv_into(b)
socket.timeout: timed out
It consistently happens within the __init__ function of a form. And specifically in there when I try to append a validator to a validators list.
self.password.validators.append(InputRequired(message='Please enter password!'))
It is not specific to this one validator, the same thing happens with others too. I am at a complete loss as to why and how appending validators would interact with SMTP or sockets.
One thing I noticed is that I had an issue with the Email validator which also worked fine locally but required me to install the module 'email_validator' to work. When I did that it complained that it couldn't use append on a tuple when I tried to append a validator to - what was a list in my local app - but for some reason turned out to be a tuple when I ran the exact same code on the app engine. I removed the Email validator (and the import/requirements) entirely and now I'm at the problem I've described above. It may or may not be related to the Email validator issue.
Update: The error message does indeed seem to be related to the validators.append() call seeing as by setting up the validators at object creation and avoiding all further changes via validators.append() fixed the problem for me. This is the requirements.txt that goes with the application:
blinker>=1.4
Click>=7.0
Flask>=1.1.1
Flask-Login>=0.5.0
Flask-Mail>=0.9.1
Flask-SQLAlchemy>=2.4.1
Flask-WTF>=0.14.3
itsdangerous>=1.1.0
Jinja2>=2.11.1
MarkupSafe>=1.1.1
PyJWT>=1.7.1
PyMySQL>=0.9.3
python-dotenv>=0.11.0
SQLAlchemy>=1.3.13
Werkzeug>=1.0.0
WTForms>=2.2.1
Instead of a full minimal, reproducible example I can offer a minimized version of the form that was causing the issues when instanciated on the GAE:
class ExampleForm(FlaskForm):
name = StringField('Name')
original_name = HiddenField('Original Name')
def add_validators(self):
names = [a.name for a in Users.query.all()]
if self.original_name.data:
names.remove(self.original_name.data)
self.name.validators.append(InputRequired(message='Please enter name!'))
self.name.validators.append(NoneOf(names, message='Username already exists!'))
def __init__(self):
super().__init__(*args, **kwargs)
self.add_validators()
As I'm writing this it occurs to me that maybe I need to always initialize an empty validators list on creation to ensure new entries can be appended to it (like with a normal list) like this name = StringField('Name', validators=[]). I'd still be confused as to why it works locally, but if it fixes the problem that'd be what really counts for me.
I'm using pydicom (installed with pip3, on python 3.7, using Idle) and I need to access pixel_array values.
I just copy-paste the example provided into the documentation and this leads to two errors:
first is about the get_testdata_files operation, which is not working because
Python 3.7.3 (v3.7.3:ef4ec6ed12, Mar 25 2019, 22:22:05) [MSC v.1916 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license()" for more information.
>>>
==================== RESTART: D:\OneDrive\Desktop\test.py ====================
None
Traceback (most recent call last):
File "D:\OneDrive\Desktop\test.py", line 8, in <module>
filename = get_testdata_files("bmode.dcm")[0]
IndexError: list index out of range
I have solved this not using this operation.
second is about the pixel_array and I'm not so able to decode what is wrong, but it seems like the pixel_array is not populated. However I'm able to access other fields in the dataset and the file can be displayed (using ImageJ for example).
==================== RESTART: D:\OneDrive\Desktop\test.py ====================
None
Filename.........: bmode.dcm
Storage type.....: 1.2.840.10008.5.1.4.1.1.3.1
Patient's name...: Femoral trombenarterectomy, Case Report:
Patient id.......: Case Report 1
Modality.........: US
Study Date.......: 20110824
Image size.......: 768 x 1024, 27472108 bytes
Slice location...: (missing)
Traceback (most recent call last):
File "D:\OneDrive\Desktop\test.py", line 38, in <module>
plt.imshow(dataset.pixel_array, cmap=plt.cm.bone)
File "C:\Users\marcl\AppData\Local\Programs\Python\Python37\lib\site-packages\pydicom\dataset.py", line 949, in pixel_array
self.convert_pixel_data()
File "C:\Users\marcl\AppData\Local\Programs\Python\Python37\lib\site-packages\pydicom\dataset.py", line 895, in convert_pixel_data
raise last_exception
File "C:\Users\marcl\AppData\Local\Programs\Python\Python37\lib\site-packages\pydicom\dataset.py", line 863, in convert_pixel_data
arr = handler.get_pixeldata(self)
File "C:\Users\marcl\AppData\Local\Programs\Python\Python37\lib\site-packages\pydicom\pixel_data_handlers\pillow_handler.py", line 188, in get_pixeldata
UncompressedPixelData.extend(decompressed_image.tobytes())
File "C:\Users\marcl\AppData\Local\Programs\Python\Python37\lib\site-packages\PIL\Image.py", line 746, in tobytes
self.load()
File "C:\Users\marcl\AppData\Local\Programs\Python\Python37\lib\site-packages\PIL\ImageFile.py", line 261, in load
raise_ioerror(err_code)
File "C:\Users\marcl\AppData\Local\Programs\Python\Python37\lib\site-packages\PIL\ImageFile.py", line 58, in raise_ioerror
raise IOError(message + " when reading image file")
OSError: broken data stream when reading image file
Here is my code:
import matplotlib.pyplot as plt
import sys
import pydicom
import numpy
from pydicom.data import get_testdata_files
print(__doc__)
#filename = get_testdata_files("bmode.dcm")[0]
filename = "bmode.dcm"
dataset = pydicom.dcmread(filename)
# Normal mode:
print()
print("Filename.........:", filename)
print("Storage type.....:", dataset.SOPClassUID)
print()
pat_name = dataset.PatientName
display_name = pat_name.family_name + ", " + pat_name.given_name
print("Patient's name...:", display_name)
print("Patient id.......:", dataset.PatientID)
print("Modality.........:", dataset.Modality)
print("Study Date.......:", dataset.StudyDate)
if 'PixelData' in dataset:
rows = int(dataset.Rows)
cols = int(dataset.Columns)
print("Image size.......: {rows:d} x {cols:d}, {size:d} bytes".format(
rows=rows, cols=cols, size=len(dataset.PixelData)))
if 'PixelSpacing' in dataset:
print("Pixel spacing....:", dataset.PixelSpacing)
# use .get() if not sure the item exists, and want a default value if missing
print("Slice location...:", dataset.get('SliceLocation', "(missing)"))
# plot the image using matplotlib
plt.imshow(dataset.pixel_array, cmap=plt.cm.bone)
plt.show()
Could you help me to solve these two errors and access pixel_array values?
Don't hesitate to give me some advices /remarks/...
Thanks!
Hi Marc welcome to SO!
Your first error means that the get_testdata_files returns an empty list, so your file is not found. Have a look at the pydicom source, it shows that a search is performed in [DATA_ROOT]/test_files. Is your file located in that path?
Your second error is related to PIL and that can be quite difficult to debug and fix. First try to read the pixel_array from a dataset created from one of the supplied test files. If that works, your problem is probably that PIL cannot handle the specific encoding of your image data. You want to install and use GDCM instead of PIL to see if that solves the problem. Another user has had a similar issue as you, GDCM solved the problem. It can be a bit of a headache to get working unfortunately. Or have a look at this page, it shows some other alternatives on viewing the image data.
When I do a filter on a ForeignKey field with __isnull=True, this exception is raised:
DatabaseError: This query is not supported by the database.
However, __isnull=False on ForeignKey works as long as there are no other inequality filters (which I would expect). And __isnull=True works for other field types.
So why does __isnull=True not work on ForeignKey? It seems that DBIndexer tries to make it work as shown here:
https://github.com/django-nonrel/django-dbindexer/blob/dbindexer-1.4/dbindexer/backends.py
But then there is an exception in djangotoolbox:
File "/Users//Documents/workspace/-gae-dev/src/django/db/models/query.py", line 107, in _result_iter
self._fill_cache()
File "/Users//Documents/workspace/-gae-dev/src/django/db/models/query.py", line 774, in _fill_cache
self._result_cache.append(self._iter.next())
File "/Users//Documents/workspace/-gae-dev/src/django/db/models/query.py", line 275, in iterator
for row in compiler.results_iter():
File "/Users//Documents/workspace/-gae-dev/src/djangotoolbox/db/basecompiler.py", line 337, in results_iter
results = self.build_query(fields).fetch(
File "/Users//Documents/workspace/-gae-dev/src/djangotoolbox/db/basecompiler.py", line 428, in build_query
self.check_query()
File "/Users//Documents/workspace/-gae-dev/src/djangotoolbox/db/basecompiler.py", line 409, in check_query
raise DatabaseError("This query is not supported by the database.")
I did come across the following commented-out test case in djangoappengine, and am wondering if is referring to the same issue?
def test_is_null(self):
self.assertEquals(FieldsWithOptionsModel.objects.filter(
floating_point__isnull=True).count(), 0)
FieldsWithOptionsModel(
integer=5.4, email='shinra.tensai#sixpaths.com',
time=datetime.datetime.now().time()).save()
self.assertEquals(FieldsWithOptionsModel.objects.filter(
floating_point__isnull=True).count(), 1)
# XXX: These filters will not work because of a Django bug.
# self.assertEquals(FieldsWithOptionsModel.objects.filter(
# foreign_key=None).count(), 1)
# (it uses left outer joins if checked against isnull)
# self.assertEquals(FieldsWithOptionsModel.objects.filter(
# foreign_key__isnull=True).count(), 1)
Alex Burgel on the NonRel project set me straight:
The NonRel/dbindexer project fixes this query (which otherwise doesn't work due to this Django bug: https://code.djangoproject.com/ticket/10790). To set up dbindexer:
of course, add it to INSTALLED_APPS
also in settings.py, set DATABASES['default]['ENGINE']= 'dbindexer'
also in settings.py, set DBINDEXER_BACKENDS to use FKNullFix. For example:
DBINDEXER_BACKENDS = (
'dbindexer.backends.BaseResolver',
'dbindexer.backends.FKNullFix',
'dbindexer.backends.InMemoryJOINResolver',
'dbindexer.backends.ConstantFieldJOINResolver',
)
I'm getting this error... "ImportError: Could not find 'input_readers' on path 'map reduce'" when trying to Run my map reduce job via the http://localhost:8080/mapreduce launcher page.
It looks like my problem is similar to this post, AppEngine mapper API import error. Unfortunately, no definitive answers were given.
I've simplified it down to this tiny testmapreduce.py:
from google.appengine.ext import db
class TestEntity(db.Model):
value = db.StringProperty()
def mapperhandler(test):
print test.value
return
And my mapreduce.yaml:
mapreduce:
- name: Simplest MapReduce
mapper:
handler: testmapreduce.mapperhandler
input_reader: mapreduce.input_readers.DatastoreInputReader
params:
- name: entity_kind
default: testmapreduce.TestEntity
One possible clue is the presence of __init__.py has no effect (whether in the project root, the mapreduce directory, or both). I'm sure I'm making a beginner mistake, but over the last couple of days I have read every bit of documentation, and all the examples I can find. Thanks.
UPDATE:
I get the same error trying to invoke it via...
control.start_map(
"Give awards",
"testmapreduce.mapperhandler",
"mapreduce.input_readers.DatastoreInputReader",
{"entity_kind": "testmapreduce.TestEntity"},
shard_count=10)
UPDATE:
As requested, the stack trace -- let me know what else would be helpful...
ERROR 2011-10-16 17:09:27,216 _webapp25.py:464] Could not find 'input_readers' on path 'mapreduce'
Traceback (most recent call last):
File "/Develop/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/google/appengine/ext/webapp/_webapp25.py", line 701, in __call__
handler.get(*groups)
File "/Users/lc/PycharmProjects/mrtest/testmapreduce.py", line 22, in get
shard_count=10) # handle web form test interface
File "/Users/lc/PycharmProjects/mrtest/mapreduce/control.py", line 94, in start_map
transactional=transactional)
File "/Users/lc/PycharmProjects/mrtest/mapreduce/handlers.py", line 811, in _start_map
mapper_input_reader_class = mapper_spec.input_reader_class()
File "/Users/lc/PycharmProjects/mrtest/mapreduce/model.py", line 393, in input_reader_class
return util.for_name(self.input_reader_spec)
File "/Users/lc/PycharmProjects/mrtest/mapreduce/util.py", line 94, in for_name
module = for_name(module_name, recursive=True)
File "/Users/lc/PycharmProjects/mrtest/mapreduce/util.py", line 102, in for_name
short_name, module_name))
ImportError: Could not find 'input_readers' on path 'mapreduce'
INFO 2011-10-16 22:09:27,253 dev_appserver.py:4247] "GET /giveawards HTTP/1.1" 500 -
This problem turned out to be that I was using the 2.7 version of the Python Interpreter in my local environment. When I switched to 2.5, it works fine.