简体   繁体   中英

Where can I find Python snippets that utilize SQLite to create columns?

I'm working on a small personal project that uses common flask practices, like user administration and content restriction and I want to create a new column that provides the role of a user in my SQLite database, which is being generated by a python script.Specifically I want to give the role user to every new registry. Where can I find an example of that or a solution?

I've tried a solution using classes but I think that I got it wrong or maybe I didn't grasp it completely.

To be more specific I tried it and I get the following error

sqlalchemy.exc.OperationalError: (sqlite3.OperationalError) no such column: user.role
[SQL: SELECT user.id AS user_id, user.username AS user_username, user.password AS user_password, user.email AS user_email, user.role AS user_role
FROM user
WHERE user.username IN (?)
 LIMIT ? OFFSET ?]
[parameters: ('a', 1, 0)]
class User(Base):
    __tablename__ = "user"

    id = Column(Integer, primary_key=True)
    username = Column(String(30), unique=True)
    password = Column(String(30))
    email = Column(String(50))
    role = Column(String(50))

    def __repr__(self):
        return '<User %r>' % self.username

In your init.py file you should do it like this:

from flask import Flask
from flask_sqlalchemy import SQLAlchemy

db = SQLAlchemy()

def create_app():
   app = Flask(__name__)
   db.init_app(app)
   db.app = app

   from .models import User
   db.create_all()

.models is a .py file where your User model is, and keep it in mind to call

from .models import User
db.create_all()

after you already created the app and set the db:

app = Flask(__name__)
db.init_app(app)
db.app = app

otherwise you're going to get an exception, which is understandably, you cannot work on a db before you create the app and the db itself.

Solution from above is if you are creating project from scratch, in case you have on-going project and you need just to add one more table, or to update existing, solutions is: https://flask-migrate.readthedocs.io/en/latest/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM