Optimise repo_connect by skipping authenticate_user
authorChristophe de Vienne <christophe@unlish.com>
Mon, 22 Sep 2014 12:15:31 +0200
changeset 11513 0170f8a55620
parent 11512 bb548010b390
child 11514 82e86cd8e217
Optimise repo_connect by skipping authenticate_user The authentication being handled by pyramid itself, going through the authentication stack to recreate the temporary session at each request is very costly. On my desktop, for a mostly static front page, the total time for delivering the page drops from 100ms to 47ms.
pyramid_cubicweb/core.py
--- a/pyramid_cubicweb/core.py	Mon Sep 22 09:40:43 2014 +0200
+++ b/pyramid_cubicweb/core.py	Mon Sep 22 12:15:31 2014 +0200
@@ -149,11 +149,11 @@
     return cnx
 
 
-def repo_connect(repo, login, **kw):
+def repo_connect(repo, eid):
     """A lightweight version of repo.connect that does not keep track of opened
     sessions, removing the need of closing them"""
     with repo.internal_cnx() as cnx:
-        user = repo.authenticate_user(cnx, login, **kw)
+        user = repo._build_user(cnx, eid=eid)
     session = Session(user, repo, None)
     user._cw = user.cw_rset.req = session
     user.cw_clear_relation_cache()
@@ -169,11 +169,10 @@
 def _cw_session(request):
     """Obtains a cw session from a pyramid request"""
     repo = request.registry['cubicweb.repository']
-    config = request.registry['cubicweb.config']
 
     if not request.authenticated_userid:
-        login, password = config.anonymous_user()
-        session = repo_connect(repo, login, password=password)
+        session = repo_connect(
+            repo, eid=request.registry['cubicweb.anonymous_eid'])
     else:
         session = request._cw_cached_session
 
@@ -194,8 +193,7 @@
     repo = request.registry['cubicweb.repository']
 
     try:
-        session = repo_connect(
-            repo, str(login), __pyramid_directauth=authplugin.EXT_TOKEN)
+        session = repo_connect(repo, eid=login)
         request._cw_cached_session = session
     except:
         log.exception("Failed")
@@ -213,6 +211,11 @@
 def includeme(config):
     repo = config.registry['cubicweb.repository']
 
+    with repo.internal_cnx() as cnx:
+        login = config.registry['cubicweb.config'].anonymous_user()[0]
+        config.registry['cubicweb.anonymous_eid'] = cnx.find(
+            'CWUser', login=login).one().eid
+
     repo.system_source.add_authentifier(authplugin.DirectAuthentifier())
 
     config.add_request_method(