Prince Francis
Prince Francis

Reputation: 3097

Pyramid : How to create a REST Server using @view_defaults and @view_config with classes in separate file

I am creating a simple REST server in pyramid by following the tutorial. When I write the class and server startup code in same file, it works as expected. But when I move the class file to separate file it is not working.

The following is my project structure. enter image description here

The code I have written is

1. server.py

from wsgiref.simple_server import make_server
from pyramid.config import Configurator

from test_view_defaults import RESTView

if __name__ == '__main__':
  with Configurator() as config:
    config.add_route('rest', '/rest')
    config.scan()
    app = config.make_wsgi_app()
    server = make_server('0.0.0.0', 6543, app)
    server.serve_forever()

2. test_view_defaults.py

from pyramid.response import Response
from pyramid.view import view_config
from pyramid.view import view_defaults

@view_defaults(route_name='rest')
class RESTView(object):
  def __init__(self, request):
      self.request = request

  @view_config(request_method='GET')
  def get(self):
      return Response('get')

  @view_config(request_method='POST')
  def post(self):
      return Response('post')

  @view_config(request_method='DELETE')
  def delete(self):
      return Response('delete')

When I request http://localhost:6543/rest it gives 404 error. Could anyone help me to find what I am doing wrong ?

Upvotes: 0

Views: 132

Answers (1)

Prince Francis
Prince Francis

Reputation: 3097

I solved the problem as below

  1. Created a directory (module) named 'api'

  2. Moved the class file test_view_defaults.py into the above created directory

  3. Changed the scan method as config.scan(package='api')

  4. The changed server.py is as follows

from wsgiref.simple_server import make_server
from pyramid.config import Configurator


if __name__ == '__main__':
  with Configurator() as config:
    config.add_route('rest', '/rest')
    config.scan(package='api')
    app = config.make_wsgi_app()
    server = make_server('0.0.0.0', 6543, app)
    server.serve_forever()

Upvotes: 2

Related Questions