这几天一直在学习<<flask web开发>>, 在学习到5.8节,操作数据库时,一直报错,连续三天,一直在找原因,各种百度,最后发现解决方法有二:
一、更换成mysql数据库,这种解决方案不太好,因为我们没有根据实例做出结果来;
第二种方法:hello.py
import os from flask import Flask, render_template, session, redirect, url_for, flash from flask_bootstrap import Bootstrap from flask_moment import Moment from flask_wtf import FlaskForm from wtforms import StringField, SubmitField from wtforms.validators import DataRequired from flask_sqlalchemy import SQLAlchemy basedir = os.path.abspath(os.path.dirname(__file__)) app = Flask(__name__) app.config['SECRET_KEY'] = 'hard to guess string' # app.config['SQLALCHEMY_DATABASE_URI'] = "sqlite:///D:/PycharmProjects/hello/data.sqlite" # app.config['SQLALCHEMY_COMMIT_ON_TEARDOWN'] = True # # app.config['SQLALCHEMY_DATABASE_URI'] =\ # 'sqlite:///' + os.path.join(basedir, 'data.sqlite') # app.config['SQLALCHEMY_COMMIT_ON_TEARDOWN'] = True # app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql://root:root@localhost:3306/test?charset=utf8mb4' app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///' + os.path.join(basedir, 'data.sqlite') app.config['SQLALCHEMY_COMMIT_ON_TEARDOWN'] = True app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False bootstrap = Bootstrap(app) moment = Moment(app) 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') def __repr__(self): return '<Role %r>' % 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 '<User %r>' % self.username # def __repr__(self): # return '%s (%r, %r,%r)' % (self.__class__.__name__, self.id, self.username, self.role_id) class NameForm(FlaskForm): name = StringField('What is your name?', validators=[DataRequired()]) submit = SubmitField('Submit') @app.errorhandler(404) def page_not_found(e): return render_template('404.html'), 404 @app.errorhandler(500) def internal_server_error(e): return render_template('500.html'), 500 @app.route('/', methods=['GET', 'POST']) def index(): form = NameForm() if form.validate_on_submit(): old_name = session.get('name') if old_name is not None and old_name != form.name.data: flash('Looks like you have changed your name!') session['name'] = form.name.data return redirect(url_for('index')) return render_template('index.html', form=form, name=session.get('name')) if __name__ == '__main__': app.run(debug=True)
然后,在PyCharm开发工具中的Python Console中开始输入命令
PyDev console: starting.
Python 3.6.2 (v3.6.2:5fd33b5, Jul 8 2017, 04:57:36) [MSC v.1900 64 bit (AMD64)] on win32
from hello import db
db.drop_all()
db.create_all()
from hello import Role, User
admin_role = Role(name='Admin')
mod_role = Role(name='Moderator')
user_role= Role(name='User')
user_john = User(username='john',role=admin_role)
user_susan = User(username='susan',role=user_role)
user_david = User(username='david',role=user_role)
db.session.add_all([admin_role, mod_role, user_role,user_john, user_susan, user_david])
db.session.commit()
print(admin_role.id)
1
Role.query.all()
Traceback (most recent call last):
File "D:\PycharmProjects\hello\venv\lib\site-packages\sqlalchemy\engine\base.py", line 1127, in _execute_context
context = constructor(dialect, self, conn, *args)
File "D:\PycharmProjects\hello\venv\lib\site-packages\sqlalchemy\engine\default.py", line 637, in _init_compiled
self.cursor = self.create_cursor()
File "D:\PycharmProjects\hello\venv\lib\site-packages\sqlalchemy\engine\default.py", line 952, in create_cursor
return self._dbapi_connection.cursor()
File "D:\PycharmProjects\hello\venv\lib\site-packages\sqlalchemy\pool.py", line 970, in cursor
return self.connection.cursor(*args, **kwargs)
sqlite3.ProgrammingError: SQLite objects created in a thread can only be used in that same thread.The object was created in thread id 5668 and this is thread id 9904
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "<input>", line 1, in <module>
File "D:\PycharmProjects\hello\venv\lib\site-packages\sqlalchemy\orm\query.py", line 2726, in all
return list(self)
File "D:\PycharmProjects\hello\venv\lib\site-packages\sqlalchemy\orm\query.py", line 2878, in __iter__
return self._execute_and_instances(context)
File "D:\PycharmProjects\hello\venv\lib\site-packages\sqlalchemy\orm\query.py", line 2901, in _execute_and_instances
result = conn.execute(querycontext.statement, self._params)
File "D:\PycharmProjects\hello\venv\lib\site-packages\sqlalchemy\engine\base.py", line 948, in execute
return meth(self, multiparams, params)
File "D:\PycharmProjects\hello\venv\lib\site-packages\sqlalchemy\sql\elements.py", line 269, in _execute_on_connection
return connection._execute_clauseelement(self, multiparams, params)
File "D:\PycharmProjects\hello\venv\lib\site-packages\sqlalchemy\engine\base.py", line 1060, in _execute_clauseelement
compiled_sql, distilled_params
File "D:\PycharmProjects\hello\venv\lib\site-packages\sqlalchemy\engine\base.py", line 1132, in _execute_context
None, None)
File "D:\PycharmProjects\hello\venv\lib\site-packages\sqlalchemy\engine\base.py", line 1413, in _handle_dbapi_exception
exc_info
File "D:\PycharmProjects\hello\venv\lib\site-packages\sqlalchemy\util\compat.py", line 203, in raise_from_cause
reraise(type(exception), exception, tb=exc_tb, cause=cause)
File "D:\PycharmProjects\hello\venv\lib\site-packages\sqlalchemy\util\compat.py", line 186, in reraise
raise value.with_traceback(tb)
File "D:\PycharmProjects\hello\venv\lib\site-packages\sqlalchemy\engine\base.py", line 1127, in _execute_context
context = constructor(dialect, self, conn, *args)
File "D:\PycharmProjects\hello\venv\lib\site-packages\sqlalchemy\engine\default.py", line 637, in _init_compiled
self.cursor = self.create_cursor()
File "D:\PycharmProjects\hello\venv\lib\site-packages\sqlalchemy\engine\default.py", line 952, in create_cursor
return self._dbapi_connection.cursor()
File "D:\PycharmProjects\hello\venv\lib\site-packages\sqlalchemy\pool.py", line 970, in cursor
return self.connection.cursor(*args, **kwargs)
sqlalchemy.exc.ProgrammingError: (sqlite3.ProgrammingError) SQLite objects created in a thread can only be used in that same thread.The object was created in thread id 5668 and this is thread id 9904 [SQL: 'SELECT roles.id AS roles_id, roles.name AS roles_name \nFROM roles'] [parameters: [{}]] (Background on this error at: http://sqlalche.me/e/f405)
看到这些是不是疯了,没办法重新写,
~~~~~
db.session.commit()
Traceback (most recent call last):
File "<input>", line 1, in <module>
File "D:\PycharmProjects\hello\venv\lib\site-packages\sqlalchemy\orm\scoping.py", line 153, in do
return getattr(self.registry(), name)(*args, **kwargs)
File "D:\PycharmProjects\hello\venv\lib\site-packages\sqlalchemy\orm\session.py", line 937, in commit
self.transaction.commit()
File "D:\PycharmProjects\hello\venv\lib\site-packages\sqlalchemy\orm\session.py", line 459, in commit
self._assert_active(prepared_ok=True)
File "D:\PycharmProjects\hello\venv\lib\site-packages\sqlalchemy\orm\session.py", line 276, in _assert_active
% self._rollback_exception
sqlalchemy.exc.InvalidRequestError: This Session's transaction has been rolled back due to a previous exception during flush. To begin a new transaction with this Session, first issue Session.rollback(). Original exception was: (sqlite3.ProgrammingError) SQLite objects created in a thread can only be used in that same thread.The object was created in thread id 5700 and this is thread id 556 [SQL: 'INSERT INTO roles (name) VALUES (?)'] [parameters: [{'name': 'Admin'}]] (Background on this error at: http://sqlalche.me/e/f405)
谁能告诉我,这又是怎么回事?
from hello import db
db.drop_all()
db.create_all()
from hello import Role, User
admin_role = Role(name='Admin')
mod_role = Role(name='Moderator')
user_role= Role(name='User')
user_john = User(username='john',role=admin_role)
user_susan = User(username='susan',role=user_role)
user_david = User(username='david',role=user_role)
db.session.add_all([admin_role, mod_role, user_role,user_john, user_susan, user_david])
try:
db.session.commit()
except:
db.session.rollback()
raise
finally:
db.session.close()
#注意此处有空格
Role.query.all()
[<Role 'Admin'>, <Role 'Moderator'>, <Role 'User'>]
最后居然好了,
相关推荐
Flask Web Development 2018最新版本 “You should have some level of Python coding experience to make the most of this book. Although the book assumes no previous Flask knowledge, Python concepts such ...
《Flask-Web开发实战》是一本专注于使用Python Flask框架进行Web应用开发的书籍。Flask作为轻量级的Web服务器网关接口(WSGI)微框架,以其简洁、灵活的特点受到众多开发者喜爱。这本书旨在帮助初学者和有一定经验的...
该资源为Flask-1.1.2-py2.py3-none-any.whl,欢迎下载使用哦!
基于YOLOv9+Flask构建的目标检测Web应用+使用步骤.zip基于YOLOv9+Flask构建的目标检测Web应用+使用步骤.zip基于YOLOv9+Flask构建的目标检测Web应用+使用步骤.zip基于YOLOv9+Flask构建的目标检测Web应用+使用步骤.zip...
Flask 是一个轻量级的Web服务程序框架,它基于Python编写,被广泛应用于构建小型到中型的Web应用。Flask的核心设计理念是保持简单,同时提供足够的灵活性以适应各种复杂的开发需求。在这个"flask-3.0.2.tar.gz...
Flask-1.0.2-py2.py3-none-any.whl
基于Python的Flask实现WEB后台权限管理系统源码+使用文档.zip基于Python的Flask实现WEB后台权限管理系统源码+使用文档.zip基于Python的Flask实现WEB后台权限管理系统源码+使用文档.zip基于Python的Flask实现WEB后台...
Flask-1.1.1-py2.py3-none-any.whl
《Flask Web框架全方位解析》 Flask是一个轻量级的Python Web开发框架,由Armin Ronacher开发,因其简洁而灵活的特性,在Python Web开发领域广泛应用。本套剖析资料全面深入地探讨了Flask框架的各个方面,旨在帮助...
资源包含文件:设计报告word+答辩PPT+项目源码+使用说明+项目截图 注意: 1. 全部源代码在code文件夹中 2. 全部报告在报告文件夹中,其中最重要的报告文档是“详细设计报告” 环境要求:python 3.x * 如何查看本地...
标题中的“flask-web实现天气预报.zip”表明这是一个关于使用Flask框架开发Web应用程序的项目,主要用于展示天气预报。Flask是Python编程语言中的一个微型Web服务器和Web应用框架,因其轻量级和可扩展性而广受欢迎。...
**Flask Web开发实战——Python Web开发的轻量级选择** Flask,作为一个轻量级的Python Web框架,自2010年开源以来,已经在开发者社区中积累了极高的声誉。与Django这样的全功能框架相比,Flask以其灵活性、简单性...
该资源为Flask-0.12.5-py2.py3-none-any.whl,欢迎下载使用哦!
Flask Web开发实战中文版flask基础支持,http,开发,测试,实战内容都有,强推
《Python Flask Web开发实战》是一门综合性的课程,旨在教授用户如何使用Python的Flask框架进行Web应用的构建。这门课程涵盖了从基础到高级的多个主题,通过一系列的视频教程,帮助学习者掌握Flask的核心概念和技术...
在本压缩包“基于flask搭建web应用-python源码.zip”中,包含了使用Python的Flask框架构建Web应用程序的相关源代码。Flask是一款轻量级的Web服务程序,以其简洁和模块化的特性深受开发者喜爱。这里我们将深入探讨...