--- a/cwconfig.py Fri Apr 09 19:18:55 2010 +0200
+++ b/cwconfig.py Fri Apr 09 19:19:28 2010 +0200
@@ -1019,7 +1019,9 @@
return i18n.compile_i18n_catalogs(sourcedirs, i18ndir, langs)
def sendmails(self, msgs):
- """msgs: list of 2-uple (message object, recipients)"""
+ """msgs: list of 2-uple (message object, recipients). Return False
+ if connection to the smtp server failed, else True.
+ """
server, port = self['smtp-host'], self['smtp-port']
SMTP_LOCK.acquire()
try:
@@ -1028,7 +1030,7 @@
except Exception, ex:
self.exception("can't connect to smtp server %s:%s (%s)",
server, port, ex)
- return
+ return False
heloaddr = '%s <%s>' % (self['sender-name'], self['sender-addr'])
for msg, recipients in msgs:
try:
@@ -1039,6 +1041,7 @@
smtp.close()
finally:
SMTP_LOCK.release()
+ return True
set_log_methods(CubicWebConfiguration, logging.getLogger('cubicweb.configuration'))
--- a/entity.py Fri Apr 09 19:18:55 2010 +0200
+++ b/entity.py Fri Apr 09 19:19:28 2010 +0200
@@ -202,6 +202,59 @@
needcheck = False
return mainattr, needcheck
+ @classmethod
+ def cw_instantiate(cls, execute, **kwargs):
+ """add a new entity of this given type
+
+ Example (in a shell session):
+
+ >>> companycls = vreg['etypes'].etype_class(('Company')
+ >>> personcls = vreg['etypes'].etype_class(('Person')
+ >>> c = companycls.cw_instantiate(req.execute, name=u'Logilab')
+ >>> personcls.cw_instantiate(req.execute, firstname=u'John', lastname=u'Doe',
+ ... works_for=c)
+
+ """
+ rql = 'INSERT %s X' % cls.__regid__
+ relations = []
+ restrictions = set()
+ pending_relations = []
+ for attr, value in kwargs.items():
+ if isinstance(value, (tuple, list, set, frozenset)):
+ if len(value) == 1:
+ value = iter(value).next()
+ else:
+ del kwargs[attr]
+ pending_relations.append( (attr, value) )
+ continue
+ if hasattr(value, 'eid'): # non final relation
+ rvar = attr.upper()
+ # XXX safer detection of object relation
+ if attr.startswith('reverse_'):
+ relations.append('%s %s X' % (rvar, attr[len('reverse_'):]))
+ else:
+ relations.append('X %s %s' % (attr, rvar))
+ restriction = '%s eid %%(%s)s' % (rvar, attr)
+ if not restriction in restrictions:
+ restrictions.add(restriction)
+ kwargs[attr] = value.eid
+ else: # attribute
+ relations.append('X %s %%(%s)s' % (attr, attr))
+ if relations:
+ rql = '%s: %s' % (rql, ', '.join(relations))
+ if restrictions:
+ rql = '%s WHERE %s' % (rql, ', '.join(restrictions))
+ created = execute(rql, kwargs).get_entity(0, 0)
+ for attr, values in pending_relations:
+ if attr.startswith('reverse_'):
+ restr = 'Y %s X' % attr[len('reverse_'):]
+ else:
+ restr = 'X %s Y' % attr
+ execute('SET %s WHERE X eid %%(x)s, Y eid IN (%s)' % (
+ restr, ','.join(str(r.eid) for r in values)),
+ {'x': created.eid}, build_descr=False)
+ return created
+
def __init__(self, req, rset=None, row=None, col=0):
AppObject.__init__(self, req, rset=rset, row=row, col=col)
dict.__init__(self)
--- a/req.py Fri Apr 09 19:18:55 2010 +0200
+++ b/req.py Fri Apr 09 19:19:28 2010 +0200
@@ -119,9 +119,6 @@
def set_entity_cache(self, entity):
pass
- # XXX move to CWEntityManager or even better as factory method (unclear
- # where yet...)
-
def create_entity(self, etype, **kwargs):
"""add a new entity of the given type
@@ -133,48 +130,8 @@
"""
_check_cw_unsafe(kwargs)
- execute = self.execute
- rql = 'INSERT %s X' % etype
- relations = []
- restrictions = set()
- cachekey = []
- pending_relations = []
- for attr, value in kwargs.items():
- if isinstance(value, (tuple, list, set, frozenset)):
- if len(value) == 1:
- value = iter(value).next()
- else:
- del kwargs[attr]
- pending_relations.append( (attr, value) )
- continue
- if hasattr(value, 'eid'): # non final relation
- rvar = attr.upper()
- # XXX safer detection of object relation
- if attr.startswith('reverse_'):
- relations.append('%s %s X' % (rvar, attr[len('reverse_'):]))
- else:
- relations.append('X %s %s' % (attr, rvar))
- restriction = '%s eid %%(%s)s' % (rvar, attr)
- if not restriction in restrictions:
- restrictions.add(restriction)
- cachekey.append(attr)
- kwargs[attr] = value.eid
- else: # attribute
- relations.append('X %s %%(%s)s' % (attr, attr))
- if relations:
- rql = '%s: %s' % (rql, ', '.join(relations))
- if restrictions:
- rql = '%s WHERE %s' % (rql, ', '.join(restrictions))
- created = execute(rql, kwargs, cachekey).get_entity(0, 0)
- for attr, values in pending_relations:
- if attr.startswith('reverse_'):
- restr = 'Y %s X' % attr[len('reverse_'):]
- else:
- restr = 'X %s Y' % attr
- execute('SET %s WHERE X eid %%(x)s, Y eid IN (%s)' % (
- restr, ','.join(str(r.eid) for r in values)),
- {'x': created.eid}, 'x', build_descr=False)
- return created
+ cls = self.vreg['etypes'].etype_class(etype)
+ return cls.cw_instantiate(self.execute, **kwargs)
def ensure_ro_rql(self, rql):
"""raise an exception if the given rql is not a select query"""
--- a/server/test/unittest_session.py Fri Apr 09 19:18:55 2010 +0200
+++ b/server/test/unittest_session.py Fri Apr 09 19:19:28 2010 +0200
@@ -37,6 +37,7 @@
def test_dbapi_query(self):
session = self.repo.internal_session()
self.assertFalse(session.running_dbapi_query)
+ session.close()
if __name__ == '__main__':
unittest_main()
--- a/web/views/basecontrollers.py Fri Apr 09 19:18:55 2010 +0200
+++ b/web/views/basecontrollers.py Fri Apr 09 19:19:28 2010 +0200
@@ -91,11 +91,11 @@
# anonymous connection is allowed and the page will be displayed or
# we'll be redirected to the login form
msg = self._cw._('you have been logged out')
- if self._cw.https:
- # XXX hack to generate an url on the http version of the site
- self._cw._base_url = self._cw.vreg.config['base-url']
- self._cw.https = False
- return self._cw.build_url('view', vid='index', __message=msg)
+ # force base_url so on dual http/https configuration, we generate an url
+ # on the http version of the site
+ return self._cw.build_url('view', vid='index', __message=msg,
+ base_url=self._cw.vreg.config['base-url'])
+
class ViewController(Controller):
"""standard entry point :
@@ -595,25 +595,14 @@
for entity in rset.entities():
yield entity
- @property
- @cached
- def smtp(self):
- mailhost, port = self._cw.config['smtp-host'], self._cw.config['smtp-port']
- try:
- return SMTP(mailhost, port)
- except Exception, ex:
- self.exception("can't connect to smtp server %s:%s (%s)",
- mailhost, port, ex)
- url = self._cw.build_url(__message=self._cw._('could not connect to the SMTP server'))
- raise Redirect(url)
-
def sendmail(self, recipient, subject, body):
- helo_addr = '%s <%s>' % (self._cw.config['sender-name'],
- self._cw.config['sender-addr'])
msg = format_mail({'email' : self._cw.user.get_email(),
'name' : self._cw.user.dc_title(),},
[recipient], body, subject)
- self.smtp.sendmail(helo_addr, [recipient], msg.as_string())
+ if not self._cw.vreg.config.sendmails([(msg, [recipient])]):
+ msg = self._cw._('could not connect to the SMTP server')
+ url = self._cw.build_url(__message=msg)
+ raise Redirect(url)
def publish(self, rset=None):
# XXX this allows users with access to an cubicweb instance to use it as