使用flask的数据表中的键错误column_1

时间:2014-04-19 10:32:11

标签: python datatable flask pymongo

我在烧瓶中使用数据表。由于庞大的数据库我试图使用服务器端,但我得到错误column_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

当我print self.result_data显示我的收藏时。附加值时出错。aaData_row.append(row[ self.columns[i] ].replace('"','\\"')) 运行上面的代码时出现以下错误:

Traceback (most recent call last):
  File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 1836, in __call__
    return self.wsgi_app(environ, start_response)
  File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 1820, in wsgi_app
    response = self.make_response(self.handle_exception(e))
  File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 1403, in handle_exception
    reraise(exc_type, exc_value, tb)
  File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 1817, in wsgi_app
    response = self.full_dispatch_request()
  File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 1477, in full_dispatch_request
    rv = self.handle_user_exception(e)
  File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 1381, in handle_user_exception
    reraise(exc_type, exc_value, tb)
  File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 1475, in full_dispatch_request
    rv = self.dispatch_request()
  File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 1461, in dispatch_request
    return self.view_functions[rule.endpoint](**req.view_args)
  File "/home/bhim/remo/surveyApp_bibek/surveyApp.py", line 262, in get_server_data
    results = DataTablesServer(request, columns, index_column, collection).output_result()
  File "/home/bhim/remo/surveyApp_bibek/surveyApp.py", line 297, in output_result
     aaData_row.append(row[ self.columns[i] ].replace('"','\\"'))
KeyError: 'column_1'

1 个答案:

答案 0 :(得分:0)

KeyError是“在现有密钥集中找不到映射(字典)密钥时引发的。”此错误似乎发生在

行中
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_row的副作用。不确定这是不是你想要的。