pythonfalconframeworkfalcon

object has no attribute 'API' error in falcon


I am using python 2.7.6 on ubuntu 14.04 with falcon web framework and trying to run simple hello world program. But it gives the following error while running this example. Any idea about this?

Code :

import falcon

class ThingsResource(object):
    def on_get(self, req, resp):
        """Handles GET requests"""
        resp.status = falcon.HTTP_200
        resp.body = 'Hello world!'

# falcon.API instances are callable WSGI apps
wsgi_app = api = falcon.API()

# Resources are represented by long-lived class instances
things = ThingsResource()

# things will handle all requests to the '/things' URL path
api.add_route('/hello', things)

Error:

Traceback (most recent call last):
  File "falcon.py", line 1, in <module>
    import falcon
  File "/home/naresh/Desktop/PythonFramework/falcon.py", line 10, in <module>
    wsgi_app = api = falcon.API()
AttributeError: 'module' object has no attribute 'API'

Solution

  • Your python file is falcon.py so when you call falcon.API() you are calling a method API() in your file, not from the real falcon module.

    Just rename your file and it will work.


    For a more complete solution, see this :

    Trying to import module with the same name as a built-in module causes an import error :

    You will want to read about Absolute and Relative Imports which addresses this very problem. Use:

    from __future__ import absolute_import Using that, any unadorned package name will always refer to the top level package. You will then
    

    need to use relative imports (from .email import ...) to access your own package.