Heim > Fragen und Antworten > Hauptteil
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可以查询得到数据库中的数据,但通过程序不行。请指教