OperationalError:无法打开数据库文件:sqlalchemy

时间:2016-03-04 09:07:12

标签: python database sqlite ubuntu flask-sqlalchemy

我在ubuntu服务器上创建了一个烧瓶api。我的代码在本机上运行(没有apache),但为什么要部署它我得到OperationalError:(sqlite3.OperationalError)无法打开数据库文件。

代码:

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"

错误(来自/var/log/apache2/error.log):

http://pastebin.com/vdAVrFFN

调试:  运行apache的用户是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$

必须在上面的数据库文件夹中创建数据库。

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/

当我从python解释器运行home.py时,它可以正常工作并在数据库文件夹中创建.db

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

1 个答案:

答案 0 :(得分:2)

在与/dev/chat上的海报讨论后,他告诉我,指定SQLite数据库位置的绝对路径可以解决问题。