4

I have a flask app with the following directory structure:

  • myapp/
    • application.py
    • __init__.py
    • models/
      • __init__.py
      • user.py

The models use Flask-SQLAlchemy, and therefore, they need to have access to the db object (a SQLAlchemy instance) from application.py

user.py:

import sys,os
sys.path.append('/path/to/application/package')

from testapp import db

class User(db.Model):
    id = db.Column(db.Integer,primary_key=True)
    username = db.Column(db.String(255),unique=True)
    age = db.Column(db.Integer)

    def __init__(self,username,age):
        self.username = username
        self.age = age

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

Because any of the models need access to the application's SQLAlchemy instance, the db property, I have to throw this whole package on the path and then import from the main application module. For sanity's sake, I would like to keep the models in separate files. Will I need to put the path code on top of every model? Is there a better way? I'd rather not have the full path input like that, as they may be deployed to different hosts with different directory structures. Ideally there would be some way to internally handle the path so when it is used as another user via mod_wsgi I don't have to manually change the code.

4

1 に答える 1

6

最初のアプローチ:

私は次の構造になってしまいました:

  • project_root — 一部の構成、.gitignore ファイルなども保持します
    • start.py
    • フラスコルート
      • __init__.py
      • アプリケーション.py
      • モジュール_1
        • __init__.py
        • models.py
      • モジュール_2
        • __init__.py
        • models.py

最上位の start.py はアプリを実行するだけです:

#! /usr/bin/env python
from flask_root import applicaiton

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

Pythonは、スクリプトを開始したディレクトリでパッケージを検索するため、sys.path にパッケージを追加する必要はありません (私の場合、sys.path の変更は見苦しく見えます)。これで、 flask_root python パッケージが完全に機能するようになり、アプリケーションのどこからでも、そこからすべてをインポートできます。

from flask_root.application import db

2番目のアプローチ:

Flask アプリケーションをそのディレクトリから起動すると、

./application.py runserver

__init__.py が含まれていても、開始したディレクトリに python パッケージとしてアクセスすることはできません。

ただし、ディレクトリ レイアウトを使用すると、次のトリックを実行できます。

models/__init__.py :

from application import db
...

モデル/user.py :

from . import db
...

最初のアプローチは、よりクリーンで普遍的です。2 つ目は、複数の Flask プロジェクト間で同じ設計図を共有する必要がある場合に役立つ可能性があります。

于 2012-07-19T21:26:04.423 に答える