Advertisement
Guest User

Untitled

a guest
Aug 30th, 2014
212
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.86 KB | None | 0 0
  1. import psycopg2
  2.  
  3. @needsNewCursor
  4. def findItem(cursor, item_id):
  5. cursor.execute('SELECT name FROM items WHERE id = %s', [item_id])
  6. item_result = cursor.fetchone()
  7. # ...
  8. return item
  9.  
  10. # caller only needs to know about the ID
  11. findItem(1234)
  12.  
  13. def needsNewCursor(func):
  14. def decorator(*args, **kargs):
  15. print 'Creating new cursor'
  16. # This is slightly different in the final code, but I'm only
  17. # concerned about how I'm dealing with decorators, at the moment
  18. cursor = createDefaultCursor()
  19. if cursor:
  20. with cursor:
  21. # Pass the cursor in as the 1st param
  22. return func(cursor, *args, **kargs)
  23.  
  24. # Give the function a chance to deal with fails
  25. return func(None, *args, **kargs)
  26.  
  27. # QUESTION: Is this enough?
  28. decorator.__name__ = func.__name__
  29. return decorator
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement