1

I'm trying to make a RESTful blog.

The problem occurs when I add a "new post" to my blog, which returns the error below.

I've already tried to google the problem for hours now and can't find any solution.

The code can read data from the database, all of my routes works perfectly fine except the create_new_post route which supposed to add the data.

I've narrowed down on the problems which seems to be the pathing of database, but I can't seem to figure out what's wrong with it.

sqlalchemy.exc.OperationalError: (sqlite3.OperationalError) unable to open database file [SQL: INSERT INTO blog_post (title, subtitle, date, body, author, img_url) VALUES (?, ?, ?, ?, ?, ?)] [parameters: ('Blog Post Title', 'Subtitle goes here', 'August 18, 2021', '<p>BLog Content content</p>\r\n', 'Your Name', 'https://images.unsplash.com/photo-1629103257407-6eee51452cbd?ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&ixlib=rb-1.2.1&auto=format&fit=crop&w=701&q=80')] (Background on this error at: http://sqlalche.me/e/13/e3q8)

from flask import Flask, render_template, redirect, url_for
from flask_bootstrap import Bootstrap
from flask_sqlalchemy import SQLAlchemy
from flask_wtf import FlaskForm
from wtforms import StringField, SubmitField
from wtforms.validators import DataRequired, URL
from flask_ckeditor import CKEditor, CKEditorField
from datetime import datetime, date

app = Flask(__name__)


##CONNECT TO DB
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///posts.db'
db = SQLAlchemy(app)

app.config['SECRET_KEY'] = '8BYkEfBA6O6donzWlSihBXox7C0sKR6b'
ckeditor = CKEditor(app)
Bootstrap(app)

# Returns the current year to be passed on the jinja templates. Used in website's footer
@app.context_processor
def inject_now():
    return {"now": datetime.utcnow()}


##CONFIGURE TABLE
class BlogPost(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    title = db.Column(db.String(250), unique=True, nullable=False)
    subtitle = db.Column(db.String(250), nullable=False)
    date = db.Column(db.String(250), nullable=False)
    body = db.Column(db.Text, nullable=False)
    author = db.Column(db.String(250), nullable=False)
    img_url = db.Column(db.String(250), nullable=False)

    


##WTForm
class CreatePostForm(FlaskForm):
    title = StringField("Blog Post Title", validators=[DataRequired()])
    subtitle = StringField("Subtitle", validators=[DataRequired()])
    author = StringField("Your Name", validators=[DataRequired()])
    img_url = StringField("Blog Image URL", validators=[DataRequired(), URL()])
    body = CKEditorField("Blog Content", validators=[DataRequired()])
    submit = SubmitField("Submit Post")


##CKEditor


@app.route('/')
@app.route('/index')
def get_all_posts():
    posts = BlogPost.query.all()
    return render_template("index.html", all_posts=posts)


@app.route("/post/<int:post_id>")
def show_post(post_id):
    requested_post = BlogPost.query.get(post_id)
    return render_template("post.html", post=requested_post)


@app.route("/about")
def about():
    return render_template("about.html")


@app.route("/contact")
def contact():
    return render_template("contact.html")


@app.route("/new-post", methods=["GET", "POST"])
def create_new_post():
    form = CreatePostForm()
    if form.validate_on_submit():
        new_post = BlogPost(
            title=form.title.data,
            subtitle=form.subtitle.data,
            body=form.body.data,
            img_url=form.img_url.data,
            author=form.author.data,
            date=date.today().strftime("%B %d, %Y")
        )
        db.session.add(new_post)
        db.session.commit()
        return redirect(url_for("get_all_posts"))
    return render_template("make-post.html", form=form)


if __name__ == "__main__":
    app.run(debug=True)
5
  • Try to use a full absolute path and make sure you have write permissions to the file and the folder it is in. Commented Aug 18, 2021 at 3:02
  • @KlausD. I tried your solution, and the problem still persists. Commented Aug 18, 2021 at 3:31
  • Did you find your posts.db file in your directory?? Commented Aug 18, 2021 at 6:00
  • Yes i can find the posts.db file, I have no problem readting the data in the database, problem only occurs when I add new data Commented Aug 18, 2021 at 6:03
  • just an update, I tried running the same code on another laptop and it worked, must be because my old laptop has alot of weird stuff in it, anyway I've reformat windows and it now works Commented Aug 18, 2021 at 9:53

1 Answer 1

2

please try to put the exact path to the database. you can do this;

import os
basedir = os.path.abspath(os.path.dirname(__file__))
app.config['SQLALCHEMY_DATABASE_URI']="sqlite:///"+os.path.join(basedir, "posts.db")

As for the above example, creates the database posts.db into to the current working directory folder if it does not exist and also creates a connection with the flask server.

For more info please refer here

Sign up to request clarification or add additional context in comments.

2 Comments

Please explain your answer in order to help to solve the question.
basedir this is your current working directory. So if you say sqlite:///posts.db , sqlite will not find the actual database file. app.config['SQLALCHEMY_DATABASE_URI']="sqlite:///"+os.path.join(basedir, "posts.db") This line is basically,a sqlite uri; sqlite:///+basedir+[database_file]. I hope you understand

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.