我是python的新手所以我通过Flaskr教程创建了一个简单的聊天。当我到第4步创建数据库时,我得到以下错误:
>>> import __init__
>>> init_db()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "__init__.py", line 34, in init_db
db = get_db()
File "__init__.py", line 29, in get_db
g.sqlite_db = connect_db()
File "__init__.py", line 22, in connect_db
rv = sqlite3.connect(app.config['DATABASE'])
NameError: global name 'connect' is not defined
这是__ init __。py:
# coding: utf-8
from flask import Flask, render_template, request, redirect, session, url_for, escape, g, abort, flash
from functools import wraps
from time import *
import locale
import os
import sqlite3
app = Flask(__name__)
app.config.from_object(__name__)
app.config.update(dict(
DATABASE='chat.db',
DEBUG=True,
SECRET_KEY = "very secret",
USERNAME="user",
PASSWORD="password"
))
app.config.from_envvar("FLASKR_SETTINGS", silent=True)
def connect_db():
rv = sqlite3.connect(app.config['DATABASE'])
rv.row_factory = sqlite3.Row
return rv
def get_db():
if not hasattr(g, "sqlite_db"):
g.sqlite_db = connect_db()
return g.sqlite_db
def init_db():
with app.app_context():
db = get_db()
with app.open_resource("schema.sql", mode="r") as f:
db.cursor().executescript(f.read())
db.commit()
#some @app.route
@app.teardown_appcontext
def close_db(error):
if hasattr(g, "sqlite_db"):
g.sqlite_db.close()
if __name__ == "__main__":
app.run(debug=True)
这是schema.sql:
drop table if exists entries;
create table entries (
id integer primary key autoincrement,
name text not null,
text text not null
);
抱歉我的英语不好,这不是我的第一语言。 谢谢你的回答!
大卫
编辑:我在带有mod_wsgi的apche服务器上运行它