Related
I'm unittesting token creation (think PyJWT) and I need to test if
expired token raises exception:
from jwt.exceptions import ExpiredSignatureError
def test_invalid_logout_expired_token(self):
add_user('testuser', 'testemail#mail.com', 'hakunamatata')
current_app.config['TOKEN_EXPIRATION_SECONDS'] = -1
with self.client:
resp_login = self.client.post(
'/auth/login',
data=json.dumps({
'email': 'testemail#mail.com',
'password': 'hakunamatata'
}),
content_type='application/json'
)
token = json.loads(resp_login.data.decode())['auth_token']
response = self.client.get('/auth/logout', headers={'Authorization': f'Bearer {token}'})
data = json.loads(response.data.decode())
self.assertRaises(ExpiredSignatureError, data) # <-- isn't working
exception is raised correctly:
File "/usr/src/app/project/api/auth.py", line 90, in logout
resp = User.decode_auth_token(auth_token)
File "/usr/src/app/project/api/models.py", line 45, in decode_auth_token
return jwt.decode(token, current_app.config.get('SECRET_KEY'), algorithms=["HS256"])
File "/usr/local/lib/python3.8/site-packages/jwt/api_jwt.py", line 119, in decode
decoded = self.decode_complete(jwt, key, algorithms, options, **kwargs)
File "/usr/local/lib/python3.8/site-packages/jwt/api_jwt.py", line 106, in decode_complete
self._validate_claims(payload, merged_options, **kwargs)
File "/usr/local/lib/python3.8/site-packages/jwt/api_jwt.py", line 142, in _validate_claims
self._validate_exp(payload, now, leeway)
File "/usr/local/lib/python3.8/site-packages/jwt/api_jwt.py", line 177, in _validate_exp
raise ExpiredSignatureError("Signature has expired")
jwt.exceptions.ExpiredSignatureError: Signature has expired
but test runner gives error:
test_invalid_logout_expired_token (test_auth.TestAuthBlueprint) ... ERROR
What is the right way to go about it ?
Update:
def test_invalid_logout_expired_token(self):
add_user('testuser', 'testemail#mail.com', 'hakunamatata')
current_app.config['TOKEN_EXPIRATION_SECONDS'] = -1
with self.client:
resp_login = self.client.post(
'/auth/login',
data=json.dumps({
'email': 'testemail#mail.com',
'password': 'hakunamatata'
}),
content_type='application/json'
)
token = json.loads(resp_login.data.decode())['auth_token']
self.assertRaises(ExpiredSignatureError, User.decode_auth_token(token))
User class:
class User:
...
#staticmethod
def decode_auth_token(token):
return jwt.decode(token, current_app.config.get('SECRET_KEY'), algorithms=["HS256"])
Replaced data with User.decode_auth_token().
I am using django-pghistory 1.2.0 to keep my changes using postgres triggers. For insert or update, it saves data to event table for both ORM and raw queries. But while using delete, it throws errors.
My model:
#pghistory.track(
pghistory.AfterInsert('after_insert'),
pghistory.AfterUpdate('after_update'),
pghistory.BeforeDelete('before_delete')
)
class TestModel(models.Model):
int_field = models.IntegerField()
char_field = models.CharField(max_length=16)
Error:
psycopg2.errors.ObjectNotInPrerequisiteState: record "new" is not assigned yet
DETAIL: The tuple structure of a not-yet-assigned record is indeterminate.
CONTEXT: SQL statement "INSERT INTO "loan_mngmt_app_testmodelevent"
("int_field", "char_field", "id", "pgh_created_at", "pgh_label", "pgh_obj_id", "pgh_context_id") VALUES (OLD."int_field", OLD."char_field", OLD."id", NOW(), 'before_delete', NEW."id", _pgh_attach_context())"
PL/pgSQL function pgtrigger_before_delete_f0f49() line 14 at SQL statement
django.db.utils.OperationalError: record "new" is not assigned yet
DETAIL: The tuple structure of a not-yet-assigned record is indeterminate.
CONTEXT: SQL statement "INSERT INTO "loan_mngmt_app_testmodelevent"
("int_field", "char_field", "id", "pgh_created_at", "pgh_label", "pgh_obj_id", "pgh_context_id") VALUES (OLD."int_field", OLD."char_field", OLD."id", NOW(), 'before_delete', NEW."id", _pgh_attach_context())"
PL/pgSQL function pgtrigger_before_delete_f0f49() line 14 at SQL statement
Test API for CRUD operation:
class TestModelAPI(APIView):
def post(self, request, *args, **kwargs):
obj = TestModel.objects.create(int_field=1, char_field='c1')
obj.int_field = 2
obj.char_field = 'c2'
obj.save()
obj.delete()
return JsonResponse(
data={'message': 'success'},
status=200,
)
My INSTALLED_APPS:
INSTALLED_APPS = [
.............,
'pgtrigger',
'pgconnection',
'pghistory',
]
My database settings:
DATABASES = pgconnection.configure({
"default": {
"ENGINE": "django.db.backends.postgresql",
"NAME": "<some-value>",
"USER": "<some-value>",
"PASSWORD": "<some-value>",
"HOST": "<some-value>",
"PORT": "<some-value>",
},
})
Details error:
Traceback (most recent call last):
File "/media/arif/74809FD62472EDA3/SourceCode/tkdc/venv/lib/python3.6/site-packages/django/db/backends/utils.py", line 84, in _execute
return self.cursor.execute(sql, params)
File "/media/arif/74809FD62472EDA3/SourceCode/tkdc/venv/lib/python3.6/site-packages/pgconnection/core.py", line 85, in execute
return super().execute(sql, args)
psycopg2.errors.ObjectNotInPrerequisiteState: record "new" is not assigned yet
DETAIL: The tuple structure of a not-yet-assigned record is indeterminate.
CONTEXT: SQL statement "INSERT INTO "loan_mngmt_app_testmodelevent"
("int_field", "char_field", "id", "pgh_created_at", "pgh_label", "pgh_obj_id", "pgh_context_id") VALUES (OLD."int_field", OLD."char_field", OLD."id", NOW(), 'before_delete', NEW."id", _pgh_attach_context())"
PL/pgSQL function pgtrigger_before_delete_f0f49() line 14 at SQL statement
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/media/arif/74809FD62472EDA3/SourceCode/tkdc/venv/lib/python3.6/site-packages/django/core/handlers/exception.py", line 47, in inner
response = get_response(request)
File "/media/arif/74809FD62472EDA3/SourceCode/tkdc/venv/lib/python3.6/site-packages/django/core/handlers/base.py", line 179, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/media/arif/74809FD62472EDA3/SourceCode/tkdc/venv/lib/python3.6/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view
return view_func(*args, **kwargs)
File "/media/arif/74809FD62472EDA3/SourceCode/tkdc/venv/lib/python3.6/site-packages/django/views/generic/base.py", line 70, in view
return self.dispatch(request, *args, **kwargs)
File "/media/arif/74809FD62472EDA3/SourceCode/tkdc/venv/lib/python3.6/site-packages/rest_framework/views.py", line 509, in dispatch
response = self.handle_exception(exc)
File "/media/arif/74809FD62472EDA3/SourceCode/tkdc/venv/lib/python3.6/site-packages/rest_framework/views.py", line 469, in handle_exception
self.raise_uncaught_exception(exc)
File "/media/arif/74809FD62472EDA3/SourceCode/tkdc/venv/lib/python3.6/site-packages/rest_framework/views.py", line 480, in raise_uncaught_exception
raise exc
File "/media/arif/74809FD62472EDA3/SourceCode/tkdc/venv/lib/python3.6/site-packages/rest_framework/views.py", line 506, in dispatch
response = handler(request, *args, **kwargs)
File "/media/arif/74809FD62472EDA3/SourceCode/tkdc/loan_mngmt_app/api/client_data_api.py", line 88, in post
obj.delete()
File "/media/arif/74809FD62472EDA3/SourceCode/tkdc/venv/lib/python3.6/site-packages/django/db/models/base.py", line 947, in delete
return collector.delete()
File "/media/arif/74809FD62472EDA3/SourceCode/tkdc/venv/lib/python3.6/site-packages/django/db/models/deletion.py", line 396, in delete
count = sql.DeleteQuery(model).delete_batch([instance.pk], self.using)
File "/media/arif/74809FD62472EDA3/SourceCode/tkdc/venv/lib/python3.6/site-packages/django/db/models/sql/subqueries.py", line 43, in delete_batch
num_deleted += self.do_query(self.get_meta().db_table, self.where, using=using)
File "/media/arif/74809FD62472EDA3/SourceCode/tkdc/venv/lib/python3.6/site-packages/django/db/models/sql/subqueries.py", line 23, in do_query
cursor = self.get_compiler(using).execute_sql(CURSOR)
File "/media/arif/74809FD62472EDA3/SourceCode/tkdc/venv/lib/python3.6/site-packages/django/db/models/sql/compiler.py", line 1156, in execute_sql
cursor.execute(sql, params)
File "/media/arif/74809FD62472EDA3/SourceCode/tkdc/venv/lib/python3.6/site-packages/django/db/backends/utils.py", line 98, in execute
return super().execute(sql, params)
File "/media/arif/74809FD62472EDA3/SourceCode/tkdc/venv/lib/python3.6/site-packages/django/db/backends/utils.py", line 66, in execute
return self._execute_with_wrappers(sql, params, many=False, executor=self._execute)
File "/media/arif/74809FD62472EDA3/SourceCode/tkdc/venv/lib/python3.6/site-packages/django/db/backends/utils.py", line 75, in _execute_with_wrappers
return executor(sql, params, many, context)
File "/media/arif/74809FD62472EDA3/SourceCode/tkdc/venv/lib/python3.6/site-packages/django/db/backends/utils.py", line 84, in _execute
return self.cursor.execute(sql, params)
File "/media/arif/74809FD62472EDA3/SourceCode/tkdc/venv/lib/python3.6/site-packages/django/db/utils.py", line 90, in __exit__
raise dj_exc_value.with_traceback(traceback) from exc_value
File "/media/arif/74809FD62472EDA3/SourceCode/tkdc/venv/lib/python3.6/site-packages/django/db/backends/utils.py", line 84, in _execute
return self.cursor.execute(sql, params)
File "/media/arif/74809FD62472EDA3/SourceCode/tkdc/venv/lib/python3.6/site-packages/pgconnection/core.py", line 85, in execute
return super().execute(sql, args)
django.db.utils.OperationalError: record "new" is not assigned yet
DETAIL: The tuple structure of a not-yet-assigned record is indeterminate.
CONTEXT: SQL statement "INSERT INTO "loan_mngmt_app_testmodelevent"
("int_field", "char_field", "id", "pgh_created_at", "pgh_label", "pgh_obj_id", "pgh_context_id") VALUES (OLD."int_field", OLD."char_field", OLD."id", NOW(), 'before_delete', NEW."id", _pgh_attach_context())"
PL/pgSQL function pgtrigger_before_delete_f0f49() line 14 at SQL statement
What wrong i have done to configure pghistory.BeforeDelete() of django-pghistory and what is the solution of this problem?
The solution is to use obj_fk=None to pghistory.track()
#pghistory.track(
pghistory.AfterInsert('after_insert'),
pghistory.AfterUpdate('after_update'),
pghistory.BeforeDelete('before_delete'),
obj_fk=None
)
class TestModel(models.Model):
int_field = models.IntegerField()
char_field = models.CharField(max_length=16)
Without obj_fk=None, The trigger will be created where pgh_obj_id column will be present and it will be populated via NEW."id" into trigger's insert statement which raises the error.
CREATE OR REPLACE FUNCTION public.pgtrigger_before_delete_f0f49()
RETURNS trigger
LANGUAGE plpgsql
AS $function$
BEGIN
IF (_pgtrigger_should_ignore(TG_TABLE_NAME, TG_NAME) IS TRUE) THEN
IF (TG_OP = 'DELETE') THEN
RETURN OLD;
ELSE
RETURN NEW;
END IF;
END IF;
INSERT INTO "loan_mngmt_app_testmodelevent"
("int_field", "char_field", "id", "pgh_created_at", "pgh_label", "pgh_obj_id", "pgh_context_id") VALUES (OLD."int_field", OLD."char_field", OLD."id", NOW(), 'before_delete', NEW."id", _pgh_attach_context());
RETURN NULL;
END;
$function$
;
After using obj_fk=None, you run make migration and migrate command which will remove pgh_obj_id column and NEW."id" from the insert statement.
New statement will be this:
CREATE OR REPLACE FUNCTION public.pgtrigger_before_delete_f0f49()
RETURNS trigger
LANGUAGE plpgsql
AS $function$
BEGIN
IF (_pgtrigger_should_ignore(TG_TABLE_NAME, TG_NAME) IS TRUE) THEN
IF (TG_OP = 'DELETE') THEN
RETURN OLD;
ELSE
RETURN NEW;
END IF;
END IF;
INSERT INTO "loan_mngmt_app_testmodelevent"
("int_field", "char_field", "id", "pgh_created_at", "pgh_label", "pgh_context_id") VALUES (OLD."int_field", OLD."char_field", OLD."id", NOW(), 'before_delete', _pgh_attach_context());
RETURN NULL;
END;
$function$
;
I am working on a Django/React project. Using DRF, I am throwing an API route for performing SQL queries in my PostgreSQL database. But I am having issues with my current code setup.
I have setup my INSERT query in the API as raw queries (using cursor) enclosed in a triple quote multi-line string """INSERT...""", then format my values using string formatting %s. In my API, I capture each data from the request body into a variable. Everything works fine if all request data are filled. But, if it is null, Django obviously assigns None to the variable.
Now back to my sql query, Django will treat the null %s as None and as a table column instead of a correct null value, thus throwing a ProgrammingError column "none" does not exist.
Here are sample codes:
React Frontend
const [lastName, setLastName] = useState('')
const [firstName, setFirstName] = useState('')
const [middleName, setMiddleName] = useState('')
const [nameExtn, setNameExtn] = useState('')
const [sex, setSex] = useState('')
const [civilStatus, setCivilStatus] = useState('')
const [bloodType, setBloodType] = useState('')
const [height, setHeight] = useState('')
const [weight, setWeight] = useState('')
const newPersonalInfo = (token, data) => {
let endpoint = "/jobnet/api/profile/pds/basic/personal/"
let lookupOptions = {
method: "POST",
headers: {
'Content-Type': 'application/json',
'Authorization': `Token ${token}`
},
body: JSON.stringify(data),
credentials: 'include'
}
fetch(endpoint, lookupOptions)
.then(res=>res.json())
.then(function(info){
console.log(info)
})
.catch(err=>console.log(err));
}
const handleNewPersonalInfo = () => {
newPersonalInfo(props.user.token, {
firstname: firstName,
lastname: lastName,
middlename: middleName,
extension: nameExtn,
birthdate: selectedDate,
sex: sex,
civilstatus: civilStatus,
bloodtype: bloodType,
height: height,
weight: weight,
})
}
...
return(
<Button
variant="contained"
color="primary"
onClick={handleNewPersonalInfo}
>
SAVE
</Button>
)
Django API (DRF)
class APIListCreate__PersonalInfo(generics.ListCreateAPIView):
try:
serializer_class = PDSBasicPersonalInfoSerializer
permission_classes = (jobnet_permissions.IsAuthenticated,)
authentication_classes = (knox_TokenAuthentication,)
except Exception as e:
traceback.print_exc()
def get_queryset(self):
user = self.request.user
if user and user.is_authenticated:
query = ("""
SELECT
bsinfo.firstname,
bsinfo.middlename,
bsinfo.surname,
bsinfo.birthdate,
bsinfo.sex,
bsinfo.extention,
bsinfo.civilstatus,
bsinfo.height_m,
bsinfo.weight_kg,
bsinfo.bloodtype,
bsinfo.photo_path
FROM jobnet_app.basicinfo bsinfo
WHERE
id=%s
""" % user.id)
return raw_sql_select(query, "default")
else:
return None
def get(self, request):
data = [
{
"first_name": col.firstname,
"middle_name": col.middlename,
"last_name": col.surname,
"name_extension": col.extention,
"birthdate": col.birthdate,
"sex": col.sex,
"civil_status": col.civilstatus,
"height": col.height_m,
"weight": col.weight_kg,
"blood_type": col.bloodtype,
"photo_path": col.photo_path
} for col in self.get_queryset()[1]
]
return Response(data[0])
def post(self, request):
try:
user = request.user.id
firstname = request.data.get('firstname') or ''
middlename = request.data.get('middlename') or ''
lastname = request.data.get('lastname') or ''
birthdate = request.data.get('birthdate') or ''
sex = request.data.get('sex') or ''
extension = request.data.get('extension') or ''
civilstatus = request.data.get('civilstatus') or ''
height_m = request.data.get('height') or 0
weight_kg = request.data.get('weight') or 0
bloodtype = request.data.get('bloodtype') or ''
query = ("""
START TRANSACTION;
INSERT INTO jobnet_app.basicinfo (
id,
firstname,
middlename,
surname,
birthdate,
sex,
extention,
civilstatus,
height_m,
bloodtype,
weight_kg
)
VALUES (%s,'%s','%s','%s','%s','%s','%s','%s',%s,'%s',%s);
""" % (
user,
firstname,
middlename,
lastname,
birthdate,
sex,
extension,
civilstatus,
height_m,
bloodtype,
weight_kg
)
)
unformatted_query_result = raw_sql_insert(query, "default")
if unformatted_query_result:
raw_sql_commit("default")
return Response({
"success": True,
"message": "Your basic personal information has been updated successfully."
}, status=status.HTTP_201_CREATED)
else:
raw_sql_rollback("default")
return Response({
"success": False,
"message": "There was a problem updating your personal information."
}, status=status.HTTP_400_BAD_REQUEST)
except Exception as e:
traceback.print_exc()
return Response({
"success": False,
"message":"Internal System Error: " + str(e)
}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
With above setup, I get such error:
Traceback (most recent call last):
File "C:\Users\Acer\Envs\adnwebsite-react\lib\site-packages\django\db\backends\utils.py", line 83, in _execute
return self.cursor.execute(sql)
psycopg2.ProgrammingError: column "none" does not exist
LINE 4: ...on','2002-03-18T06:18:45.284Z','Male','','Single',None,'B+',...
^
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "D:\PGADN\Projects\pgadn-v2-website\adnwebsite\reactify\utils.py", line 17, in raw_sql_insert
cn.execute(query)
File "C:\Users\Acer\Envs\adnwebsite-react\lib\site-packages\django\db\backends\utils.py", line 100, in execute
return super().execute(sql, params)
File "C:\Users\Acer\Envs\adnwebsite-react\lib\site-packages\django\db\backends\utils.py", line 68, in execute
return self._execute_with_wrappers(sql, params, many=False, executor=self._execute)
File "C:\Users\Acer\Envs\adnwebsite-react\lib\site-packages\django\db\backends\utils.py", line 77, in _execute_with_wrappers
return executor(sql, params, many, context)
File "C:\Users\Acer\Envs\adnwebsite-react\lib\site-packages\django\db\backends\utils.py", line 85, in _execute
return self.cursor.execute(sql, params)
File "C:\Users\Acer\Envs\adnwebsite-react\lib\site-packages\django\db\utils.py", line 89, in __exit__
raise dj_exc_value.with_traceback(traceback) from exc_value
File "C:\Users\Acer\Envs\adnwebsite-react\lib\site-packages\django\db\backends\utils.py", line 83, in _execute
return self.cursor.execute(sql)
django.db.utils.ProgrammingError: column "none" does not exist
LINE 4: ...on','2002-03-18T06:18:45.284Z','Male','','Single',None,'B+',...
I am using:
Django 2.0.6
Django Rest Framework 3.10.3
PostgreSQL 11.3 (on my development machine) and PostgreSQL 12.1 (on production server) (although the error above has not yet been replicated to the server)
Note: raw_sql_select, raw_sql_insert, raw_sql_commit, raw_sql_rollback are simply custom-made helper functions which handle the actual cursor execution in the background.
Use SQL Parameters instead of % to create your insert script.
For example-
# **WRONG**
>>> cur.execute("INSERT INTO numbers VALUES (%s, %s)" % (10, 20))
# **correct**
>>> cur.execute("INSERT INTO numbers VALUES (%s, %s)", (10, 20))
You must be using cusrsor.execute in your helper functions. Pass the values as a list as a second parameter in the cusrsor.execute as shown above.
Folow this link to read more.
When trying to query for event documents that match this condition, I'm getting a parsing exception and I'm not sure what's causing it. This is occurring in my custom get_queryset method. In my get_query in my document view set I'm getting an error.
def get_queryset(self):
qs = super().get_queryset()
user = self.request.user
if hasattr(user, 'userprofile'):
user_universities = user.userprofile.universities.all().values_list("id")
user_universities_campus = user.userprofile.universities.all().values_list("main_campus__id")
query = query | Q('bool', must=[
Q('match', visibility_scope=Event.UNIVERSITY),
Q('bool', must=[
Q('terms', university__id=list(user_universities)),
Q('bool', should=[
Q('terms', university__main_campus__id=list(user_universities)),
Q('terms', university__main_campus__id=list(user_universities_campus))
])
])
])
qs = qs.query(query)
return qs
I'm getting this error:
if self.count == 0 and not self.allow_empty_first_page:
File "C:\Users\fendy\.virtualenvs\cul\lib\site-packages\django\utils\functional.py", line 80, in __get__
res = instance.__dict__[self.name] = self.func(instance)
File "C:\Users\fendy\.virtualenvs\cul\lib\site-packages\django\core\paginator.py", line 91, in count
return c()
File "C:\Users\fendy\.virtualenvs\cul\lib\site-packages\elasticsearch_dsl\search.py", line 679, in count
**self._params
File "C:\Users\fendy\.virtualenvs\cul\lib\site-packages\elasticsearch\client\utils.py", line 84, in _wrapped
return func(*args, params=params, **kwargs)
File "C:\Users\fendy\.virtualenvs\cul\lib\site-packages\elasticsearch\client\__init__.py", line 529, in count
"POST", _make_path(index, doc_type, "_count"), params=params, body=body
File "C:\Users\fendy\.virtualenvs\cul\lib\site-packages\elasticsearch\transport.py", line 358, in perform_request
timeout=timeout,
File "C:\Users\fendy\.virtualenvs\cul\lib\site-packages\elasticsearch\connection\http_urllib3.py", line 261, in perform_request
self._raise_error(response.status, raw_data)
File "C:\Users\fendy\.virtualenvs\cul\lib\site-packages\elasticsearch\connection\base.py", line 182, in _raise_error
status_code, error_message, additional_info
elasticsearch.exceptions.RequestError: RequestError(400, 'parsing_exception', '[terms] unknown token [END_ARRAY] after [university.id]')
Query String printout:
Bool(should=[Bool(must=[Match(visibility_scope=2), Bool(must=[Terms(university__id=[(42809,)]), Bool(should=[Terms(university__main_campus__id=[(42809,)]), Terms(university__main_campus__id=[(None,)])])])]), Match(visibility_scope=0)])
Your query in string should be like this:
{
"bool": {
"should":[
"bool" : {
"must":[
{"match":{
"visibility_scope" : 2
},
"bool":{
"must":[
{
"terms": {
}
....
.....
.....
}
]
}
}
]
}
]
}
}
Can you update your question with a querystring? I may be able to complete it.
It is because of queryset. Please set flat=True.
user_universities = user.userprofile.universities.all().values_list("id", flat=True)
How would I log errors to django-sentry from celery tasks?
I've tried try: except: blocks and using raven_client.create_from_exception but that blows up every time with:
Traceback (most recent call last):
File "/home/controlpanel/current/env/lib/python2.6/site-packages/celery/execute/trace.py", line 47, in trace
return cls(states.SUCCESS, retval=fun(*args, **kwargs))
File "/home/controlpanel/current/env/lib/python2.6/site-packages/celery/app/task/__init__.py", line 247, in __call__
return self.run(*args, **kwargs)
File "/home/controlpanel/current/env/lib/python2.6/site-packages/celery/app/__init__.py", line 175, in run
return fun(*args, **kwargs)
File "/home/controlpanel/deployments/1323265958/src/deploy/tasks.py", line 60, in async_deploy_bundle
raven_client.create_from_exception(exc_info=exc_info)
File "/home/controlpanel/current/env/lib/python2.6/site-packages/raven/contrib/django/__init__.py", line 120, in create_from_exception
return super(DjangoClient, self).create_from_exception(exc_info, **kwargs)
File "/home/controlpanel/current/env/lib/python2.6/site-packages/raven/base.py", line 285, in create_from_exception
frames = varmap(shorten, get_stack_info(iter_traceback_frames(exc_traceback)))
File "/home/controlpanel/current/env/lib/python2.6/site-packages/raven/utils/stacks.py", line 128, in get_stack_info
'vars': transform(frame.f_locals.items()),
File "/home/controlpanel/current/env/lib/python2.6/site-packages/raven/utils/encoding.py", line 78, in transform
ret = type(value)(transform_rec(o) for o in value)
File "/home/controlpanel/current/env/lib/python2.6/site-packages/raven/utils/encoding.py", line 78, in <genexpr>
ret = type(value)(transform_rec(o) for o in value)
File "/home/controlpanel/current/env/lib/python2.6/site-packages/raven/utils/encoding.py", line 72, in <lambda>
transform_rec = lambda o: transform(o, stack + [value], context)
File "/home/controlpanel/current/env/lib/python2.6/site-packages/raven/utils/encoding.py", line 78, in transform
ret = type(value)(transform_rec(o) for o in value)
File "/home/controlpanel/current/env/lib/python2.6/site-packages/raven/utils/encoding.py", line 78, in <genexpr>
ret = type(value)(transform_rec(o) for o in value)
File "/home/controlpanel/current/env/lib/python2.6/site-packages/raven/utils/encoding.py", line 72, in <lambda>
transform_rec = lambda o: transform(o, stack + [value], context)
File "/home/controlpanel/current/env/lib/python2.6/site-packages/raven/utils/encoding.py", line 78, in transform
ret = type(value)(transform_rec(o) for o in value)
File "/home/controlpanel/current/env/lib/python2.6/site-packages/git/util.py", line 588, in __init__
raise ValueError("First parameter must be a string identifying the name-property. Extend the list after initialization")
ValueError: First parameter must be a string identifying the name-property. Extend the list after initialization
My task:
#task
def async_deploy_bundle(bundle_id):
try:
do_stuff(bundle_id)
except:
exc_info = sys.exc_info()
traceback.print_exception(*exc_info)
try:
raven_client = get_client()
raven_client.create_from_exception(exc_info=exc_info)
except:
pass
raise
What about this:
myLogger = logging.getLogger('mylogger.info')
myLogger.setLevel(logging.INFO)
myLogger.info(exc_info)
?
In my settings.py:
'loggers': {
'mylogger.info': {
'level': 'INFO',
'handlers': ['sentry'],
'propagate': False,
},
}