简体   繁体   中英

Python import modules in same directory for Flask

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

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!

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM