0

I am creating an flask api on ubuntu server. My code runs on native machine (without apache)but why deploying it I get OperationalError: (sqlite3.OperationalError) unable to open database file.

Code:

home.py

from flask import Flask,jsonify, request
from models import UsersLoginInfo,Base
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import relationship, sessionmaker
from sqlalchemy import create_engine
import sqlalchemy.pool

sqlite = sqlalchemy.pool.manage(sqlite3, poolclass=sqlalchemy.pool.SingletonThreadPool)
engine = sqlite.create_engine('sqlite:///database/userslogininfo.db')

Base.metadata.bind = engine
DBSession = sessionmaker(bind=engine)
session = DBSession()
app=Flask(__name__)

@app.route('/login',methods=['POST'])
def home():
    data_rec = {'username' : request.json['username'], 'password' : request.json['password']}
    users = [i.serialize['username'] for i in session.query(UsersLoginInfo).all()]
    passwords = [i.serialize['password'] for i in session.query(UsersLoginInfo).all()]
    login=False
    try:
        user_index=users.index(unicode(data_rec['username']))
        password_from_db=passwords[user_index]
        if password_from_db==data_rec['password']:
            login=True
            msg=None
        else:
            msg="Wrong password entered."
    except ValueError:
        msg="There is no user with that username, please create an account."
    return jsonify({'login' : login ,"msg": msg})

@app.route('/create',methods=['POST'])
def create():
    data_rec = {'username' : request.json['username'], 'password' : request.json['password']}
    users = [i.serialize['username'] for i in session.query(UsersLoginInfo).all()]
    if data_rec['username'] in users: #check account exists
        account_exists=True
        msg="An account with that username already exists, please choose another username."
    else:
        account_exists=False
        id=len(users)
        user = UsersLoginInfo(username = unicode(data_rec['username']), password = unicode(data_rec['password']), id = id)
        session.add(user)
        session.commit()
        msg="Your account has been created. Please login with it."
    return jsonify({'account_exists' : account_exists ,"msg": msg})

if __name__ == "__main__":
    app.run()

models.py

# -*- coding: utf-8 -*-
from sqlalchemy import Column,Integer,String
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import relationship, sessionmaker
from sqlalchemy import create_engine

Base = declarative_base()
class UsersLoginInfo(Base):
  __tablename__ = 'userslogininfo'
  id = Column(Integer, primary_key = True)
  username = Column(String)
  password = Column(String)

  #Add a property decorator to serialize information from this database
  @property
  def serialize(self):
    return {
      'username': self.username,
      'password': self.password,
      }

engine = create_engine('sqlite:///database/userslogininfo.db')


Base.metadata.create_all(engine)

FlaskApps.wsgi

import sys
import logging
logging.basicConfig(stream=sys.stderr)
sys.path.insert(0,"/var/www/FlaskApps/notepad_app/")
print "hello"
# home points to the home.py file
from home import app as application
application.secret_key = "somesecretses212sionkey"

Error(from /var/log/apache2/error.log):

http://pastebin.com/vdAVrFFN

Debugging: The user that runs apache is www-data.

ubuntu@ip-171-31-38-0:/var/www/FlaskApps$ ls
FlaskApps.wsgi  notepad_app
ubuntu@ip-171-31-38-0:/var/www/FlaskApps$ tree
.
├── FlaskApps.wsgi
└── notepad_app
    ├── clean_log.sh
    ├── database
    ├── home.py
    ├── home.pyc
    ├── models.py
    ├── models.pyc
    ├── print_log.sh
    ├── README.md
    └── restart.sh

2 directories, 9 files
ubuntu@ip-171-31-38-0:/var/www/FlaskApps$

The database has to be created in the database folder above.

ubuntu@ip-171-31-38-0:/var/www/FlaskApps/notepad_app$ ls -ld database/
drwxrwxrwx 2 www-data www-data 4096 Mar 13 21:31 database/

When I run home.py from python interpreter it works perfectly and creates a .db in database folder

ubuntu@ip-171-31-38-0:/var/www/FlaskApps/notepad_app$ python home.py
 * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
 * Restarting with stat
 * Debugger is active!
 * Debugger pin code: 312-927-730
ubuntu@ip-171-31-38-0:/var/www/FlaskApps/notepad_app$ ls database/
userslogininfo.db
9
  • And why isn't your question a duplicate of the linked ones? Commented Mar 4, 2016 at 9:09
  • @CL. I tried solutions from those questions, but it didn't work. Therefore, asked. My code employs the threads. Sry for mentioning explicitly. Commented Mar 4, 2016 at 9:10
  • 2
    What do you think the absolute path of the userslogininfo.db is? Are you sure? Do you have write permissions to that file? If the file doesn't exist, do you have permissions to create the file in that directory? Commented Mar 4, 2016 at 20:16
  • Same folder, works on my local machine. Who is executing the file, it is in /var/www. Commented Mar 4, 2016 at 20:42
  • 2
    A guess: your apache user doesn't have permissions to write to the directory you're trying to use. You could add a lot more debugging information to help solve this - for instance when you say it works on the local machine, do you mean under apache on the local machine or using the dev server? You give two SO questions as "references", but don't explain their relevance - why don't they solve your problem (particularly the second). Please add this info into the question (not in comments, where it can get lost). Commented Mar 12, 2016 at 14:47

1 Answer 1

4
+50

After discussion with the poster on /dev/chat, he informed me that specifying an absolute path for the location of the SQLite database fixed the problem.

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

1 Comment

Thanks! Also, special thanks to @Antti Haapala and @J Richard Snape.

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.