Search code examples
python-3.xflaskuwsgiflask-restful

Flask uWSGI application structure and python3 imports


I have a basic flask-restful application with a structure that looks like this as recommended on the flask website.

/application
    /application
        /config.py
        /__init__.py
    /wsgi.ini

Slightly irrelevant, but config.py is generated by our CD server.

wsgi.ini looks likes this

[uwsgi]
module = application:app

master = true
processes =5

socket = /tmp/application.sock
chmod-socket = 660
vacuum = true

die-on-term = true

and __init__.py looks something like this

import config

from flask import Flask, request, g
from flask_restful import Resource, Api, abort


app = Flask(__name__)
api = Api(app)

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

Now when I try to startup the application using uwsgi --ini wsgi.ini I get this error:

File "./application/__init__.py", line 2, in <module>
    import config

Originally __init__.py was called main.py and I executed that to debug, which is why the import is now wrong. I'm guess I will need to change the import to be from .config import *

My question is two fold:

  1. Could I have avoided the import problem completely. ie is there a way in python3 to import sibling modules that will work for both approaches
  2. is my wsgi.ini in the correct place, or should it be in the inner application directory?

Solution

  • Python 3.x dropped support for infra-package relative imports. You need to use an absolute import:

    from application import config 
    

    or the new spelling of relative imports:

    from . import config
    

    If you need to also support legacy versions of Python you can enable this behavior with:

    from __future__ import absolute_import