DEV Community

Saphi8
Saphi8

Posted on • Updated on

I've a little problem with Flask-SQLAlchemy

Problem solved !

I'm currently in highschool, and we have a project : create a website. We're three and my part is the backend, with Flask in python.It is the first time I try to do something like that. The first thing I need to do is create an API for new users, but I can't write things on the database.

Here is the final error :

sqlalchemy.exc.OperationalError: (sqlite3.OperationalError) attempt to write a readonly database 
[SQL: INSERT INTO user (id, mdp, accents) VALUES (?, ?, ?)]
[parameters: ('saphi', '$2b$12$0McLhda54LEQtkg8QHxff.f.rJDADQ.sDsAGfvXHy8vhl4H9wE0y6', "{'': ['', '']}")]
(Background on this error at: https://sqlalche.me/e/20/e3q8)
Enter fullscreen mode Exit fullscreen mode

Here the part where I Initialize the database : (thoth-edu/thoth-edu/Backend/appInit.py)

from flask import Flask
from flask_cors import CORS
from flask_sqlalchemy import SQLAlchemy


app = Flask(__name__)
app.config["SQLALCHEMY_DATABASE_URI"] = "sqlite:////home/ubuntu/thoth-edu/database/data.db"
app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = False
CORS(
    app,
    resources={
        r"/.*": {"origins": ["https://thoth-edu.fr", "https://professeur.thoth-edu.fr"]}
    },
)
db = SQLAlchemy(app)


class User(db.Model):
    id = db.Column(db.String, unique=True, nullable=False, primary_key=True)
    mdp = db.Column(db.String, nullable=False)
    accents = db.Column(db.String)



class Eval(db.Model):
    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    cheminJSON = db.Column(db.String)
    cheminCSV = db.Column(db.String)
    idProf = db.Column(db.String, db.ForeignKey("user.id"), nullable=False)


class Acces(db.Model):
    id = db.Column(db.String, unique=True, nullable=False, primary_key=True)
    nom = db.Column(db.String, nullable=False)
    dateDeb = db.Column(db.String, nullable=False)
    dateFin = db.Column(db.String, nullable=False)
    modele = db.Column(db.String, db.ForeignKey("eval.id"), nullable=False)



with app.app_context():
    try:
        db.create_all()
        print("Tables created successfully.")
    except Exception as e:
        print("An error occurred while creating tables:", e)
Enter fullscreen mode Exit fullscreen mode

What my API look like : (thoth-edu/thoth-edu/Backend/main.py)

# Import libraries
from flask import request
import json

# Import routes (and other modules)
import routes as r
from appInit import app

@app.route("/user/login", methods=["POST"])
def connexion():
    data = request.get_json()
    return r.user.login(data)
Enter fullscreen mode Exit fullscreen mode

And what r.user.login look like: (thoth-edu/thoth-edu/Backend/routes/user/login.py)

# Import libraries
from flask import jsonify
import sqlite3

# Import app
from appInit import db, User, bcrypt


def signup(data):
    # { "id" : "Bob" ; "mdp" : "mdp" ; "accents" : "é" }
    newUser = User(
        id=data["id"],
        mdp=bcrypt.generate_password_hash(data["mdp"]).decode("utf-8"),
        accents=str(data["accents"]),
    )

    user = User.query.filter_by(id=data["id"]).first()

    if user == None:
        db.session.add(newUser)
        db.session.commit()
        return (jsonify({"message": "True"}),)

    if user.id == data["id"]:
        return (jsonify({"message": "False"}),)

    db.session.add(newUser)
    db.session.commit()

    return (jsonify({"message": "True"}),)
Enter fullscreen mode Exit fullscreen mode

Here's what I tried :
-> Giving rwx permissions for everyone
-> Install sqlite with sudo apt install sqlite3 Nothing worked, and I didn't found anything else to help me

Note that I’m trying this out in a VM (running Debian 12 with KDE), and that the files of the project are taken from my computer (and accessed through the shared files functionality of VirtualBox).

Top comments (0)