Reputation: 415
I am trying to create a Flask application. I would like to include a separate module in my application to separate logic into distinct units. The separate module is called 'validator' and my current directory structure looks like this:
src/
validation-api/
__init__.py
api.py
validator/
__init__.py
validator.py
validation-form/
...
updater/
...
My Flask application is in api.py
and I am trying to do from validator import ValidationOptions, ValidationResult, ValidationRun
where ValidationOptions
, ValidationResult
, and ValidationRun
are classes in validator
.
I am getting the error
ImportError: No module named validator
If I try from .validator...
or from ..validator
I get the error
ValueError: Attempted relative import in non-package
I don't quite understand how modules and packages work in Python. Any suggestions?
Contents of api.py:
from flask import Flask, request
from validator.validator import ValidationOptions, ValidationResult, ValidationRun
app = Flask(__name__)
@app.route("/validate", methods=["POST"])
def validate(self):
pass
if __name__ == '__main__':
app.run(debug=True)
I am starting Flask using the following three commands:
set FLASK_APP=api
set FLASK_DEBUG=1
python -m flask run
Upvotes: 6
Views: 4953
Reputation: 3661
If you have a simple app
src/
app.py
something.py
templates/
and app.py
has the statement import something
in it, then make sure you do NOT have an __init__.py
in the source directory.
See the doc for some explanation as to why.
Upvotes: 2
Reputation: 415
Thanks to @Daniel-Roseman, I've figured out what's going on. I changed the FLASK_APP
environment variable to validation-api.api
, and ran the python -m flask run
command from src
. All imports are working now!
Upvotes: 4