python - Flask 连接sqlite 提示 has no attribute 'cursor'
PHP中文网
PHP中文网 2017-04-17 16:37:00
0
1
756

flask0.10.1 程序结构如下:
app
| static
|--style.css
| templates
|--show_entries.html
|--layout.html
|--login.html
| flaskr.py
| sqldb.db

flaskr.py:

#-*-code=utf-8-*-
import os
import sqlite3
from flask import Flask,request,session,g,redirect,url_for,abort,render_template,flash

app = Flask(__name__)

DATABASE='sqldb.db'
DEBUG=True
SECRET_KEY='8888'
USERNAME='admin'
PASSWORD='PWD'

app.config.from_object(__name__)

def get_db():
    if not hasattr(g,'sqlite_db'):
        g.sqlite_db = sqlite3.connect(app.config['DATABASE'])
        g.sqlite_db.text_factory = str
    return g.sqlite_db

@app.teardown_appcontext
def teardown_db(exception):
    if hasattr(g,'sqlite_db'):
        g.sqlite_db.close()

@app.route('/')
def show_entries():
    db=get_db()
    cur = db.cursor()
    cur.execute('select e.title,e.body,u.username from entries e left join users u on e.user_id=u.id');
    entries = cur.fetchall()
    return render_template('show_entries.html',entries=entries)

@app.route('/add/',methods=['POST'])
def add_entries():
    if not session.get('logged_in'):
        abort(401)
    db = get_db
    cur = db.cursor()
    cur.execute('insert into entries(title,body,user_id) values(?,?,?)',[request.form['title'],request.form['body'],session.get('userid')])
    db.commit()
    flash('New entries was successfully added.')
    return redirect(url_for('show_entries'))
……

在访问"/"时,不显示数据库中的内容,添加entries时,报错如题:
AttributeError: 'function' object has no attribute 'cursor'。指示到add_entries函数中 cur = db.cursor()处,
个人感觉,不显示数据是不是没有连接到数据库?添加数据此处报错就很奇怪,是路径设置不对么?我在交互shell中手工输入原生sql可以查询得到数据库中的数据,但通过程序不行。请指教

PHP中文网
PHP中文网

认证0级讲师

모든 응답(1)
PHPzhong

db = get_db가 get_db()로 변경되었습니다.

최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿