Python Forum
sqlite objects in thread can only be used in the same thread
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
sqlite objects in thread can only be used in the same thread
#1
hi.
I made a table showing user accounts in my app and i tought it would be a good thing to add an edit function to it so i can edit the accounts. Every thing works till i get to the saveing part of the edit function there i get this error

Error:
ProgrammingError: SQLite objects created in a thread can only be used in that same thread.The object was created in thread id and this is thread
Something like that. The funny thing i get this error on my laptop but not on my stationary but also nothing happens there i can spam the save button and nothing happens all i see in the console is POST msg.

Could any one help me with this? I can provide more code if this i post is not enough.

main.py
This is for the table.

@app.route('/show_users')
@login_required(role="admin")
def show_users():
    results = []

    qry = db_session.query(User)
    results = qry.all()

    if not results:
        flash('Inget kunde hittas!')
        return redirect('adminindex')
    else:
        # display results
        table = Users(results)
        table.border = True
        return render_template('show_users.html', table=table)
this is for the account edit function.
@app.route('/redigera_anvandare/<int:id>', methods=['GET', 'POST'])
@login_required(role="admin")
def redigera_anvandare(id):
    """
    Add / edit an item in the database
    """
    qry = db_session.query(User).filter(
                User.id==id)
    anvandare = qry.first()

    if anvandare:
        form = UserForm(formdata=request.form, obj=anvandare)
        if request.method == 'POST' and form.validate():
            # save edits
            save_changes3(anvandare, form)
            flash('Artikeln har blivit uppdaterad!')
            return redirect('/adminindex')
        return render_template('redigera_användare.html', form=form)
    else:
        return 'Error loading #{id}'.format(id=id)
Forms.py
class UserForm(FlaskForm):
    user = StringField('Användarnamn:', validators=[DataRequired()])
    password = StringField('Lösenord:', validators=[DataRequired()])
    #owner = StringField('Konto ägare:', validators=[DataRequired()])
    urole = RadioField('Användar Behörighet:', choices=[('admin', 'administratör'),('user', 'Användare')])
    submit = SubmitField("Sign In")    
models.py
class User(db.Model):
    __tablename__ = "anvandare"
    id = db.Column(db.Integer, primary_key=True)    
    user = db.Column(db.String(80), unique=True)
    password = db.Column(db.String(80))
    #owner = db.Column(db.String(80))
    urole = db.Column(db.String(80))

    def __init__(self, user, password, urole):
        self.user = user
        self.password = password
        #self.owner = owner
        self.urole = urole
        
    def __repr__(self):
        return '<User %r>' % self.user

    def is_authenticated(self):
        return True

    def is_active(self):
        return True

    def is_anonymous(self):
        return False

    def get_id(self):
        return str(self.user)
db_setup.py
from sqlalchemy import create_engine
from sqlalchemy.orm import scoped_session, sessionmaker
from sqlalchemy.ext.declarative import declarative_base

engine = create_engine('sqlite:///Matrialdb.db', connect_args={'check_same_thread': False}, convert_unicode=True)


db_session = scoped_session(sessionmaker(autocommit=False,
                                         autoflush=False,
                                         bind=engine))
Base = declarative_base()
Base.query = db_session.query_property()

def init_db():
    import models
    Base.metadata.create_all(bind=engine)
Reply
#2
This looks like a pretty good article on sharing data between threads, covers several methods: https://www.pythonforthelab.com/blog/han...n-threads/
Reply
#3
When you use Flask should use Flask-SQLAlchemy and not SQLAlchemy directly.
Quote:Flask-SQLAlchemy aims to simplify using SQLAlchemy with Flask,
by providing useful defaults and extra helpers that make it easier to accomplish common tasks.
Reply
#4
(Oct-23-2019, 07:22 PM)Larz60+ Wrote: This looks like a pretty good article on sharing data between threads, covers several methods: https://www.pythonforthelab.com/blog/han...n-threads/

But im not using threads.

(Oct-23-2019, 07:37 PM)snippsat Wrote: When you use Flask should use Flask-SQLAlchemy and not SQLAlchemy directly.
Quote:Flask-SQLAlchemy aims to simplify using SQLAlchemy with Flask,
by providing useful defaults and extra helpers that make it easier to accomplish common tasks.

I am following this guys tutorial on the matter of the database https://www.blog.pythonlibrary.org/2017/...-database/

My app.py looks like this

from flask import Flask
from flask_sqlalchemy import SQLAlchemy

app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///Matrialdb.db'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
app.secret_key = "flask rocks!"
app.debug = True

db = SQLAlchemy(app)
Reply
#5
(Oct-24-2019, 03:51 AM)darktitan Wrote: My app.py looks like this
Then you don't need db_setup.py at all,it's maybe confusing because he mixing this stuff together in tutorial.
He do mention this.
Mike Driscoll Wrote:You will note that Flask-SQLAlchemy doesn’t require all the imports that just plain SQLAlchemy required.
All we need is the db object we created in our app script.
Reply
#6
(Oct-24-2019, 05:08 AM)snippsat Wrote:
(Oct-24-2019, 03:51 AM)darktitan Wrote: My app.py looks like this
Then you don't need db_setup.py at all,it's maybe confusing because he mixing this stuff together in tutorial.
He do mention this.
Mike Driscoll Wrote:You will note that Flask-SQLAlchemy doesn’t require all the imports that just plain SQLAlchemy required.
All we need is the db object we created in our app script.

Nice to know. I did the modification needed and removed SQLAlchemy but im still got same problem as before. I cant save the changes i do to the account. and im not getting any error on my stationary computer. In console i can see the POST but nothing more. And when i enter the db file nothing have changed. Funny thing is i use almost the identical code in another thing in an another table in the db and it works the changes gets saved and i get redirected to another page.

eureka

I hade put FlaskForm instead of Form In my Form for the page

class UserForm(Form):
    user = StringField('Användarnamn:', validators=[DataRequired()])
    password = StringField('Lösenord:', validators=[DataRequired()])
    urole = StringField('Användar Behörighet:', validators=[DataRequired()])
    owner = StringField('Användar namn:', validators=[DataRequired()])
       
Got it to work now.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  new window in separate thread - flask website Notabene 3 3,373 Sep-20-2021, 08:29 AM
Last Post: jamesaarr

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020