Python net import for models - SQL Alchemy

I have a flash application with the following directory structure:

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

Models use Flask-SQLAlchemy, so they must have access to the db object (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 

Since any of the models needs access to the instance of the SQLAlchemy application, the db property, I have to throw this whole package in the path and then import from the main application module. For common sense, I would like to save the models in separate files. Should I provide a path code on top of each model? Is there a better way? I would prefer not to have a full input path like this, since they can be deployed to different hosts with different directory structures. Ideally, there is some way to internally handle the path, so when it is used as another user via mod_wsgi , I do not need to manually change the code.

+4
source share
1 answer

1st approach:

I got the following structure:

  • project_root - also contains some configs, a .gitignore file, etc.
    • start.py
    • flask_root
      • __ __ INIT. RU
      • application.py
      • module_1
        • __ __ INIT. RU
        • models.py
      • module_2
        • __ __ INIT. RU
        • models.py

The topmost start.py launches the application:

 #! /usr/bin/env python from flask_root import applicaiton if __name__ == '__main__': application.manager.run() 

Python searches for packages in the directory from which you are the script, so now you do not need to add them to sys.path (as for me, changing sys.path looks ugly). Now you have the full flask_root python working package, and you can import all of it from anywhere in your application:

 from flask_root.application import db 

Second approach:

If you run the Flask application from it,

 ./application.py runserver 

the directory you started from cannot be accessed as a python package, even if it has __init__.py in it.

Although in your catalog layout you can do the following trick:

models / __ __ INIT ru :.

 from application import db ... 

models /user.py

 from . import db ... 

The first approach is cleaner and more universal. The second may be useful when you need to share the same drawings between multiple Flask projects.

+6
source

All Articles