IntegrityError "django_session_pkey" - django

I'm contributing to a django application which from time to time crashes responding with:
IntegrityError at /signin/
duplicate key value violates unique constraint "django_session_pkey"
DETAIL: Key (session_key)=(ahwvmdwpz5hg1rnu8q7ctudvfl9nfnga) already exists.
To me it makes absolutely no sense, as session key is always randomly generated and it is almost impossible to see this kind of error. When it happens it blocks the whole site, as users get this for every request, no matter what browser or system. The only way to get rid of this is to reboot machine.
Has anyone ever seen this error or has any permanent solution?
I tried to google it, but found no sensible results.

Related

How can I catch a unique constraint violation through QT's QSqlDatabase interface?

The title says it all, really. I have a QT application, using the QSqlDatabase interface, and I need to take a different action on a unique key constraint violation as opposed to any other type of error.
Currently the backend database is SQLite, if that matters. However, management is talking about switching to MS SQL Server, so if the solution is database-specific, I'll need one for both.
You can use a QSqlQuery::lastError method to check an error occured while INSERT or UPDATE query execution. It returns QSqlError, which has a nativeErrorCode method. I'm not sure, if it contains only a numeric value or a full error description.
In common, according to documentation SQLite should return 2067 error, however SQL Server has a different error codes 2601 and 2627, those are table key constraint specific.
So, you should check, if the string value of QSqlError::nativeErrorCode contains a database engine specific error code.

Any way to handler IntegrityError in django?

In django the exception IntegrityError could be caused by a lot of reasons.
Some times this error means a unique conflict. Some other times this could be caused by some foreign key check.
Currently we can only know the root cause by convert the exception into text:
(1062, "Duplicate entry '79d3dd88917a11e98d42f000ac192cee-not_created' for key 'fs_cluster_id_dir_e8164dce_uniq'")
But this is very unfriendly for program to identify. Is there any way for code to identify the root cause of exception?
For example, if I know this is caused by a unique conflict, I can tell the client this is caused because some resouce already exist. If I know this is caused by foreign key not exist, I can tell the client this is caused by some parent resource not created.
So can any good way to identify the cause by code?
Don't know about good.
Do you need to identify the exact cause in your code? If you have an alternative way of proceeding that you want to avoid using every time because of efficiency considerations, you might just code:
try:
# the simple way
except IntegrityError as simplefail:
try:
# the complicated way
except IntegrityError as complexfail:
# log this utter failure and re-raise one or other of the caught errors

Django+postgres auth_user duplicate key value violates unique constraint "auth_user_username_key"

try:
django_user = User.objects.get(username__iexact=self.username)
except User.DoesNotExist:
django_user = User(username=self.username)
django_user.is_staff=True
django_user.save()
Above gets the user by searching by username if present or create a new object if not present and updates its attribute and saves it back to db.
This code ideally should handle the situation where the object is already present in the database. But it is throwing following error
duplicate key value violates unique constraint "auth_user_username_key"
DETAIL: Key (username)=(xxxxxxxx#yyyyy.com) already
exists.
I don't get the reason for this. Searched on the internet and found that It might be because of indices are corrupted and has to reset the sequence but Cannot find the exact reason and solution for this.
Please help me with this.
Thanks in advance
I've been a while since i don't refresh my Django skills but as far i remember you
can use another way to surpass this problem like:
if Entry.objects.filter(username=self.username).exists():
# DO IF STUFF
else:
# DO ELSE STUFF
If your username isn't the pk key then you may have to set it as unique and that would prevent to have duplicated usernames.
Oficial Django reference
But there is something it is digging in my mind by the way you are using your self.username variable. It seems you have some class where you needs to make such kind of functionality. And i'm afraid that this peace of code you have is located inside of the same class model declaration, by the kind of query you wants to perform you should keep this in mind:
If you wants to check for some username that hasn't been insert in the databse yet then it won't have a pk and you won't be able to look for such data in the database. By summoning it before the .save() some of this errors can happen.
Hope this helps you.

Utility.SearchPrincipals does not return any results

I am writing a provider hosted SharePoint 2013 application. I'm using SharePoint online.
Since the people picker isn't supported in this scenario, I need to build my own. I found the SearchPrincipals method. That seems like exactly what I'm looking for, but no matter what I try, the method is returning with 0 results.
What little information I've found around this method suggests that the problem is usually a permissions issue, but the user that I'm logged in as is a Site Collection Administrator (ClientContext.Web.CurrentUser.IsSiteAdmin is true), so that shouldn't be the case with me.
I've tried passing in virtually every combination of PrincipalType and PrincipalSource, even ones that didn't make sense. I've also tried passing in ClientContext.Web.SiteUsers for the scope, and also null, both of which I've seen used in my searches, and that didn't turn up any results either.
Any help would be appreciated!
I figured it out. The ClientContext of the CSOM (Client Side Object Model) allows the developer to make multiple --unrelated -- queries. It queues up these queries and does not execute them until ExecuteQuery is called. Even though SearchPrincipals is a static method off of the Utility class, it still translates the method call into a query and queues it up. The method will always return an empty collection, but once you call ExecuteQuery on the ClientContext, that collection is then filled with the results of the search.
Also, another problem that I ran into immediately afterwards was that I was getting an error that seemed completely unrelated to my query when I called ExecuteQuery. It turns out that there was code that previously executed that queued up some queries, but it never executed them, so when I called ExecuteQuery, it executed those queries as well, and one of those was erroring. If you are getting an unexpected error, it's a good idea to see if there are other queued queries that haven't been executed yet. You can check the boolean property HasPendingRequest to help determine this.
Hopefully this answer saves other people a lot of time!

Diagnosing a Sporadic Django/ Postgres "DatabaseError: current transaction is aborted"

I have a "DatabaseError: current transaction is aborted" that comes and goes (to be specific, 11 times out of 841) in a Django 1.3 project using Postgres. The project is a quiz site and the error occurs when a user submits the answer form in the view. From the database's perspective, the process involves a number of queries and looks like this:
Gather all of the correct answers for the question (they are multiple choice and may need more than one answer)*
Grab the user's profile
Save this answer
Query for the user's new point total
Save the total to their profile
Check to see if they qualify for a new reward
Award new reward if they do
Somewhere in that tortured process, this error crops up (I'm guessing because one query isn't waiting for the others). Is there a way for me, in production (i.e., DEBUG = False), to log the database errors just in this case? I'm on WebFaction and the Postgres error logs are not available to me. Could I steal something from this middleware example to fire in just this specific case?
Alternatively, is there a better way to find this error or should I be wrapping the individual queries in transactions (unfortunately they aren't all in the same place in the code, not sure if wrapping the view in a transaction decorator would help)?
*Just to confuse matters, the multiple right answers requirement was added in the middle of development and then dropped right before we went live, so I could simplify this process somewhat, basically skipping steps 1 and 4, but I'd like to know a general answer to this sort of mysterious issue.
You haven't said where in your 7 steps you have transactions that begin and end. That would be helpful to know.
One source of "transaction aborted" messages is due to deadlocks. More details would be in the PostgreSQL logs.
But the bottom line is that you will continue to have a painful and time-consuming experience debugging PostgreSQL if you can't get access to your PostgreSQL error messages. Take that up with WebFaction. If they can't helpful and your time is worth much, your bottom line costs will be lower by moving to an environment that provides this fundamental feature.
You have to enable autocommit for the transaction. In your DATABASES entry, include:
'OPTIONS': {'autocommit': True,},
By default, Django opens a transaction at the first query. By using this option, you manually have to start a transaction (e.g. using #commit_on_success). Since there is no transaction open anymore, you'll get the actual error that was previously masked by the transaction error.
The autocommit setting will be the new default for Django 1.6, see https://docs.djangoproject.com/en/dev/ref/databases/#postgresql-notes