在SQLAlchemy中使用正确的文件结构,以及如何向db

时间:2018-08-08 22:44:00

标签: python heroku flask sqlalchemy flask-sqlalchemy

我正在尝试构建一个简单的博客平台来学习Python和Flask。我正在使用SQLAlchemy连接到Heroku和flask_s3上托管的Postgres数据库,以提供来自AWS存储桶的静态文件。我主要遵循以下步骤:

https://gist.github.com/mayukh18/2223bc8fc152631205abd7cbf1efdd41/

一切进展顺利,它已正确托管在Heroku上,并已连接到AWS S3存储桶,随时可用。但是,我对如何通过某种形式或路线将博客文章添加到数据库中感到困惑,这将允许我填写博客文章的属性(可在下面的models.py中的Post中找到)

我有可呈现的html模板和以下三个文件,app.py,manage.py和models.py。

app.py:

from flask import Flask, render_template
from flask_sqlalchemy import SQLAlchemy
from flask_s3 import FlaskS3

app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = '*URI for DB hosted on heroku'
app.config['FLASKS3_BUCKET_NAME'] = 'my S3 bucket on AWS'

db = SQLAlchemy(app)
s3 = FlaskS3(app)

from models import Post

#routes to templates to be rendered

if __name__ == '__main__'
    app.run(debug=True)

manage.py:

from flask_script import Manager
from flask_migrate import Migrate, MigrateCommand

from app import app, db

migrate = Migrate(app, db)

manager = Manager(app)
manager.add_command('db', MigrateCommand)

if __name__ == '__main__':
    manager.run()

和models.py:

from manage import db,app

class Post(db.Model):
    __tablename__ = 'blogposts'

    id = db.Column(db.Integer, primary_key=True)
    title = db.Column(db.String(120), index=True, unique=True)
    content = db.Column(db.Text, index=True, unique=True)
    date = db.Column(db.DateTime, index=True, unique=True)
    tag = db.Column(db.String(120), index=True, unique=True)
    cover = db.Column(db.String(120), index=True, unique=True)

    def __repr__(self):
        return '<Post: %r>' % (self.title)

我的文件结构是:

-blog
  --__pycache__
  --migrations
  --static
  --templates
  app.py
  manage.py
  models.py
  Pipfile
  Pipfile.lock
  Procfile

我想在本地工作(在将任何内容发布到Heroku之前),但是不知道从这里开始做什么。在我将最终的博客文章推送到Heroku之前,有人对如何创建一条添加博客文章并将其保存到本地Postgres实例的路线有建议吗?

我一直遵循的要旨是这样的:

@app.route('/add/')
def webhook():
    #post attributes defined
    p = Post(id = id, title = title, date = datetime.datetime.utcnow, content = content, tag = tag, cover = cover)
    print("post created", p)
    db.session.add(p)
    db.session.commit()
    return "post created"

当我尝试在本地运行它时,出现以下错误,因此我不确定文件是否正确连接。

File "/Users/Mb/Desktop/datadude/app.py", line 15, in <module>
from models import Post
ImportError: cannot import name 'Post'

很抱歉,如果这是错误的地方。如果有更好的地方寻求建议,请告诉我。

1 个答案:

答案 0 :(得分:0)

问题存在于循环依赖项中。

您可以将SQLAlchemy的初始化移动到models.py。然后仅对app.py中的db对象运行方法init_app。

models.py

from flask_sqlalchemy import SQLAlchemy

db = SQLAlchemy()

class Post(db.Model):
    __tablename__ = 'blogposts'

    id = db.Column(db.Integer, primary_key=True)
    title = db.Column(db.String(120), index=True, unique=True)
    content = db.Column(db.Text, index=True, unique=True)
    date = db.Column(db.DateTime, index=True, unique=True)
    tag = db.Column(db.String(120), index=True, unique=True)
    cover = db.Column(db.String(120), index=True, unique=True)

    def __repr__(self):
         return '<Post: %r>' % (self.title)

app.py

import datetime
from flask import Flask, render_template

from flask_s3 import FlaskS3
from models import db


app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = '*URI for DB hosted on heroku'
app.config['FLASKS3_BUCKET_NAME'] = 'my S3 bucket on AWS'
db.init_app(app)

s3 = FlaskS3(app)
from models import Post


@app.route('/add/')
def webhook():
    #post attributes defined
    p = Post(id = id, title = title, date = datetime.datetime.utcnow, content = content, tag = tag, cover = cover)
    print("post created", p)
    db.session.add(p)
    db.session.commit()
    return "post created"
#routes to templates to be rendered

if __name__ == '__main__':
    app.run(debug=True)

您可以详细了解https://github.com/slezica/bleg/blob/master/data/posts/2014-03-08-avoiding-circular-dependencies-in-flask.md