Advertisement
Guest User

Untitled

a guest
Apr 20th, 2014
117
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 11.25 KB | None | 0 0
  1. import cherrypy
  2. from cherrypy.process import wspbus, plugins
  3. from sqlalchemy import create_engine
  4. from sqlalchemy.orm import scoped_session, sessionmaker
  5. from sqlalchemy.ext.declarative import declarative_base
  6. from sqlalchemy import Column, String
  7. import os
  8.  
  9.  
  10. # BELOW CLASSES COPIED FROM
  11. # https://bitbucket.org/Lawouach/cherrypy-recipes/src/d140e6da973aa271e6b68a8bc187e53615674c5e/web/database/?at=default
  12. class SATool(cherrypy.Tool):
  13. def __init__(self):
  14. """
  15. The SA tool is responsible for associating a SA session
  16. to the SA engine and attaching it to the current request.
  17. Since we are running in a multithreaded application,
  18. we use the scoped_session that will create a session
  19. on a per thread basis so that you don't worry about
  20. concurrency on the session object itself.
  21.  
  22. This tools binds a session to the engine each time
  23. a requests starts and commits/rollbacks whenever
  24. the request terminates.
  25. """
  26. cherrypy.Tool.__init__(self, 'on_start_resource',
  27. self.bind_session,
  28. priority=20)
  29.  
  30. def _setup(self):
  31. cherrypy.Tool._setup(self)
  32. cherrypy.request.hooks.attach('on_end_resource',
  33. self.commit_transaction,
  34. priority=80)
  35.  
  36. def bind_session(self):
  37. """
  38. Attaches a session to the request's scope by requesting
  39. the SA plugin to bind a session to the SA engine.
  40. """
  41. session = cherrypy.engine.publish('bind-session').pop()
  42. cherrypy.request.db = session
  43.  
  44. def commit_transaction(self):
  45. """
  46. Commits the current transaction or rolls back
  47. if an error occurs. Removes the session handle
  48. from the request's scope.
  49. """
  50. if not hasattr(cherrypy.request, 'db'):
  51. return
  52. cherrypy.request.db = None
  53. cherrypy.engine.publish('commit-session')
  54.  
  55.  
  56. class SAEnginePlugin(plugins.SimplePlugin):
  57. def __init__(self, bus):
  58. """
  59. The plugin is registered to the CherryPy engine and therefore
  60. is part of the bus (the engine *is* a bus) registery.
  61.  
  62. We use this plugin to create the SA engine. At the same time,
  63. when the plugin starts we create the tables into the database
  64. using the mapped class of the global metadata.
  65. """
  66. plugins.SimplePlugin.__init__(self, bus)
  67. self.sa_engine = None
  68. self.session = scoped_session(sessionmaker(autoflush=True,
  69. autocommit=False))
  70.  
  71. def start(self):
  72. self.bus.log('Starting up DB access')
  73.  
  74. self.sa_engine = create_engine('oracle+cx_oracle://%s:%s@%s' %
  75. (os.getenv('DB_USERNAME'), os.getenv('DB_PASSWORD'), os.getenv('DB_SERVER')),
  76. echo=True)
  77.  
  78. self.bus.subscribe("bind-session", self.bind)
  79. self.bus.subscribe("commit-session", self.commit)
  80.  
  81. def stop(self):
  82. self.bus.log('Stopping down DB access')
  83. self.bus.unsubscribe("bind-session", self.bind)
  84. self.bus.unsubscribe("commit-session", self.commit)
  85. if self.sa_engine:
  86. self.sa_engine.dispose()
  87. self.sa_engine = None
  88.  
  89. def bind(self):
  90. """
  91. Whenever this plugin receives the 'bind-session' command, it applies
  92. this method and to bind the current session to the engine.
  93.  
  94. It then returns the session to the caller.
  95. """
  96. self.session.configure(bind=self.sa_engine)
  97. return self.session
  98.  
  99. def commit(self):
  100. """
  101. Commits the current transaction or rollbacks if an error occurs.
  102.  
  103. In all cases, the current session is unbound and therefore
  104. not usable any longer.
  105. """
  106. try:
  107. self.session.commit()
  108. except:
  109. self.session.rollback()
  110. raise
  111. finally:
  112. self.session.remove()
  113.  
  114. # SQL Alchemy model
  115. Base = declarative_base()
  116. class Registration(Base):
  117. __tablename__ = 'beta_registration'
  118. email = Column('email', String, primary_key=True)
  119.  
  120.  
  121. class Root():
  122. @cherrypy.expose
  123. def index(self):
  124. registration = Registration()
  125. registration.email = "test@test.com"
  126.  
  127. db = cherrypy.request.db
  128. try:
  129. db.add(registration)
  130. except Exception as e:
  131. # **** never gets here *****
  132. # should be IntegrityError on second call from sqlalchemy.exc
  133. raise cherrypy.HTTPError("409 Conflict", "The email address has already been registered")
  134.  
  135. SAEnginePlugin(cherrypy.engine).subscribe()
  136. cherrypy.tools.db = SATool()
  137.  
  138. cherrypy.config.update({
  139. 'tools.sessions.on' : True,
  140. 'tools.sessions.storage_type' : 'File',
  141. 'tools.sessions.storage_path' : 'adf'
  142. })
  143.  
  144.  
  145. cherrypy.quickstart(Root(), '/')
  146.  
  147. [09/Apr/2014:16:43:54] ENGINE Error in 'commit-session' listener <bound method SAEnginePlugin.commit of <plugins.saplugin.SAEnginePlugin object at 0x105a0cd10>>
  148. Traceback (most recent call last):
  149. File "/Users/xatter/Sites/connectfor/venv/lib/python2.7/site-packages/cherrypy/process/wspbus.py", line 197, in publish
  150. output.append(listener(*args, **kwargs))
  151. File "/Users/xatter/Sites/connectfor/plugins/saplugin.py", line 57, in commit
  152. self.session.commit()
  153. File "/Users/xatter/Sites/connectfor/venv/lib/python2.7/site-packages/sqlalchemy/orm/scoping.py", line 149, in do
  154. return getattr(self.registry(), name)(*args, **kwargs)
  155. File "/Users/xatter/Sites/connectfor/venv/lib/python2.7/site-packages/sqlalchemy/orm/session.py", line 765, in commit
  156. self.transaction.commit()
  157. File "/Users/xatter/Sites/connectfor/venv/lib/python2.7/site-packages/sqlalchemy/orm/session.py", line 370, in commit
  158. self._prepare_impl()
  159. File "/Users/xatter/Sites/connectfor/venv/lib/python2.7/site-packages/sqlalchemy/orm/session.py", line 350, in _prepare_impl
  160. self.session.flush()
  161. File "/Users/xatter/Sites/connectfor/venv/lib/python2.7/site-packages/sqlalchemy/orm/session.py", line 1879, in flush
  162. self._flush(objects)
  163. File "/Users/xatter/Sites/connectfor/venv/lib/python2.7/site-packages/sqlalchemy/orm/session.py", line 1997, in _flush
  164. transaction.rollback(_capture_exception=True)
  165. File "/Users/xatter/Sites/connectfor/venv/lib/python2.7/site-packages/sqlalchemy/util/langhelpers.py", line 57, in __exit__
  166. compat.reraise(exc_type, exc_value, exc_tb)
  167. File "/Users/xatter/Sites/connectfor/venv/lib/python2.7/site-packages/sqlalchemy/orm/session.py", line 1961, in _flush
  168. flush_context.execute()
  169. File "/Users/xatter/Sites/connectfor/venv/lib/python2.7/site-packages/sqlalchemy/orm/unitofwork.py", line 370, in execute
  170. rec.execute(self)
  171. File "/Users/xatter/Sites/connectfor/venv/lib/python2.7/site-packages/sqlalchemy/orm/unitofwork.py", line 523, in execute
  172. uow
  173. File "/Users/xatter/Sites/connectfor/venv/lib/python2.7/site-packages/sqlalchemy/orm/persistence.py", line 64, in save_obj
  174. mapper, table, insert)
  175. File "/Users/xatter/Sites/connectfor/venv/lib/python2.7/site-packages/sqlalchemy/orm/persistence.py", line 562, in _emit_insert_statements
  176. execute(statement, multiparams)
  177. File "/Users/xatter/Sites/connectfor/venv/lib/python2.7/site-packages/sqlalchemy/engine/base.py", line 717, in execute
  178. return meth(self, multiparams, params)
  179. File "/Users/xatter/Sites/connectfor/venv/lib/python2.7/site-packages/sqlalchemy/sql/elements.py", line 317, in _execute_on_connection
  180. return connection._execute_clauseelement(self, multiparams, params)
  181. File "/Users/xatter/Sites/connectfor/venv/lib/python2.7/site-packages/sqlalchemy/engine/base.py", line 814, in _execute_clauseelement
  182. compiled_sql, distilled_params
  183. File "/Users/xatter/Sites/connectfor/venv/lib/python2.7/site-packages/sqlalchemy/engine/base.py", line 927, in _execute_context
  184. context)
  185. File "/Users/xatter/Sites/connectfor/venv/lib/python2.7/site-packages/sqlalchemy/engine/base.py", line 1076, in _handle_dbapi_exception
  186. exc_info
  187. File "/Users/xatter/Sites/connectfor/venv/lib/python2.7/site-packages/sqlalchemy/util/compat.py", line 185, in raise_from_cause
  188. reraise(type(exception), exception, tb=exc_tb)
  189. File "/Users/xatter/Sites/connectfor/venv/lib/python2.7/site-packages/sqlalchemy/engine/base.py", line 920, in _execute_context
  190. context)
  191. File "/Users/xatter/Sites/connectfor/venv/lib/python2.7/site-packages/sqlalchemy/engine/default.py", line 425, in do_execute
  192. cursor.execute(statement, parameters)
  193. IntegrityError: (IntegrityError) duplicate key value violates unique constraint "beta_registration_pk"
  194. DETAIL: Key (email)=(test@test.com) already exists.
  195. 'INSERT INTO beta_registration (email) VALUES (%(email)s)' {'email': u'test@test.com'}
  196.  
  197. [09/Apr/2014:16:43:54] Traceback (most recent call last):
  198. File "/Users/xatter/Sites/connectfor/venv/lib/python2.7/site-packages/cherrypy/_cprequest.py", line 102, in run
  199. hook()
  200. File "/Users/xatter/Sites/connectfor/venv/lib/python2.7/site-packages/cherrypy/_cprequest.py", line 62, in __call__
  201. return self.callback(**self.kwargs)
  202. File "/Users/xatter/Sites/connectfor/plugins/satool.py", line 47, in commit_transaction
  203. cherrypy.engine.publish('commit-session')
  204. File "/Users/xatter/Sites/connectfor/venv/lib/python2.7/site-packages/cherrypy/process/wspbus.py", line 215, in publish
  205. raise exc
  206. ChannelFailures: IntegrityError('(IntegrityError) duplicate key value violates unique constraint "beta_registration_pk"nDETAIL: Key (email)=(test@test.com) already exists.n',)
  207.  
  208. [09/Apr/2014:16:43:54] HTTP
  209. Request Headers:
  210. Content-Length: 25
  211. COOKIE: remember_token=_tm4c-HNpJWTHB1PXj8Wbg; session_id=25757ddac3a84730ce3b87f32b80a4288f5421b4
  212. HOST: localhost:5000
  213. ORIGIN: http://localhost:5000
  214. CONNECTION: keep-alive
  215. Remote-Addr: 127.0.0.1
  216. ACCEPT: application/json, text/plain, */*
  217. USER-AGENT: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_2) AppleWebKit/537.75.14 (KHTML, like Gecko) Version/7.0.3 Safari/537.75.14
  218. REFERER: http://localhost:5000/
  219. ACCEPT-LANGUAGE: en-us
  220. Content-Type: application/json;charset=UTF-8
  221. ACCEPT-ENCODING: gzip, deflate
  222. [09/Apr/2014:16:43:54] HTTP Traceback (most recent call last):
  223. File "/Users/xatter/Sites/connectfor/venv/lib/python2.7/site-packages/cherrypy/_cprequest.py", line 670, in respond
  224. self.hooks.run('on_end_resource')
  225. File "/Users/xatter/Sites/connectfor/venv/lib/python2.7/site-packages/cherrypy/_cprequest.py", line 112, in run
  226. raise exc
  227. ChannelFailures: IntegrityError('(IntegrityError) duplicate key value violates unique constraint "beta_registration_pk"nDETAIL: Key (email)=(test@test.com) already exists.n',)
  228.  
  229. 127.0.0.1 - - [09/Apr/2014:16:43:54] "POST /beta_registration HTTP/1.1" 500 1303 "http://localhost:5000/" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_2) AppleWebKit/537.75.14 (KHTML, like Gecko) Version/7.0.3 Safari/537.75.14"
  230.  
  231. import cherrypy
  232.  
  233. cherrypy.config.update({
  234. 'tools.sessions.on' : True,
  235. 'tools.sessions.storage_type' : 'File',
  236. 'tools.sessions.storage_path' : 'adf'
  237. })
  238.  
  239. class Root(object):
  240. @cherrypy.expose
  241. def index(self):
  242. try:
  243. asdf = cherrypy.session['asdf']
  244. except Exception as e:
  245. raise cherrypy.HTTPError("409 Conflict", "The email address has already been registered")
  246. #return str(e)
  247. return 1
  248.  
  249. @cherrypy.expose
  250. @cherrypy.tools.json_out()
  251. def main(self):
  252. return 'hi'
  253.  
  254. cherrypy.quickstart(Root())
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement