Python 使用flask时数据表中的键错误列_1

Python 使用flask时数据表中的键错误列_1,python,datatable,flask,pymongo,Python,Datatable,Flask,Pymongo,我在烧瓶中使用数据表。由于庞大的数据库,我试图使用服务器端,但我得到了错误列_1。我想不出我的问题。 这是我的python代码 @app.route("/_retrieve_server_data") def get_server_data(): columns = [ 'column_1', 'column_2', 'column_3', 'column_4'] index_column = "_id" collection = "AssetMapping" r

我在烧瓶中使用数据表。由于庞大的数据库,我试图使用服务器端,但我得到了错误列_1。我想不出我的问题。 这是我的python代码

@app.route("/_retrieve_server_data")
def get_server_data():
    columns = [ 'column_1', 'column_2', 'column_3', 'column_4']
    index_column = "_id"
    collection = "AssetMapping"
    results = DataTablesServer(request, columns, index_column, collection).output_result()
    # return the results as a string for the datatable
    print json.dumps(results)
    return json.dumps(results)

# translation for sorting between datatables and mongodb
order_dict = {'asc': 1, 'desc': -1}

class DataTablesServer(object):
    def __init__( self, request, columns, index, collection):
        self.columns = columns
        self.index = index
        self.collection = collection
        # values specified by the datatable for filtering, sorting, paging
        self.request_values = request.values
        # connection to your mongodb (see pymongo docs). this is defaulted to localhost
        self.dbh = MongoClient()
        # results from the db
        self.result_data = None
        # total in the table after filtering
        self.cardinality_filtered = 0
        # total in the table unfiltered
        self.cardinality = 0
        self.run_queries()

    def output_result(self):
        output = {}
        output['sEcho'] = str(int(self.request_values['sEcho']))
        output['iTotalRecords'] = str(self.cardinality)
        output['iTotalDisplayRecords'] = str(self.cardinality_filtered)
        aaData_rows = []
        for row in self.result_data:
            aaData_row = []
            for i in range( len(self.columns) ):
                print self.columns[i]
                print aaData_row.append(row[ 'column_1' ].replace('"','\\"')) 
                aaData_row.append(row[ self.columns[i] ].replace('"','\\"'))
        # add additional rows here that are not represented in the database
        # aaData_row.append(('''<input id='%s' type='checkbox'></input>''' % (str(row[ self.index ]))).replace('\\', ''))
            aaData_rows.append(aaData_row)
        output['aaData'] = aaData_rows

        return output

    def run_queries(self):
        # 'mydb' is the actual name of your database

        survey = self.dbh.survey
        # pages has 'start' and 'length' attributes
        pages = self.paging()
        # the term you entered into the datatable search
        _filter = self.filtering()
        # the document field you chose to sort
        sorting = self.sorting()
        # get result from db to display on the current page
        self.result_data = list(survey[self.collection].find(spec = _filter,
            skip = pages.start,
            limit = pages.length,
            sort = sorting))

        # length of filtered set
        self.cardinality_filtered = len(list(survey[self.collection].find(spec = _filter)))
        # length of all results you wish to display in the datatable, unfiltered
        self.cardinality = len(list( survey[self.collection].find()))
    def filtering(self):
        # build your filter spec
        _filter = {}
        if ( self.request_values.has_key('sSearch') ) and ( self.request_values['sSearch'] != "" ):
        # the term put into search is logically concatenated with 'or' between all columns
            or_filter_on_all_columns = []
            for i in range( len(self.columns) ):
                column_filter = {}
                # case insensitive partial string matching pulled from user input
                column_filter[self.columns[i]] = {'$regex': self.request_values['sSearch'], '$options': 'i'}
                or_filter_on_all_columns.append(column_filter)
                _filter['$or'] = or_filter_on_all_columns
        # individual column filtering - uncomment if needed
        #and_filter_individual_columns = []
        #for i in range(len(columns)):
        # if (request_values.has_key('sSearch_%d' % i) and request_values['sSearch_%d' % i] != ''):
        # individual_column_filter = {}
        # individual_column_filter[columns[i]] = {'$regex': request_values['sSearch_%d' % i], '$options': 'i'}
        # and_filter_individual_columns.append(individual_column_filter)

        #if and_filter_individual_columns:
        # _filter['$and'] = and_filter_individual_columns
            return _filter
    def sorting(self):
        order = []
        # mongo translation for sorting order
        if ( self.request_values['iSortCol_0'] != "" ) and ( self.request_values['iSortingCols'] > 0 ):
            for i in range( int(self.request_values['iSortingCols']) ):
                # column number
                column_number = int(self.request_values['iSortCol_'+str(i)])
        # sort direction
                sort_direction = self.request_values['sSortDir_'+str(i)]
                order.append((self.columns[column_number], order_dict[sort_direction]))
            return order
    def paging(self):
        pages = namedtuple('pages', ['start', 'length'])
        if (self.request_values['iDisplayStart'] != "" ) and (self.request_values['iDisplayLength'] != -1 ):
            pages.start = int(self.request_values['iDisplayStart'])
            pages.length = int(self.request_values['iDisplayLength'])
        return pages
当在现有键集中找不到映射字典键时,将引发。此错误似乎发生在线路中

aaData_row.append(row[ self.columns[i] ].replace('"','\\"'))
这条线有点长,调试起来有点复杂。所以你可以这样重写它:

row_index = self.columns[i]
actual_row = row[row_index]
row_replaced = actual_row.replace('"','\\"')
aaData_row.append(row_replaced)
现在你应该得到同样的错误,但你可以更好地找到你的错误

将代码的复杂性保持在较低水平总是一个好主意。这同样适用于每一行代码的复杂性

顺便说一句,电话线

print aaData_row.append(row[ 'column_1' ].replace('"','\\"'))

具有向aaData_行追加字符串的副作用。不确定这是否是您想要的。

请发布printrow的结果。@unutbu print row:{u'assetType':u'Test',u'end':datetime.datetime2014,4,7,6,19,31,88000,u'name':u'AssetMapping',u'form':u'AssetMapping',u'picture':u'1396851566956.jpg',u'created':datetime.datetime2014,4,7,6,22,45,672000,u'data\u'path':u'./data/AssetMapping\u/2014-04-07\u 12-03-45',u'whatFamousFor':u'Trst',u'start'datetime,2014,7、6、18、45、400000,u“地区”:u“博卡拉”,u“设备id”:u“359435051262207”,u“资产名称”:u“罗汉”,u“id”:ObjectId'5342443695c190113b437e56',u“完整”:True,u“gps”:u“28.2283292 83.9887244 0.0 34.5”KeyError是有意义的。行dict没有列\u 1键。@unutbu那么我应该如何附加行\u数据。这个问题不可能回答,因为您没有指定要附加到aaData\u行的内容。如果您确实要附加行,那么aaData\u row.appendrow。可能您需要其他内容,但我们怎么可能知道呢?I我正在尝试调试代码,但未能成功。但让我来试一试,我必须直接传递列名。通过静态传递列名,它可以工作,但我有不同的表,因此我需要在遇到问题的地方动态传递列名。请查看
print aaData_row.append(row[ 'column_1' ].replace('"','\\"'))