|
| 1 | +from flask import Flask |
| 2 | +from flask_sqlalchemy import SQLAlchemy |
| 3 | +from werkzeug.security import generate_password_hash, check_password_hash |
| 4 | +import os |
| 5 | + |
| 6 | +basedir = os.path.abspath(os.path.dirname(__file__)) |
| 7 | + |
| 8 | +""" |
| 9 | +mysql://username:password@hostname/database |
| 10 | +postgresql://username:password@hostname/database |
| 11 | +sqlite:////absolute/path/to/database |
| 12 | +""" |
| 13 | +app = Flask(__name__) |
| 14 | +app.config["SQLALCHEMY_DATABASE_URI"] = "sqlite:///" + os.path.join( |
| 15 | + basedir, "data.sqlite" |
| 16 | +) |
| 17 | +print(app.config.get("SQLALCHEMY_DATABASE_URI")) |
| 18 | +app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = False |
| 19 | + |
| 20 | +db = SQLAlchemy(app) |
| 21 | + |
| 22 | + |
| 23 | +# 定义模型 |
| 24 | +class Role(db.Model): |
| 25 | + __tablename__ = "roles" |
| 26 | + id = db.Column(db.Integer, primary_key=True) |
| 27 | + name = db.Column(db.String(64), unique=True) |
| 28 | + users = db.relationship("User", backref="role") |
| 29 | + |
| 30 | + def __repr__(self) -> str: |
| 31 | + return "<Role %s>" % self.name |
| 32 | + |
| 33 | + |
| 34 | +class User(db.Model): |
| 35 | + __tablename__ = "users" |
| 36 | + id = db.Column(db.Integer, primary_key=True) |
| 37 | + username = db.Column(db.String(64), unique=True) |
| 38 | + password = db.Column(db.String(64)) |
| 39 | + password_hash = db.Column(db.String(128)) |
| 40 | + |
| 41 | + @property |
| 42 | + def password(self): |
| 43 | + raise AttributeError("Password is not readable") |
| 44 | + |
| 45 | + @password.setter |
| 46 | + def password(self, password): |
| 47 | + self.password_hash = generate_password_hash(password) |
| 48 | + |
| 49 | + def verify_password(self, password): |
| 50 | + return check_password_hash(self.password_hash, password) |
| 51 | + |
| 52 | + role_id = db.Column(db.Integer, db.ForeignKey("roles.id")) |
| 53 | + |
| 54 | + def __repr__(self) -> str: |
| 55 | + return "<User %s>" % self.username |
| 56 | + |
| 57 | + |
| 58 | +@app.shell_context_processor |
| 59 | +def make_shell_context(): |
| 60 | + return dict(db=db, User=User, Role=Role) |
| 61 | + |
| 62 | + |
| 63 | +# 迁移数据库 |
| 64 | +# pip install flask-migrate |
| 65 | +from flask_migrate import Migrate |
| 66 | + |
| 67 | +migrate = Migrate(app, db) |
0 commit comments