Search code examples
pythonflaskeve

How do I use add_resource with Eve application?


I have an Eve application running and I wanted to reorganize it (just to follow best practices) so that it looks similar to a flask application directory structure.

I tried to use something like this from flask

from flask_restful import Api

app=Flask(__name__)
api = Api(app)
api.add_resource(resources.UserRegistration, '/registration')

like this in Eve:

from eve import Eve

app = Eve(auth=CustomAuth)
api = Api(app)
api.add_resource(resources.UserRegistration, '/registration')

I get the following error while starting the Eve application:

Traceback:

File "/var/www/flask-api/views.py", line 1, in <module>
    from run import app
  File "/var/www/flask-api/run.py", line 22, in <module>
    api.add_resource(resources.UserRegistration, '/registration')
  File "/var/www/django/lib64/python3.6/site-packages/flask_restful/__init__.py", line 382, in add_resource
    self._register_view(self.app, resource, *urls, **kwargs)
  File "/var/www/django/lib64/python3.6/site-packages/flask_restful/__init__.py", line 448, in _register_view
    app.add_url_rule(rule, view_func=resource_func, **kwargs)
  File "/var/www/django/lib64/python3.6/site-packages/flask/app.py", line 98, in wrapper_func
    return f(self, *args, **kwargs)
  File "/var/www/django/lib64/python3.6/site-packages/flask/app.py", line 1274, in add_url_rule
    rule = self.url_rule_class(rule, methods=methods, **options)
  File "/var/www/django/lib64/python3.6/site-packages/werkzeug/routing.py", line 640, in __init__
    if not string.startswith("/"):
AttributeError: 'functools.partial' object has no attribute 'startswith'

My resources.py file looks something like this:

from flask_restful import Resource

class UserRegistration(Resource):
    def post(self):
        return {'message': 'User registration'}

Solution

  • You could use Flask Blueprints to organize your routes in different files and then register them within the application. Check this eve documentation that mentions blueprints: https://docs.python-eve.org/en/stable/snippets/hooks_blueprints.html.

    More on Flask blueprints from Flask's documentation: https://flask.palletsprojects.com/en/1.1.x/blueprints/