How to handle multiple requests without SQLAlchemy crashing/raising exceptions?

KBN

Context: I'm working on a Flask app, running on CherryPy, DB handled using SQLAlchemy ORM.

Problem:

The app runs fine and does everything I want, however, if I have a page which fetches some data from DB and displays, and I press and hold "Ctrl + R" or "F5". That is, continuously refresh a page, making that many DB requests. First few goes fine, and then it breaks. The following errors are logged:

(OperationalError) (2013, 'Lost connection to MySQL server during query')

Can't reconnect until invalid transaction is rolled back (original cause: 
InvalidRequestError: Can't reconnect until invalid transaction is rolled back)

This result object does not return rows. It has been closed automatically.

(ProgrammingError) (2014, "Commands out of sync; you can't run this command now")

There's also another error which bothers me (but not logged this time), it's

dictionary changed size during iteration

This happens when I'm iterating through a query, using values obtained to populate a dictionary. The dictionary is local (scope of the dict) to the function.

More info:

How I am handling sessions:

A new session is created when you enter any page, use that session to perform all the DB transactions, and the session is closed right before rendering the HTML. Technically, that means, the scope of session is the same as the HTTP request.

I do a session.rollback() only when there's an exception raised during updating table or inserting into a table. No rollback() during any query() operations. I'm pretty sure I've made some silly mistakes or am not doing things the right way.

Unlimited refreshes like that is not really a probably scenario, but can't be overlooked. Also, I think the behavior would be similar when there a lot of users using it at the same time.

How the SQLAlchemy engine, sessionmaker was handled:

sql_alchemy_engine = create_engine(self.db_string, echo=False, encoding="utf8", convert_unicode=True, pool_recycle=9)
sqla_session = sessionmaker(bind=sql_alchemy_engine)

It's done only ONCE like it's recommended in the SQLA documentation, and a new session is created and returned sqla_session() whenever required.

Pedro Werneck

If you're using Flask, you should be using flask-sqlalchemy, and let the Flask request context manage your session, and not handling your engine and sessions by hand. This is how SQLAlchemy recommends it:

Most web frameworks include infrastructure to establish a single Session, associated with the request, which is correctly constructed and torn down corresponding torn down at the end of a request. Such infrastructure pieces include products such as Flask-SQLAlchemy, for usage in conjunction with the Flask web framework, and Zope-SQLAlchemy, for usage in conjunction with the Pyramid and Zope frameworks. SQLAlchemy strongly recommends that these products be used as available.

http://docs.sqlalchemy.org/en/rel_0_9/orm/session.html?highlight=flask

Then you create your engine simply by:

from flask import Flask
from flask.ext.sqlalchemy import SQLAlchemy

app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'your db uri'

db = SQLAlchemy(app)

Or, if you're using app factory:

from flask import Flask
from flask.ext.sqlalchemy import SQLAlchemy

db = SQLAlchemy()

def create_app():
    app = Flask(__name__)
    app.config['SQLALCHEMY_DATABASE_URI'] = 'your db uri'

    db.init_app(app)

With that, the base declarative model you should be using will be at db.Model and the session you should be using will be at db.session.

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

From Dev

How to handle multiple requests in PHP?

From Dev

How to handle multiple requests through an Ajax API?

From Dev

How does php and apache handle multiple requests?

From Dev

How does Rails handle multiple incoming requests?

From Dev

How to handle multiple http requests in my case?

From Dev

How do I handle exceptions in Python without blocking execution?

From Dev

How to run multiple tasks, handle exceptions and still return results

From Dev

How do I handle multiple checked exceptions in Java?

From Dev

How do I handle multiple checked exceptions in Java?

From Dev

How Exceptions are handle in EJB?

From Dev

Deno: How to handle exceptions

From Dev

How to handle exceptions with builders

From Dev

How to handle exceptions with unsafeInterleaveIO?

From Dev

How to handle exceptions in selenium?

From Dev

How to handle exceptions in Frege?

From Dev

How to handle exceptions with builders

From Dev

How to Wait for Angular2 to Handle Dynamic Multiple Http Requests?

From Dev

How does a single servlet handle multiple requests from client side

From Dev

Socket.io : How to handle/manage multiple clients requests and responses?

From Dev

How to handle JPA ObjectOptimisticLockException properly for multiple simultaneous transaction requests?

From Dev

How to handle high thread usage because of multiple AJAX requests in WebSphere

From Dev

nodejs async calls, how to handle multiple requests at a url

From Dev

How does TCP handle multiple requests targeted to one port?

From Dev

AngularJS - Multiple controllers with GET requests, how to handle URL?

From Dev

How to Wait for Angular2 to Handle Dynamic Multiple Http Requests?

From Dev

How Spring MVC controller handle multiple long http requests?

From Dev

How to Handle Temporary Exceptions in Asmack

From Dev

How do I handle exceptions?

From Dev

How to handle exceptions from a gem

Related Related

  1. 1

    How to handle multiple requests in PHP?

  2. 2

    How to handle multiple requests through an Ajax API?

  3. 3

    How does php and apache handle multiple requests?

  4. 4

    How does Rails handle multiple incoming requests?

  5. 5

    How to handle multiple http requests in my case?

  6. 6

    How do I handle exceptions in Python without blocking execution?

  7. 7

    How to run multiple tasks, handle exceptions and still return results

  8. 8

    How do I handle multiple checked exceptions in Java?

  9. 9

    How do I handle multiple checked exceptions in Java?

  10. 10

    How Exceptions are handle in EJB?

  11. 11

    Deno: How to handle exceptions

  12. 12

    How to handle exceptions with builders

  13. 13

    How to handle exceptions with unsafeInterleaveIO?

  14. 14

    How to handle exceptions in selenium?

  15. 15

    How to handle exceptions in Frege?

  16. 16

    How to handle exceptions with builders

  17. 17

    How to Wait for Angular2 to Handle Dynamic Multiple Http Requests?

  18. 18

    How does a single servlet handle multiple requests from client side

  19. 19

    Socket.io : How to handle/manage multiple clients requests and responses?

  20. 20

    How to handle JPA ObjectOptimisticLockException properly for multiple simultaneous transaction requests?

  21. 21

    How to handle high thread usage because of multiple AJAX requests in WebSphere

  22. 22

    nodejs async calls, how to handle multiple requests at a url

  23. 23

    How does TCP handle multiple requests targeted to one port?

  24. 24

    AngularJS - Multiple controllers with GET requests, how to handle URL?

  25. 25

    How to Wait for Angular2 to Handle Dynamic Multiple Http Requests?

  26. 26

    How Spring MVC controller handle multiple long http requests?

  27. 27

    How to Handle Temporary Exceptions in Asmack

  28. 28

    How do I handle exceptions?

  29. 29

    How to handle exceptions from a gem

HotTag

Archive