views.py
from flask import Flask
from exts import db
from models import *
import config
app = Flask(__name__)
app.config.from_object(config)
db.init_app(app)
@app.route('/')
def index():
db.create_all() #根据模型创建表
try:
a = Article('asdf', 'uiop')
db.session.add(a)
db.session.commit()
except Exception as e:
print(e)
else:
return '1'
finally:
return '0'
if __name__ == '__main__':
app.run()
config.py
DEBUG = True
SQLALCHEMY_DATABASE_URI = 'sqlite:///test.db' #此为相对路径
SQLALCHEMY_TRACK_MODIFICATIONS = False
exts.py
from flask_sqlalchemy import SQLAlchemy
db = SQLAlchemy()
models.py
from exts import db
class Article(db.Model):
__tablename__ = 'article'
id = db.Column(db.Integer, primary_key=True, autoincrement=True)
title = db.Column(db.String(100), nullable=False)
content = db.Column(db.String(1000), nullable=False)
def __init__(self, title, content):
self.title = title
self.content = content