TypeError:'NoneType'对象在Flask中使用SQLite3没有属性'__getitem__'

时间:2014-05-17 19:05:57

标签: python sqlite flask

编辑:我发现了导致NoneType错误的原因,抱歉打扰了你。

在我的代码中,我想打开我的records.db并获取其中的最后一个索引然后使用此索引作为上传文件的名称(增加一个),但我的方法仅适用于普通的python脚本,在Flask中我得到NoneType错误..

这是我的代码:

import os
import datetime
import subprocess
import sqlite3
import sys
from flask import Flask, render_template, request, redirect, url_for, g
from werkzeug import secure_filename

app = Flask(__name__)
app.config['UPLOAD_FOLDER'] = 'uploads'
app.config['ALLOWED_EXTENSIONS'] = set(['txt', 'gro', 'doc', 'docx'])

DATABASE = 'records.db'

def allowed_file(filename):
    return '.' in filename and \
           filename.rsplit('.', 1)[1] in app.config['ALLOWED_EXTENSIONS']

def get_db():
    db = getattr(g, '_database', None)
    if db is None:
        db = g._database = sqlite3.connect(DATABASE)
    return db

def get_id():
    cur = get_db().cursor()
    cur.execute('SELECT id FROM Records ORDER BY id DESC LIMIT 1;')
    number = cur.fetchone()
    filenum = int(number[0])
    return filenum + 1

@app.teardown_appcontext
def close_connection(exception):
    db = getattr(g, '_database', None)
    if db is not None:
        db.close()

@app.route('/')
def index():
    return render_template('index.html')

@app.route('/upload', methods = ['POST'])
def upload():
    num = get_id()
    file = request.files['file']
    if file and allowed_file(file.filename):
        file.save(os.path.join(app.config['UPLOAD_FOLDER'], num.filename))
        subprocess.call(['python', '/home/martyna/Dropbox/programowanie/project_firefox/topologia.py', 'uploads/'+num.filename])
        return "Thank you for uploading"


if __name__ == '__main__':
    app.debug = True
    app.run(host='0.0.0.0')

而且:filenum = int(number[0])导致我的错误。我将不胜感激任何帮助。

完整错误跟踪:

Traceback (most recent call last):
  File "/home/martyna/Dropbox/programowanie/project_firefox/venv/lib/python2.7/site-packages/flask/app.py", line 1836, in __call__
    return self.wsgi_app(environ, start_response)
  File "/home/martyna/Dropbox/programowanie/project_firefox/venv/lib/python2.7/site-packages/flask/app.py", line 1820, in wsgi_app
    response = self.make_response(self.handle_exception(e))
  File "/home/martyna/Dropbox/programowanie/project_firefox/venv/lib/python2.7/site-packages/flask/app.py", line 1403, in handle_exception
    reraise(exc_type, exc_value, tb)
  File "/home/martyna/Dropbox/programowanie/project_firefox/venv/lib/python2.7/site-packages/flask/app.py", line 1817, in wsgi_app
    response = self.full_dispatch_request()
  File "/home/martyna/Dropbox/programowanie/project_firefox/venv/lib/python2.7/site-packages/flask/app.py", line 1477, in full_dispatch_request
    rv = self.handle_user_exception(e)
  File "/home/martyna/Dropbox/programowanie/project_firefox/venv/lib/python2.7/site-packages/flask/app.py", line 1381, in handle_user_exception
    reraise(exc_type, exc_value, tb)
  File "/home/martyna/Dropbox/programowanie/project_firefox/venv/lib/python2.7/site-packages/flask/app.py", line 1475, in full_dispatch_request
    rv = self.dispatch_request()
  File "/home/martyna/Dropbox/programowanie/project_firefox/venv/lib/python2.7/site-packages/flask/app.py", line 1461, in dispatch_request
    return self.view_functions[rule.endpoint](**req.view_args)
  File "/home/martyna/Dropbox/programowanie/project_firefox/hello.py", line 46, in upload
    filenum = int(number[0]) + 1
TypeError: 'NoneType' object has no attribute '__getitem__'

1 个答案:

答案 0 :(得分:3)

您的Records表格中可能没有任何元素。因此,cur.fetchone()会返回None,因此您有效地尝试访问None[0],因此会显示错误消息。

顺便说一下,错误消息告诉您,您[0]的内容是None,所以如果你看一下这一行,你唯一要做的就是{{1}是[0]。因此,调试此类问题的一个好方法是在违规行之前添加类似number的内容,这通常会挑战我对变量内容的一些基本信念:)