示例#1
0
    def manage_advanced(self, max_rows, max_cache, cache_time,
                        class_name, class_file, direct=None,
                        REQUEST=None, zclass=''):
        """Change advanced properties

        The arguments are:

        max_rows -- The maximum number of rows to be returned from a query.

        max_cache -- The maximum number of results to cache

        cache_time -- The maximum amound of time to use a cached result.

        class_name -- The name of a class that provides additional
          attributes for result record objects. This class will be a
          base class of the result record class.

        class_file -- The name of the file containing the class
          definition.

        The class file normally resides in the 'Extensions'
        directory, however, the file name may have a prefix of
        'product.', indicating that it should be found in a product
        directory.

        For example, if the class file is: 'ACMEWidgets.foo', then an
        attempt will first be made to use the file
        'lib/python/Products/ACMEWidgets/Extensions/foo.py'. If this
        failes, then the file 'Extensions/ACMEWidgets.foo.py' will be
        used.

        """
        # paranoid type checking
        if type(max_rows) is not type(1):
            max_rows=atoi(max_rows)
        if type(max_cache) is not type(1):
            max_cache=atoi(max_cache)
        if type(cache_time) is not type(1):
            cache_time=atoi(cache_time)
        class_name=str(class_name)
        class_file=str(class_file)

        self.max_rows_ = max_rows
        self.max_cache_, self.cache_time_ = max_cache, cache_time
        self._v_cache={}, Bucket()
        self.class_name_, self.class_file_ = class_name, class_file
        self._v_brain=getBrain(self.class_file_, self.class_name_, 1)
        self.allow_simple_one_argument_traversal=direct

        if zclass:
            for d in self.aq_acquire('_getProductRegistryData')('zclasses'):
                if ("%s/%s" % (d.get('product'),d.get('id'))) == zclass:
                    self._zclass=d['meta_class']
                    break


        if REQUEST is not None:
            m="ZSQL Method advanced settings have been set"
            return self.manage_advancedForm(self,REQUEST,manage_tabs_message=m)
示例#2
0
    def advanced_edit(self, max_rows=1000, max_cache=100, cache_time=0,
                        class_name='', class_file='',
                        REQUEST=None):
        """Change advanced properties

        The arguments are:

        max_rows -- The maximum number of rows to be returned from a query.

        max_cache -- The maximum number of results to cache

        cache_time -- The maximum amound of time to use a cached result.

        class_name -- The name of a class that provides additional
          attributes for result record objects. This class will be a
          base class of the result record class.

        class_file -- The name of the file containing the class
          definition.

        The class file normally resides in the 'Extensions'
        directory, however, the file name may have a prefix of
        'product.', indicating that it should be found in a product
        directory.

        For example, if the class file is: 'ACMEWidgets.foo', then an
        attempt will first be made to use the file
        'lib/python/Products/ACMEWidgets/Extensions/foo.py'. If this
        failes, then the file 'Extensions/ACMEWidgets.foo.py' will be
        used.

        """
        context = self.context
        # paranoid type checking
        if type(max_rows) is not type(1):
            max_rows = atoi(max_rows)
        if type(max_cache) is not type(1):
            max_cache = atoi(max_cache)
        if type(cache_time) is not type(1):
            cache_time = atoi(cache_time)
        class_name = str(class_name)
        class_file = str(class_file)

        context.max_rows_ = max_rows
        context.max_cache_, context.cache_time_ = max_cache, cache_time
        context._v_sql_cache = {}, Bucket()
        context.class_name_, context.class_file_ = class_name, class_file
        context._v_sql_brain = getBrain(context.class_file_,
                                        context.class_name_, 1)
示例#3
0
 def manage_advanced(self, class_name, class_file, REQUEST=None):
     """Change Advanced Settings"""
     self.class_name_, self.class_file_ = class_name, class_file
     self._v_brain = getBrain(self.class_file_, self.class_name_, 1)
     return self.manage_editedDialog(REQUEST)
示例#4
0
文件: DA.py 项目: bendavis78/zope
    def __call__(self, REQUEST=None, __ick__=None, src__=0, test__=0, **kw):
        """Call the database method

        The arguments to the method should be passed via keyword
        arguments, or in a single mapping object. If no arguments are
        given, and if the method was invoked through the Web, then the
        method will try to acquire and use the Web REQUEST object as
        the argument mapping.

        The returned value is a sequence of record objects.
        """

        __traceback_supplement__ = (SQLMethodTracebackSupplement, self)

        if REQUEST is None:
            if kw:
                REQUEST = kw
            else:
                if hasattr(self, 'REQUEST'):
                    REQUEST = self.REQUEST
                else:
                    REQUEST = {}

        # connection hook
        c = self.connection_id
        # for backwards compatability
        hk = self.connection_hook
        # go get the connection hook and call it
        if hk:
            c = getattr(self, hk)()

        try:
            dbc = getattr(self, c)
        except AttributeError:
            raise AttributeError, (
                "The database connection <em>%s</em> cannot be found." % (c))

        try:
            DB__ = dbc()
        except:
            raise DatabaseError, ('%s is not connected to a database' %
                                  self.id)

        if hasattr(self, 'aq_parent'):
            p = self.aq_parent
        else:
            p = None

        argdata = self._argdata(REQUEST)
        argdata['sql_delimiter'] = '\0'
        argdata['sql_quote__'] = dbc.sql_quote__

        security = getSecurityManager()
        security.addContext(self)
        try:
            try:
                query = apply(self.template, (p, ), argdata)
            except TypeError, msg:
                msg = str(msg)
                if string.find(msg, 'client') >= 0:
                    raise NameError("'client' may not be used as an " +
                                    "argument name in this context")
                else:
                    raise
        finally:
            security.removeContext(self)

        if src__:
            return query

        if self.cache_time_ > 0 and self.max_cache_ > 0:
            result = self._cached_result(DB__, query, self.max_rows_, c)
        else:
            result = DB__.query(query, self.max_rows_)

        if hasattr(self, '_v_brain'):
            brain = self._v_brain
        else:
            brain = self._v_brain = getBrain(self.class_file_,
                                             self.class_name_)

        if type(result) is type(''):
            f = StringIO()
            f.write(result)
            f.seek(0)
            result = File(f, brain, p, None)
        else:
            result = Results(result, brain, p, None)
        columns = result._searchable_result_columns()
        if test__ and columns != self._col:
            self._col = columns

        # If run in test mode, return both the query and results so
        # that the template doesn't have to be rendered twice!
        if test__:
            return query, result

        return result
示例#5
0
 def connect(self):
   return getBrain("UbercartTest", "UbercartTestConnector", reload=1)()
示例#6
0
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
#
##############################################################################

from App.Extensions import getBrain
from Acquisition import Explicit, aq_base
from lxml import etree
from zLOG import LOG, ERROR, INFO
from base64 import b16encode, b16decode

SEPARATOR = '\n'

NodeBrain = getBrain('TioSafeBrain', 'Node', reload=1)
TransactionBrain = getBrain('TioSafeBrain', 'Transaction', reload=1)

class OscommerceNode(NodeBrain):

  def __init__(self, *args, **kw):
    NodeBrain.__init__(self, *args, **kw)
    # country property is used in gid computation of organisation
    # transform it to category as soon as possible
    if getattr(self, 'country', None) is not None:
      try:
        self.country = self.getIntegrationSite().getCategoryFromMapping(
          category = 'Country/%s' % self.country, create_mapping=True,
          create_mapping_line=True,
          ).split('/', 1)[-1]
      except ValueError, msg:
示例#7
0
 def connect(self):
     return getBrain("OxatisTest", "OxatisTestConnector", reload=1)()
 def _callFUT(self, module, name, reload=0, modules=None):
     from App.Extensions import getBrain
     if modules is not None:
         return getBrain(module, name, reload, modules)
     return getBrain(module, name, reload)
示例#9
0
文件: DA.py 项目: alvsgithub/erp5
def DA__call__(self, REQUEST=None, __ick__=None, src__=0, test__=0, **kw):
    """Call the database method

    The arguments to the method should be passed via keyword
    arguments, or in a single mapping object. If no arguments are
    given, and if the method was invoked through the Web, then the
    method will try to acquire and use the Web REQUEST object as
    the argument mapping.

    The returned value is a sequence of record objects.
    """
    __traceback_supplement__ = (SQLMethodTracebackSupplement, self)

    c = kw.pop("connection_id", None)
    #if c is not None:
      #LOG("DA", 300, "connection %s provided to %s" %(c, self.id))
    # patch: dynamic brain configuration
    zsql_brain = kw.pop('zsql_brain', None)
    # patch end


    if REQUEST is None:
        if kw: REQUEST=kw
        else:
            if hasattr(self, 'REQUEST'): REQUEST=self.REQUEST
            else: REQUEST={}

    # Patch to implement dynamic connection id
    # Connection id is retrieve from user preference
    if c is None:
      physical_path = self.getPhysicalPath()
      # XXX cleaner solution will be needed
      if 'portal_catalog' not in physical_path and\
         'cmf_activity' not in self.connection_id and\
         'transactionless' not in self.connection_id:
        try:
          archive_id = self.portal_preferences.getPreferredArchive()
        except AttributeError:
          pass
        else:
          if archive_id not in (None, ''):
            archive_id = archive_id.split('/')[-1]
            #LOG("DA__call__, archive_id 2", 300, archive_id)
            archive = self.portal_archives._getOb(archive_id, None)
            if archive is not None:
              c = archive.getConnectionId()
              #LOG("DA call", INFO, "retrieved connection %s from preference" %(c,))

    if c is None:
      # connection hook
      c = self.connection_id
      # for backwards compatability
      hk = self.connection_hook
      # go get the connection hook and call it
      if hk: c = getattr(self, hk)()
    #LOG("DA__call__ connection", 300, c)
    try: dbc=getattr(self, c)
    except AttributeError:
        raise AttributeError, (
            "The database connection <em>%s</em> cannot be found." % (
            c))

    try: DB__=dbc()
    except: raise DatabaseError, (
        '%s is not connected to a database' % self.id)

    p = aq_parent(self) # None if no aq_parent

    argdata=self._argdata(REQUEST)
    argdata['sql_delimiter']='\0'
    argdata['sql_quote__']=dbc.sql_quote__

    security=getSecurityManager()
    security.addContext(self)
    try:
        try:     query=apply(self.template, (p,), argdata)
        except TypeError, msg:
            msg = str(msg)
            if find(msg,'client') >= 0:
                raise NameError("'client' may not be used as an " +
                    "argument name in this context")
            else: raise
    finally: security.removeContext(self)

    if src__: return query

    if self.cache_time_ > 0 and self.max_cache_ > 0:
        result=self._cached_result(DB__, query, self.max_rows_, c)
    else:
      try:
#         if 'portal_ids' in query:
#           LOG("DA query", INFO, "query = %s" %(query,))
        result=DB__.query(query, self.max_rows_)
      except:
        LOG("DA call raise", ERROR, "DB = %s, c = %s, query = %s" %(DB__, c, query), error=sys.exc_info())
        raise

    # patch: dynamic brain configuration
    if zsql_brain is not None:
        try:
          class_file_, class_name_ = zsql_brain.rsplit('.', 1)
        except:
          #import pdb; pdb.post_mortem()
          raise
        brain = getBrain(class_file_, class_name_)
        # XXX remove this logging for performance
        LOG(__name__, INFO, "Using special brain: %r\n" % (brain,))
    else:
        brain = getBrain(self.class_file_, self.class_name_)

    if type(result) is type(''):
        f=StringIO()
        f.write(result)
        f.seek(0)
        result=RDB.File(f,brain,p)
    else:
        result=Results(result, brain, p)
    columns=result._searchable_result_columns()
    if test__ and columns != self._col: self._col=columns

    # If run in test mode, return both the query and results so
    # that the template doesn't have to be rendered twice!
    if test__: return query, result

    return result
示例#10
0
 def connect(self):
   return getBrain("OxatisTest", "OxatisTestConnector", reload=1)()
示例#11
0
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
#
##############################################################################

from App.Extensions import getBrain
from Acquisition import Explicit, aq_base
from lxml import etree
from zLOG import LOG, ERROR, INFO
from base64 import b16encode, b16decode

SEPARATOR = '\n'

NodeBrain = getBrain('TioSafeBrain', 'Node', reload=1)
ResourceBrain = getBrain('TioSafeBrain', 'Resource', reload=1)
TransactionBrain = getBrain('TioSafeBrain', 'Transaction', reload=1)
LastIdBrain = getBrain('TioSafeBrain', 'LastId', reload=1)

class UbercartNode(NodeBrain):
  def __init__(self, *args, **kw):
    NodeBrain.__init__(self, *args, **kw)
    # country property is used in gid computation of organisation
    # transform it to category as soon as possible
    if getattr(self, 'country', None) is not None:
      try:
        self.country = self.getIntegrationSite().getCategoryFromMapping(
          category = 'Country/%s' % self.country, create_mapping=True,
          create_mapping_line=True,
          ).split('/', 1)[-1]
示例#12
0
文件: DA.py 项目: ccwalkerjm/erp5
      try:
#         if 'portal_ids' in query:
#           LOG("DA query", INFO, "query = %s" %(query,))
        result=DB__.query(query, self.max_rows_)
      except:
        LOG("DA call raise", ERROR, "DB = %s, c = %s, query = %s" %(DB__, c, query), error=sys.exc_info())
        raise

    # patch: dynamic brain configuration
    if zsql_brain is not None:
        try:
          class_file_, class_name_ = zsql_brain.rsplit('.', 1)
        except:
          #import pdb; pdb.post_mortem()
          raise
        brain = getBrain(class_file_, class_name_)
        # XXX remove this logging for performance
        LOG(__name__, INFO, "Using special brain: %r\n" % (brain,))
    else:
        brain = getBrain(self.class_file_, self.class_name_)

    if type(result) is type(''):
        f=StringIO()
        f.write(result)
        f.seek(0)
        result=RDB.File(f,brain,p)
    else:
        result=Results(result, brain, p)
    columns=result._searchable_result_columns()
    if test__ and columns != self._col: self._col=columns
示例#13
0
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
#
##############################################################################

from App.Extensions import getBrain
from Acquisition import Explicit, aq_base
from lxml import etree
from zLOG import LOG, ERROR, INFO
from base64 import b16encode, b16decode

SEPARATOR = "\n"

NodeBrain = getBrain("TioSafeBrain", "Node", reload=1)
ResourceBrain = getBrain("TioSafeBrain", "Resource", reload=1)
TransactionBrain = getBrain("TioSafeBrain", "Transaction", reload=1)


class ZencartNode(NodeBrain):
    def __init__(self, *args, **kw):
        NodeBrain.__init__(self, *args, **kw)
        # country property is used in gid computation of organisation
        # transform it to category as soon as possible
        if getattr(self, "country", None) is not None:
            try:
                self.country = (
                    self.getIntegrationSite()
                    .getCategoryFromMapping(
                        category="Country/%s" % self.country, create_mapping=True, create_mapping_line=True
示例#14
0
 def connect(self):
     return getBrain("MagentoTest", "MagentoTestConnector", reload=1)()
示例#15
0
 def _results(self, rows):
     if hasattr(self, '_v_brain'):
         brain = self._v_brain
     else:
         brain = self._v_brain = getBrain(self.class_file_, self.class_name_)
     return Results((self._items, rows), brains=brain, parent=None)
示例#16
0
文件: DA.py 项目: nacho22martin/tesis
    def __call__(self, REQUEST=None, __ick__=None, src__=0, test__=0, **kw):
        """Call the database method

        The arguments to the method should be passed via keyword
        arguments, or in a single mapping object. If no arguments are
        given, and if the method was invoked through the Web, then the
        method will try to acquire and use the Web REQUEST object as
        the argument mapping.

        The returned value is a sequence of record objects.
        """

        __traceback_supplement__ = (SQLMethodTracebackSupplement, self)

        if REQUEST is None:
            if kw:
                REQUEST=kw
            else:
                if hasattr(self, 'REQUEST'):
                    REQUEST=self.REQUEST
                else:
                    REQUEST={}

        # connection hook
        c = self.connection_id
        # for backwards compatability
        hk = self.connection_hook
        # go get the connection hook and call it
        if hk:
            c = getattr(self, hk)()
           
        try:
            dbc=getattr(self, c)
        except AttributeError:
            raise AttributeError, (
                "The database connection <em>%s</em> cannot be found." % (
                c))

        try:
            DB__=dbc()
        except: raise DatabaseError, (
            '%s is not connected to a database' % self.id)

        if hasattr(self, 'aq_parent'):
            p=self.aq_parent
        else:
            p=None

        argdata=self._argdata(REQUEST)
        argdata['sql_delimiter']='\0'
        argdata['sql_quote__']=dbc.sql_quote__

        security=getSecurityManager()
        security.addContext(self)
        try:
            try:
                query=apply(self.template, (p,), argdata)
            except TypeError, msg:
                msg = str(msg)
                if string.find(msg,'client') >= 0:
                    raise NameError("'client' may not be used as an " +
                        "argument name in this context")
                else: raise
        finally:
            security.removeContext(self)

        if src__:
            return query

        if self.cache_time_ > 0 and self.max_cache_ > 0:
            result=self._cached_result(DB__, query, self.max_rows_, c)
        else:
            result=DB__.query(query, self.max_rows_)

        if hasattr(self, '_v_brain'):
            brain=self._v_brain
        else:
            brain=self._v_brain=getBrain(self.class_file_, self.class_name_)

        if type(result) is type(''):
            f=StringIO()
            f.write(result)
            f.seek(0)
            result = File(f,brain,p, None)
        else:
            result = Results(result, brain, p, None)
        columns = result._searchable_result_columns()
        if test__ and columns != self._col:
            self._col=columns

        # If run in test mode, return both the query and results so
        # that the template doesn't have to be rendered twice!
        if test__:
            return query, result

        return result
 def connect(self):
   return getBrain("VirtueMartTest", "VirtueMartTestConnector", reload=1)()
示例#18
0
            result = DB__.query(query, self.max_rows_)
        except:
            LOG("DA call raise",
                ERROR,
                "DB = %s, c = %s, query = %s" % (DB__, c, query),
                error=True)
            raise

    # patch: dynamic brain configuration
    if zsql_brain is not None:
        try:
            class_file_, class_name_ = zsql_brain.rsplit('.', 1)
        except:
            #import pdb; pdb.post_mortem()
            raise
        brain = getBrain(class_file_, class_name_)
        # XXX remove this logging for performance
        LOG(__name__, INFO, "Using special brain: %r\n" % (brain, ))
    else:
        brain = getBrain(self.class_file_, self.class_name_)

    if type(result) is type(''):
        f = StringIO()
        f.write(result)
        f.seek(0)
        result = RDB.File(f, brain, p)
    else:
        result = Results(result, brain, p)
    columns = result._searchable_result_columns()
    if test__ and columns != self._col: self._col = columns
示例#19
0
 def connect(self):
     return getBrain("UbercartTest", "UbercartTestConnector", reload=1)()
示例#20
0
class WebServiceRequest(XMLObject, ZopePageTemplate):
    # CMF Type Definition
    meta_type = 'ERP5 Web Service Request'
    portal_type = 'Web Service Request'

    # Declarative security
    security = ClassSecurityInfo()
    security.declareObjectProtected(Permissions.AccessContentsInformation)

    # Default Properties
    property_sheets = (PropertySheet.Base, PropertySheet.XMLObject,
                       PropertySheet.CategoryCore, PropertySheet.DublinCore,
                       PropertySheet.Reference, PropertySheet.SimpleItem,
                       PropertySheet.Arrow, PropertySheet.Data,
                       PropertySheet.WebServiceRequest)

    isIndexable = 0
    content_type = "text/html"

    def getIntegrationSite(self, ):
        """
    return integration site if the wsr
    """
        def cached_getIntegrationSite(self):
            parent = self.getParentValue()
            while parent.getPortalType() != "Integration Site":
                parent = parent.getParentValue()
            return parent.getPath()

        cached_getIntegrationSite = CachingMethod(
            cached_getIntegrationSite,
            id="WebServiceRequest_getIntegrationSite",
            cache_factory="erp5_content_long")

        integration_site = cached_getIntegrationSite(self)
        return self.getPortalObject().portal_integrations.restrictedTraverse(
            integration_site)

    def edit(self, **kw):
        """
    Override the edit method to register page template values
    """
        if kw.get('data'):
            self.pt_edit(text=kw['data'], content_type=kw['content_type'])
        return self._edit(**kw)

    def getIDParameterName(self):
        """
    Return the parameter name used for id
    """
        def cached_getIDParameterName(self):
            if self.getDestinationObjectType():
                return "%s_id" % (self.getDestinationObjectType().replace(
                    " ", "_").lower())
            else:
                return "id"

        cached_getIDParameterName = CachingMethod(
            cached_getIDParameterName,
            id="WebServiceRequest_getIDParameterName",
            cache_factory="erp5_content_long")
        return cached_getIDParameterName(self)

    def __call__(self,
                 context_document=None,
                 test_mode=False,
                 REQUEST=None,
                 **kw):
        """
    Make this object callable. It will call the method defined in reference using
    the web service connector it is related to
    """
        if REQUEST is not None:
            return self.view()
        #LOG("_call__", 300, kw)
        if kw.has_key("id"):
            kw[self.getIDParameterName()] = str(kw.pop("id"))

        sub_id = None
        if kw.has_key(self.getIDParameterName()) and ID_SEPARATOR in kw[
                self.getIDParameterName()]:
            kw[self.getIDParameterName()], sub_id = kw[
                self.getIDParameterName()].split(ID_SEPARATOR)

        object_list = []
        method_name = self.getReference()
        try:
            connection = self.getSourceValue().getConnection()
        except AttributeError:
            LOG(
                "__call__ of %s" % (self.getPath(), ), ERROR,
                "Error on getting connection, connector is %s" %
                (self.getSourceValue(), ))
            connection = None
        if connection is None:
            if test_mode:
                self._edit(last_request_parameter=str(kw),
                           last_request_result="",
                           last_request_path="",
                           last_request_error=
                           "No connection available, connector is %s" %
                           (self.getSourceValue(), ))
                return []
            else:
                raise ValueError("No connection available")

        # Add specific parameters defined on integration site
        site = self.getIntegrationSite()
        if site.getLanguage():
            kw['language'] = site.getLanguage()

        if site.getStartDate():
            kw['start_date'] = site.getStartDate()

        if site.getStopDate():
            kw['stop_date'] = site.getStopDate()

        # Render page template content
        if self.hasData():
            #LOG("passing options %s to self %s" %(kw, self.getPath()), 300, "CALL")
            pt_data = self.pt_render(extra_context={
                'options': kw,
            })
            pt_data = pt_data.replace('\n', '')
            kw = {'data': pt_data}

        # transforms parameters
        #LOG("before transformation of params %s" %(kw), 300, self.getPath())
        new_kw = kw.copy()
        args = []
        if self.getDestination():
            for k, v in kw.iteritems():
                new_key = site.getMappingFromProperty(
                    self.getDestinationValue(), k)
                new_kw.pop(k)
                if new_key is None:
                    # Some web service does not need explicit parameters
                    args.append(v)
                else:
                    new_kw[new_key] = v

        kw = new_kw
        #LOG("calling with params args = %s, kw = %s" %(args, kw), 300, self.getPath())
        error = None

        def callRequest(self, method_name, *args, **kw):
            connection = self.getSourceValue().getConnection()
            return getattr(connection, method_name)(*args, **kw)

        # cached_callRequest = CachingMethod(callRequest,
        #                                    id="WebServiceRequest_callRequest",
        #                                    cache_factory="erp5_content_short")

        # Call the method
        try:
            url, xml = callRequest(self, method_name, *args, **kw)
        except ConnectionError, msg:
            if test_mode:
                error = msg
                url = connection.url
                xml = ""
            else:
                raise

        # Register information for testing/debug purposes
        if test_mode:
            self._edit(last_request_parameter="args = %s, kw = %s" %
                       (str(args), str(kw)),
                       last_request_result=xml,
                       last_request_path=url,
                       last_request_error=error)

        def buildParserDict(root_mapping):
            parser_dict = {}
            for mapping in root_mapping.contentValues():
                if len(mapping.contentValues()):
                    sub_parser_dict = buildParserDict(mapping)
                    parser_dict[mapping.getSourceReference()] = (
                        mapping.getDestinationReference(), sub_parser_dict)
                else:
                    parser_dict[mapping.getSourceReference()] = (
                        mapping.getDestinationReference(), None)
            return parser_dict

        if self.hasDestination():
            sub_parser_dict = buildParserDict(self.getDestinationValue())
            parser_dict = {
                self.getDestinationValue().getSourceReference():
                (self.getDestinationValue().getDestinationReference(),
                 sub_parser_dict)
            }
        else:
            return []

        # Parse the result
        if self.getSourceValue().getParserMethodId():
            method = getattr(self, self.getSourceValue().getParserMethodId())
            result_list = method(result=xml, parser_dict=parser_dict)
        else:
            if type(xml) == list:
                result_list = self.parse_dict(parser_dict, xml)
            else:
                parser = etree.XMLParser(target=NewEchoDictTarget(parser_dict))
                # FIXME: About prestashop sync, '&' and '&' char in xml cause problem
                # xml = xml.replace('&', '')
                #LOG("got XML from WSR %s = %s" %(method_name, xml), 300, "will call parser with %s" %(parser_dict))
                result_list = []
                try:
                    result_list = etree.XML(
                        xml,
                        parser,
                    )
                    #LOG("result_list = %r" %(result_list), 300, "")
                except etree.XMLSyntaxError:
                    LOG(
                        "WebServiceRequest", ERROR,
                        "Bad XML returned by request %s with kw = %s, xml = %s"
                        % (self.getPath(), kw, xml))
                    if test_mode:
                        self._edit(
                            last_request_error=
                            "Bad XML returned by request, impossible to parse it"
                        )
                    else:
                        raise ValueError(
                            "Bad XML returned by request %s with kw = %s, xml = %s"
                            % (self.getPath(), kw, xml))

        brain = getBrain(self.brain_class_file,
                         self.brain_class_name,
                         reload=1)

        script_id = self.getBrainBuilderScript(None)
        if script_id is not None:
            brain_builder_script = getattr(self, script_id, None)
        else:
            brain_builder_script = None
        if brain_builder_script is not None:
            for result in result_list:
                object_list.extend(brain_builder_script(result, brain))
            if sub_id:
                object_list = [
                    object_list[int(sub_id) - 1],
                ]
        else:
            for result in result_list:
                #LOG("initialising brain", INFO, "data is %s" %(result))
                obj = brain(context=self,
                            object_type=self.getDestinationObjectType(),
                            **result)
                object_list.append(obj)

        return object_list
示例#21
0
                    query = query.encode('UTF-8')

        if context.cache_time_ > 0 and context.max_cache_ > 0:
            result = self._cached_result(DB__, (query, context.max_rows_))
        else:
            try:
                result = DB__.query(query, context.max_rows_)
            except ConflictError:
                raise
            except:
                log_exc(msg='Database query failed', reraise=1)

        if hasattr(context, '_v_sql_brain'):
            brain = context._v_sql_brain
        else:
            brain = context._v_sql_brain = getBrain(context.class_file_,
                                                    context.class_name_)

        if type(result) is type(''):
            f = StringIO()
            f.write(result)
            f.seek(0)
            result = RDB.File(f, brain, p, None)
        else:
            if db_encoding:
                # Encode result before we wrap it in Result object
                # We will change the encoding from source to either the specified target_encoding
                # or the site default encoding

                # The data is a list of tuples of column data
                encoded_result = []
                for row in result[1]:
示例#22
0
文件: DA.py 项目: Elbagoury/erp5
def DA__call__(self, REQUEST=None, __ick__=None, src__=0, test__=0, **kw):
    """Call the database method

    The arguments to the method should be passed via keyword
    arguments, or in a single mapping object. If no arguments are
    given, and if the method was invoked through the Web, then the
    method will try to acquire and use the Web REQUEST object as
    the argument mapping.

    The returned value is a sequence of record objects.
    """
    __traceback_supplement__ = (SQLMethodTracebackSupplement, self)

    c = kw.pop("connection_id", None)
    #if c is not None:
    #LOG("DA", 300, "connection %s provided to %s" %(c, self.id))
    # patch: dynamic brain configuration
    zsql_brain = kw.pop('zsql_brain', None)
    # patch end

    if REQUEST is None:
        if kw: REQUEST = kw
        else:
            if hasattr(self, 'REQUEST'): REQUEST = self.REQUEST
            else: REQUEST = {}

    # Patch to implement dynamic connection id
    # Connection id is retrieve from user preference
    if c is None:
        physical_path = self.getPhysicalPath()
        # XXX cleaner solution will be needed
        if 'portal_catalog' not in physical_path and\
           'cmf_activity' not in self.connection_id and\
           'transactionless' not in self.connection_id:
            try:
                archive_id = self.portal_preferences.getPreferredArchive()
            except AttributeError:
                pass
            else:
                if archive_id not in (None, ''):
                    archive_id = archive_id.split('/')[-1]
                    #LOG("DA__call__, archive_id 2", 300, archive_id)
                    archive = self.portal_archives._getOb(archive_id, None)
                    if archive is not None:
                        c = archive.getConnectionId()
                        #LOG("DA call", INFO, "retrieved connection %s from preference" %(c,))

    if c is None:
        # connection hook
        c = self.connection_id
        # for backwards compatability
        hk = self.connection_hook
        # go get the connection hook and call it
        if hk: c = getattr(self, hk)()
    #LOG("DA__call__ connection", 300, c)
    try:
        dbc = getattr(self, c)
    except AttributeError:
        raise AttributeError, (
            "The database connection <em>%s</em> cannot be found." % (c))

    try:
        DB__ = dbc()
    except:
        raise DatabaseError, ('%s is not connected to a database' % self.id)

    p = aq_parent(self)  # None if no aq_parent

    argdata = self._argdata(REQUEST)
    argdata['sql_delimiter'] = '\0'
    argdata['sql_quote__'] = dbc.sql_quote__

    security = getSecurityManager()
    security.addContext(self)
    try:
        try:
            query = apply(self.template, (p, ), argdata)
        except TypeError, msg:
            msg = str(msg)
            if find(msg, 'client') >= 0:
                raise NameError("'client' may not be used as an " +
                                "argument name in this context")
            else:
                raise
    finally:
        security.removeContext(self)

    if src__: return query

    if self.cache_time_ > 0 and self.max_cache_ > 0:
        result = self._cached_result(DB__, query, self.max_rows_, c)
    else:
        try:
            #         if 'portal_ids' in query:
            #           LOG("DA query", INFO, "query = %s" %(query,))
            result = DB__.query(query, self.max_rows_)
        except:
            LOG("DA call raise",
                ERROR,
                "DB = %s, c = %s, query = %s" % (DB__, c, query),
                error=sys.exc_info())
            raise

    # patch: dynamic brain configuration
    if zsql_brain is not None:
        try:
            class_file_, class_name_ = zsql_brain.rsplit('.', 1)
        except:
            #import pdb; pdb.post_mortem()
            raise
        brain = getBrain(class_file_, class_name_)
        # XXX remove this logging for performance
        LOG(__name__, INFO, "Using special brain: %r\n" % (brain, ))
    else:
        brain = getBrain(self.class_file_, self.class_name_)

    if type(result) is type(''):
        f = StringIO()
        f.write(result)
        f.seek(0)
        result = RDB.File(f, brain, p)
    else:
        result = Results(result, brain, p)
    columns = result._searchable_result_columns()
    if test__ and columns != self._col: self._col = columns

    # If run in test mode, return both the query and results so
    # that the template doesn't have to be rendered twice!
    if test__: return query, result

    return result
示例#23
0
    def _callFUT(self, module, name, reload=0, modules=None):
        from App.Extensions import getBrain

        if modules is not None:
            return getBrain(module, name, reload, modules)
        return getBrain(module, name, reload)
示例#24
0
文件: DA.py 项目: bendavis78/zope
    def manage_advanced(self,
                        max_rows,
                        max_cache,
                        cache_time,
                        class_name,
                        class_file,
                        direct=None,
                        REQUEST=None,
                        connection_hook=None):
        """Change advanced properties

        The arguments are:

        max_rows -- The maximum number of rows to be returned from a query.

        max_cache -- The maximum number of results to cache

        cache_time -- The maximum amound of time to use a cached result.

        class_name -- The name of a class that provides additional
          attributes for result record objects. This class will be a
          base class of the result record class.

        class_file -- The name of the file containing the class
          definition.

        The class file normally resides in the 'Extensions'
        directory, however, the file name may have a prefix of
        'product.', indicating that it should be found in a product
        directory.

        For example, if the class file is: 'ACMEWidgets.foo', then an
        attempt will first be made to use the file
        'lib/python/Products/ACMEWidgets/Extensions/foo.py'. If this
        failes, then the file 'Extensions/ACMEWidgets.foo.py' will be
        used.

        """
        # paranoid type checking
        if type(max_rows) is not type(1):
            max_rows = string.atoi(max_rows)
        if type(max_cache) is not type(1):
            max_cache = string.atoi(max_cache)
        if type(cache_time) is not type(1):
            cache_time = string.atoi(cache_time)
        class_name = str(class_name)
        class_file = str(class_file)

        self.max_rows_ = max_rows
        self.max_cache_, self.cache_time_ = max_cache, cache_time
        self._v_cache = {}, Bucket()
        self.class_name_, self.class_file_ = class_name, class_file
        self._v_brain = getBrain(self.class_file_, self.class_name_, 1)
        self.allow_simple_one_argument_traversal = direct

        self.connection_hook = connection_hook

        if REQUEST is not None:
            m = "ZSQL Method advanced settings have been set"
            return self.manage_advancedForm(self,
                                            REQUEST,
                                            manage_tabs_message=m)
示例#25
0
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
#
##############################################################################

from App.Extensions import getBrain
from Acquisition import Explicit, aq_base
from lxml import etree
from zLOG import LOG, ERROR, INFO
from base64 import b16encode, b16decode

SEPARATOR = '\n'

NodeBrain = getBrain('TioSafeBrain', 'Node', reload=1)
ResourceBrain = getBrain('TioSafeBrain', 'Resource', reload=1)
TransactionBrain = getBrain('TioSafeBrain', 'Transaction', reload=1)
LastIdBrain = getBrain('TioSafeBrain', 'LastId', reload=1)


class Transaction(TransactionBrain):
    """
    This class allows to build the TioSafe XML of a Sale Order and to sync.
  """
    __allow_access_to_unprotected_subobjects__ = 1

    def __init__(self, object_type, context, **kw):
        TransactionBrain.__init__(self, object_type, context, **kw)
        self.reference = self.id
示例#26
0
 def connect(self):
   return getBrain("MagentoTest", "MagentoTestConnector", reload=1)()