flask使用sqlite数据库的连接

Flask web开发一书中,按照书上的代码一开始可以运行,但是在shell中进行数据库的修改,插入与删除时,在提交会话的时候会出现提示多线程的问题,这个问题的解决是在配置数据时便在原来的URI中加上?check_same_thread=False这句话,就可以了。

完整代码如下:

#数据库申明
basedir = os.path.abspath(os.path.dirname(__file__))
app.config['SQLALCHEMY_DATABASE_URI'] = \
    'sqlite:///' + os.path.join(basedir, 'data.sqlite')+'?check_same_thread=False'  
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False  
db = SQLAlchemy(app)  
#定义模型
class Role(db.Model): 
    __tablename__ = 'roles'  
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(64), unique=True)
    users = db.relationship('User', backref='role',lazy='dynamic')

    def __repr__(self):
        return '' % self.name


class User(db.Model): 
    __tablename__ = 'users' 
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(64), unique=True, index=True)
    role_id = db.Column(db.Integer, db.ForeignKey('roles.id'))

    def __repr__(self):
        return '' % self.username
#上下文处理器
@app.shell_context_processor
def make_shell_context():
    return dict(db=db,User=User,Role=Role)
#默认链接
@app.route('/',methods=['GET','POST'])
def index():
    form = NameFrom()
    if form.validate_on_submit():
        user = User.query.filter_by(username=form.name.data).first()
        if user is None:
            user = User(username=form.name.data)
            db.session.add(user)
            db.session.commit()
            session['known']=False
        else:
            session['known']=True
        session['name'] = form.name.data
        form.name.data=''
        return redirect(url_for('index'))
    return render_template('index.html',\
                           current_time=datetime.utcnow(),\
                           form=form,name=session.get('name'),\
                           known=session.get('known',False))

html如下:

index.html:

{% extends "base.html" %}

{% import "bootstrap/wtf.html" as wtf %}

{% block title %}Flasky{% endblock %}

{% block page_content %}

{
    { wtf.quick_form(form) }}
{% endblock %}

base.html:

{% extends "bootstrap/base.html" %}

{% block title %}Flasky{% endblock %}

{% block head %}
{
    { super() }}


{% endblock %}

{% block navbar %}

{% endblock %}

{% block content %}
{% for message in get_flashed_messages() %}
{ { message }}
{% endfor %} {% block page_content %}{% endblock %}
{% endblock %} {% block scripts %} { { super() }} { { moment.include_moment() }} {% endblock %}

你可能感兴趣的:(数据库,Python,Flask,Python,Flask,web开发,数据库)