Flask : sqlalchemy.exc.ProgrammingError: (psycopg2.ProgrammingError) relation “users” does not exist

后端 未结 2 1654
情歌与酒
情歌与酒 2021-02-20 11:09

I am working on a flask app based on http://code.tutsplus.com/tutorials/intro-to-flask-signing-in-and-out--net-29982.

As part of the tut I\'m trying to connect

2条回答
  •  萌比男神i
    2021-02-20 11:39

    You're initializing your database twice.

    I'd suggest taking a good look at this: http://flask.pocoo.org/docs/0.10/patterns/sqlalchemy/

    Essentially, you'll want to split things up into a few more files to prevent import issues and make things a little more clean. I've done the below which seems to work. Note, I've used SQLite, since I do not have Postgres installed on this box.

    app.py

    from flask import Flask
    app = Flask(__name__)
    app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:////test11.db'
    

    models.py

    from flask.ext.sqlalchemy import SQLAlchemy
    from app import app
    db = SQLAlchemy(app)
    
    class User(db.Model):
        __tablename__ = 'users'
        uid = db.Column(db.Integer, primary_key = True)
        firstname = db.Column(db.String(100))
        lastname = db.Column(db.String(100))
        email = db.Column(db.String(120), unique=True)
        pwdhash = db.Column(db.String(54))
    
    def __init__(self, firstname, lastname, email, password):
        self.firstname = firstname.title()
        self.lastname = lastname.title()
        self.email = email.lower()
        self.set_password(password)
    
    def set_password(self, password):
        self.pwdhash = (password)
    
    def check_password(self, password):
        return password
    

    routes.py

    from models import User, db
    
    db.create_all()
    db.session.commit()
    
    admin = User('admin', 'admin@example.com', 'admin1', 'admin1@example.com')
    guest = User('admi2', 'admin@ex1ample.com', 'admin', 'admin2@example.com')
    db.session.add(admin)
    db.session.add(guest)
    db.session.commit()
    

    I'd definitely suggest looking over some tutorials! You'll need it: you should learn about web vulnerabilities, best practices, and so on.

提交回复
热议问题