⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 editdb.py

📁 监控大型网络的软件。能够自动发现拓扑结构
💻 PY
📖 第 1 页 / 共 5 页
字号:
                if len(req.form[field]):                        if not first:                        sql += ','                    sql += "'" + req.form[field] + "'"                    first = False        # Add the id value if we have queried the sequence        if nextId:            sql += ",'" + nextId + "'"        sql += ')'        try:            executeSQL([sql])        except psycopg.IntegrityError, e:            rollbackSQL()            if type(self.unique) is list:                error = 'There already exists an entry with '                first = True                for field in self.unique:                    if not first:                        error += ' and '                    error += field + "='" + req.form[field] + "'"                    first = False            else:                error = "There already exists an entry with the value '" + \                        req.form[self.unique] + "' for the unique field '" +\                        self.unique + "'"        if error:            status.errors.append(error)        else:            if self.sequence:                id = nextId            else:                id = req.form[self.tableIdKey]            entry = self.table(id)            message = 'Added ' + self.singular + ': ' + self.describe(entry)            status.messages.append(message)            action = 'list'        return (status,action,outputForm,id)          def update(self,req,outputForm,selected):        """ Updates one or more entries in the database. Takes data            from form in request object. Overriden by some subclasses             such as pageNetbox. """        status = editdbStatus()        sqllist = []        data = []        error = None             # Get the name of one of the fields that should be present        presentfield = self.fields.keys()[0]        # Use this field to check if there are multiple        # editboxes (multiple entries edited)        if type(req.form[presentfield]) is list:            for i in range(0,len(req.form[presentfield])):                values = {}                for field,descr in self.fields.items():                    # Special case: checkboxes are not posted if                    # they are not selected. Check if the field                    # is present with "req.form[field][i] and                    # catch the indexError exception if it's not                    # present.                    try:                        req.form[field][i]                        # Don't insert empty strings into fields                        # where required = REQ_NONEMPTY                        if len(req.form[field][i]):                            values[field] = req.form[field][i]                        else:                            if descr[1] != REQ_NONEMPTY:                                values[field] = req.form[field][i]                            else:                                # Insert NULL instead                                values[field] = None                    except (KeyError,IndexError):                        # Field not present (ie. unchecked checkbox)                        # Insert NULL                        values[field] = None                # The hidden element UPDATE_ENTRY contains the original ID                data.append((req.form[UPDATE_ENTRY][i],values))        else:            values = {}            for field,descr in self.fields.items():                try:                    req.form[field]                    if len(req.form[field]):                        values[field] = req.form[field]                    else:                        # Don't insert empty strings into fields                        # where required = REQ_NONEMPTY                        if descr[1] != REQ_NONEMPTY:                            values[field] = req.form[field]                        else:                            # Insert NULL instead                            values[field] = None                except KeyError:                    # Field not present (ie. ie unchecked checkbox)                    values[field] = None            # The hidden element UPDATE_ENTRY contains the original ID            data.append((req.form[UPDATE_ENTRY],values))        for i in range(0,len(data)):            sql = 'UPDATE ' + self.tableName + ' SET '            id,fields = data[i]            first = True            for field,value in fields.items():                if not first:                    sql += ','                if value:                    sql += field + "='" + value + "'"                 else:                    sql += field + '=NULL'                first = False            sql += ' WHERE ' + self.tableIdKey + "='" + id + "'"            try:                executeSQL([sql])            except psycopg.IntegrityError:                # Assumes tableIdKey = the unique field                rollbackSQL()                if type(self.unique) is list:                    error = 'There already exists an entry with '                    first = True                    for field in self.unique:                        if not first:                            error += ' and '                        error += field + "='" + req.form[field][i] + "'"                        first = False                    status.errors.append(error)                else:                    error = "There already exists an entry with the value '" + \                            req.form[self.unique] + \                            "' for the unique field '" + self.unique + "'"                    status.errors.append(error)                 # Make a list of id's. If error is returned then the original        # id's are still valid, if-not error then id's might have changed        idlist = []        if error:            for i in range(0,len(data)):                id,fields = data[i]                idlist.append(id)        elif not self.editIdAllowed:            # Id can't be edited by the user, so the ids are the same as            # we started with            for i in range(0,len(data)):                id,fields = data[i]                idlist.append(id)        else:            if type(req.form[self.tableIdKey]) is list:                for i in range(0,len(req.form[self.tableIdKey])):                    idlist.append(req.form[self.tableIdKey][i])            else:                idlist.append(req.form[self.tableIdKey])        action = 'list'        if error:            action = 'edit'        else:            # All entries updated without error, make list to displayed            # in the status header            for entry in idlist:                message = "Updated " + self.singular + ": "                message += self.describe(entry)                status.messages.append(message)        return (status,action,outputForm,selected)     def describe(self,id):        """ Gives a textual description of a database entry.            Used when adding, deleting and updating entries to tell the user            exactly what entries were altered (useful when the id field             of the table only contains a numerical key).            If the edit page class contains a descriptionFormat it             is used. Otherwise it falls back to using the id field            passed to the function.            Remember to only use NOT NULL fields when writing descrFormats            to avoid malformed descriptions. """         description = ''                try:            entry = self.table(id)              if hasattr(self,'descriptionFormat'):                # Use the description format for this page to make a                # nicely formatted description of a database entry                for part in self.descriptionFormat:                    (string,field) = part                    fieldData = ''                    if field:                        # Get data from a db field                        field = field.split('.')                                    if len(field) > 1:                            tempentry = entry                            i=0                            for f in field:                                #if i==1:                                #    raise(repr(tempentry)+':'+f)                                i+=1                                tempentry = getattr(tempentry,f)                                if type(tempentry) is str:                                    # Got the field we're after                                    break                            fieldData = tempentry                        else:                            fieldData = getattr(entry,field[0])                    description += string + str(fieldData)            else:                # Vanilla description (only the id field)                description = "'" + id +"'"         except forgetSQL.NotFound:            # No such id in this table            pass        return description    def delete(self,idList,status):        for id in idList:            try:                deletedName = self.describe(id)                deleteEntry([id],self.tableName,self.tableIdKey)                status.messages.append("Deleted %s: %s" % \                                           (self.singular,deletedName))            except psycopg.IntegrityError:                # Got integrity error while deleting, must check what                # dependencies are blocking.  But firstly, we roll back the                # failed transaction.                rollbackSQL()                error = "Error while deleting %s '%s': " % (self.singular,                                                            deletedName)                errorState = False                for (table,other,key,url) in self.dependencies:                    where = "%s='%s'" % (key,str(id))                    if table.getAll(where):                        errorState = True                        # UGLY.. HTML                        error += "referenced in "  + \                                 "one or more %s " % (other,) + \                                 "<a href=\"%s%s\">" % (url,id) + \                                 "(view report)</a>."                         break                if not errorState:                    # There are no dependencies or couldn't find reference.                    # Give general error                    error += '%s is referenced in another table' % (self.name,)                status.errors.append(error)         return status        class pageCabling(editdbPage):    """ Describes editing of the cabling table. """        basePath = BASEPATH + 'cabling/'    table = nav.db.manage.Cabling    pageName = 'cabling'    tableName = 'cabling'    tableIdKey = 'cablingid'    sequence = 'cabling_cablingid_seq'    editMultipleAllowed = True    editIdAllowed = False    # Unique fields (for errormessages from add/update)    unique = ['roomid','jack']    # Nouns    singular = 'cabling'    plural = 'cablings'    # Delete dependencies    dependencies = [(nav.db.manage.Patch,                     'patches',                     'cablingid',                     '/report/netbox/?roomid=')]    # Description format used by describe(id)    # Example: room 021 (descr) to jack 123, building, office    descriptionFormat = [('\'jack ','jack'),                         (', ','targetroom'),                         (', ','building'),                         ('\' to room \'','room.roomid'),                         (', ','room.location.locationid'),                         ('\'',None)]    pathAdd = EDITPATH + [('Cabling',basePath+'list'),('Add',False)]    pathEdit = EDITPATH + [('Cabling',basePath+'list'),('Edit',False)]    pathDelete = EDITPATH + [('Cabling',basePath+'list'),('Delete',False)]    pathList = EDITPATH + [('Cabling',False)]    class listDef(entryList):        """ Describes the format of the list view of cablings. """        def __init__(self,req,struct,sort,deleteWhere=None):            # Do general init            entryList.__init__(self,req,struct,sort,deleteWhere)                        # Specific init            self.defaultSortBy = 1            # List filters            self.filters = [['Show cablings in room ',                            ('','Select a room'),                            ('roomid,descr',                             'room',                             None,                             '((SELECT count(*) FROM cabling WHERE ' +\                             'cabling.roomid=room.roomid) > 0)',                             'room.roomid'),                             '{id}',                             '{id} ({descr})',                             'flt_room',                             'roomid',                             nav.db.manage.Cabling,                             'room.roomid']]            # list of (heading text, show sortlink, compare function for sort)            self.headingDefinition = [('Select',False,None),                                      ('Room',True,None),                                      ('Jack',True,None),                                      ('Building',True,None),                                      ('Target room',True,None),                                      ('Category',True,None),                                      ('Description',True,None)]            self.cellDefinition = [(('cablingid,roomid,jack,' + \                                     'building,targetroom,category,descr',                                     'cabling',                                     None,                                     None,                                     'roomid,jack'),                                    [(None,None,entryListCell.CHECKBOX,None,None),                                     (1,'{p}edit/{id}',None,None,None),                                     (2,None,None,None,None),                                     (3,None,None,None,None),                                     (4,None,None,None,None),                                     (5,None,None,None,None),                                     (6,None,None,None,None)])]    class editbox(editbox):        """ Describes fields for adding and editing cabling entries.            The template uses this field information to draw the form. """        def __init__(self,page,req=None,editId=None,formData=None):            self.page = page.pageName

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -