3
\$\begingroup\$

I am developing a reporting application in Flask where I pull data in a route function from a postgresql database and jsonify the data. On the client side I have some javascript that does a $.getJSON on the route to request the data.

Here is what the code looks like.

Flask route

def get_db():
 if not hasattr(g, 'postgres_db'):
 g.postgres_db = connect_db()
 return g.postgres_db
@main.route('/Q5')
@login_required
def failed_access():
 failed_query = """select * from prototype.Q5"""
 db = get_db()
 with db.cursor(cursor_factory=RealDictCursor) as cur:
 cur.execute(failed_query)
 results = cur.fetch_all()
 data = json.dumps(results, indent=2, default=date_handler)
 return data

Client side javascript looks like this:

$.getJSON('/Q5', function genChart() { blah() }));

Everything works fine but I want to make sure that there is something I am not missing or could be doing a better way.

Quill
12k5 gold badges41 silver badges93 bronze badges
asked Nov 21, 2014 at 15:21
\$\endgroup\$

3 Answers 3

1
\$\begingroup\$

That is not a lot of JavaScript to review ;)

  • You are not dealing with failure, $.getJSON() returns a jqXHR object and you can/should define failure handling there.

  • Similarly for the backend, it seems you are not handling any failures. That is okay for a prototype, not for production. (Perhaps you take care of exception handling elsewhere in Flask, it is not obvious in the documentation)

answered Nov 21, 2014 at 17:55
\$\endgroup\$
1
\$\begingroup\$

I don't really get the purpose of the get_db function. Why not simply initialize the database at the very beginning like so:

db = connect_db()

And then use db in failed_access directly. It seems you wanted to do lazy initialization, but is it really worth it? Sooner or later, the database will be used anyway. Initializing upfront is straightforward, simple, and less error prone.

answered Nov 21, 2014 at 23:30
\$\endgroup\$
1
\$\begingroup\$
data = json.dumps(results, indent=2, default=date_handler)

Since the JSON data is only read by Javascript the indentation is not needed. It only consumes extra bandwidth. So you write better:

data = json.dumps(results, default=date_handler)
answered Nov 22, 2014 at 19:32
\$\endgroup\$

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.