OiO.lk Community platform!

Oio.lk is an excellent forum for developers, providing a wide range of resources, discussions, and support for those in the developer community. Join oio.lk today to connect with like-minded professionals, share insights, and stay updated on the latest trends and technologies in the development field.
  You need to log in or register to access the solved answers to this problem.
  • You have reached the maximum number of guest views allowed
  • Please register below to remove this limitation

database error with sqlalchemy on Google Cloud Run

  • Thread starter Thread starter Nyiko Maswanganyi
  • Start date Start date
N

Nyiko Maswanganyi

Guest
I am trying to deploy a flask app on Google Cloud Run that has a sqlite database and I keep getting an error that a table already exists. Even when I delete the database instance from my container before I click Deploy on Cloud Run the error still persists.

Here is the error:

Traceback (most recent call last): File "/usr/local/lib/python3.10/site-packages/sqlalchemy/engine/base.py", line 1965, in _exec_single_context self.dialect.do_execute( File "/usr/local/lib/python3.10/site-packages/sqlalchemy/engine/default.py", line 921, in do_execute cursor.execute(statement, parameters) sqlite3.OperationalError: table user already exists

here is the code:

Code:
import math
import json
from flask import Flask, session, render_template, request, url_for, redirect, flash, send_file
from flask_sqlalchemy import SQLAlchemy
from flask_login import LoginManager, UserMixin, login_user, logout_user, current_user, login_required
from sqlalchemy import ForeignKey, inspect, create_engine
from flask_bcrypt import Bcrypt
import openpyxl

import datetime
from datetime import date
from datetime import datetime
import schedule
import time
from sqlalchemy.orm import relationship
from datetime import timedelta
import os
from sqlalchemy import text
import pandas as pd
from flask_mail import Mail, Message
from itsdangerous import URLSafeTimedSerializer

app = Flask(__name__)
app.app_context().push()
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///bams.sqlite3'
engine = create_engine(app.config['SQLALCHEMY_DATABASE_URI'])
app.config['SESSION_COOKIE_SECURE'] = True
app.config['PERMANENT_SESSION_LIFETIME'] = timedelta(minutes=15)
app.config['SECRET_KEY'] = "random Letago is the 0ne I w@nt string"
app.config['UPLOAD_FOLDER'] = 'uploads'  # Folder to store the uploaded files
app.config['ALLOWED_EXTENSIONS'] = {'xlsx', 'csv'}  # Allowed file extensions
# Upload folder
UPLOAD_FOLDER = 'static/files'
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER

db = SQLAlchemy()
# Configure server parameters
app.config['MAIL_SERVER'] = 'smtp.gmail.com'
app.config['MAIL_PORT'] = 465
app.config['MAIL_USERNAME'] = '[email protected]'
app.config['MAIL_PASSWORD'] = 'lbgi qnhn jizj cozk'
app.config['MAIL_USE_TLS'] = False
app.config['MAIL_USE_SSL'] = True
# Generate a unique token serializer
serializer = URLSafeTimedSerializer(app.config['SECRET_KEY'])

mail = Mail(app)
login_manager = LoginManager()
login_manager.init_app(app)
bcrypt = Bcrypt(app)
# initialize the app with the extension
db.init_app(app)


# Define User model
class User(UserMixin, db.Model):
    id = db.Column(db.Integer, primary_key=True)
    email = db.Column(db.String(250), unique=True, nullable=False)
    password = db.Column(db.String(250), nullable=False)
    usertype = db.Column(db.String(250), nullable=False)
    respondent = relationship('Respondent', backref='user')

# Define Respondent model
class Respondent(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    user_id = db.Column(db.Integer, db.ForeignKey('user.id'))
    name = db.Column(db.String(250))
    surname = db.Column(db.String(250))
    contact_number = db.Column(db.String(250), default="number unavailable")
    alt_contact_number = db.Column(db.String(250), default="alternate number unavailable")
    address = db.Column(db.String(250), default="address unavailable")
    birthday = db.Column(db.String(250), default="birthday unavailable")
    consent_to_join = db.Column(db.String(250), default="yes")
    panel_joined_date = db.Column(db.Date, default=date.today)
    recipient = relationship('Recipient', backref='respondent')

# Define Recipient model
class Recipient(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    respondent_id = db.Column(db.Integer, db.ForeignKey('respondent.id'))
    reason = db.Column(db.String(250))
    response = db.Column(db.String(250))
    date_sent = db.Column(db.DateTime, default=datetime.now())

# Check if tables exist and create them if they don't
with app.app_context():
    if not inspect(db.engine).has_table('user'):
        db.create_all()
    if not inspect(db.engine).has_table('respondent'):
        db.create_all()
    if not inspect(db.engine).has_table('recipient'):
        db.create_all()
<p>I am trying to deploy a flask app on Google Cloud Run that has a sqlite database and I keep getting an error that a table already exists. Even when I delete the database instance from my container before I click Deploy on Cloud Run the error still persists.</p>
<p>Here is the error:</p>
<p>Traceback (most recent call last):
File "/usr/local/lib/python3.10/site-packages/sqlalchemy/engine/base.py", line 1965, in _exec_single_context
self.dialect.do_execute(
File "/usr/local/lib/python3.10/site-packages/sqlalchemy/engine/default.py", line 921, in do_execute
cursor.execute(statement, parameters)
sqlite3.OperationalError: table user already exists</p>
<p>here is the code:</p>
<pre><code>import math
import json
from flask import Flask, session, render_template, request, url_for, redirect, flash, send_file
from flask_sqlalchemy import SQLAlchemy
from flask_login import LoginManager, UserMixin, login_user, logout_user, current_user, login_required
from sqlalchemy import ForeignKey, inspect, create_engine
from flask_bcrypt import Bcrypt
import openpyxl

import datetime
from datetime import date
from datetime import datetime
import schedule
import time
from sqlalchemy.orm import relationship
from datetime import timedelta
import os
from sqlalchemy import text
import pandas as pd
from flask_mail import Mail, Message
from itsdangerous import URLSafeTimedSerializer

app = Flask(__name__)
app.app_context().push()
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///bams.sqlite3'
engine = create_engine(app.config['SQLALCHEMY_DATABASE_URI'])
app.config['SESSION_COOKIE_SECURE'] = True
app.config['PERMANENT_SESSION_LIFETIME'] = timedelta(minutes=15)
app.config['SECRET_KEY'] = "random Letago is the 0ne I w@nt string"
app.config['UPLOAD_FOLDER'] = 'uploads' # Folder to store the uploaded files
app.config['ALLOWED_EXTENSIONS'] = {'xlsx', 'csv'} # Allowed file extensions
# Upload folder
UPLOAD_FOLDER = 'static/files'
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER

db = SQLAlchemy()
# Configure server parameters
app.config['MAIL_SERVER'] = 'smtp.gmail.com'
app.config['MAIL_PORT'] = 465
app.config['MAIL_USERNAME'] = '[email protected]'
app.config['MAIL_PASSWORD'] = 'lbgi qnhn jizj cozk'
app.config['MAIL_USE_TLS'] = False
app.config['MAIL_USE_SSL'] = True
# Generate a unique token serializer
serializer = URLSafeTimedSerializer(app.config['SECRET_KEY'])

mail = Mail(app)
login_manager = LoginManager()
login_manager.init_app(app)
bcrypt = Bcrypt(app)
# initialize the app with the extension
db.init_app(app)


# Define User model
class User(UserMixin, db.Model):
id = db.Column(db.Integer, primary_key=True)
email = db.Column(db.String(250), unique=True, nullable=False)
password = db.Column(db.String(250), nullable=False)
usertype = db.Column(db.String(250), nullable=False)
respondent = relationship('Respondent', backref='user')

# Define Respondent model
class Respondent(db.Model):
id = db.Column(db.Integer, primary_key=True)
user_id = db.Column(db.Integer, db.ForeignKey('user.id'))
name = db.Column(db.String(250))
surname = db.Column(db.String(250))
contact_number = db.Column(db.String(250), default="number unavailable")
alt_contact_number = db.Column(db.String(250), default="alternate number unavailable")
address = db.Column(db.String(250), default="address unavailable")
birthday = db.Column(db.String(250), default="birthday unavailable")
consent_to_join = db.Column(db.String(250), default="yes")
panel_joined_date = db.Column(db.Date, default=date.today)
recipient = relationship('Recipient', backref='respondent')

# Define Recipient model
class Recipient(db.Model):
id = db.Column(db.Integer, primary_key=True)
respondent_id = db.Column(db.Integer, db.ForeignKey('respondent.id'))
reason = db.Column(db.String(250))
response = db.Column(db.String(250))
date_sent = db.Column(db.DateTime, default=datetime.now())

# Check if tables exist and create them if they don't
with app.app_context():
if not inspect(db.engine).has_table('user'):
db.create_all()
if not inspect(db.engine).has_table('respondent'):
db.create_all()
if not inspect(db.engine).has_table('recipient'):
db.create_all()
</code></pre>
Continue reading...
 

Latest posts

B
Replies
0
Views
1
Blundering Ecologist
B
Top