Source

moviedemo / moviedemo / controllers / rest.py

Full commit
"""Rest Controller Info"""
from datetime import datetime
from tg.controllers import RestController, redirect
from tg.decorators import expose, validate
from moviedemo.model import DBSession, Movie, Genre, Director
from formencode.validators import DateConverter, Int, NotEmpty

class MovieRestController(RestController):

    @expose('moviedemo.templates.rest.movies.get_all')
    def get_all(self):
        movies = DBSession.query(Movie).all()
        return dict(movies=movies)
    
    @expose('moviedemo.templates.rest.movies.new')
    def new(self, *args, **kw):
        genres = DBSession.query(Genre).all()
        directors = DBSession.query(Director).all()
        
        if 'directors' in kw and not isinstance(kw['directors'], list):
            kw['directors'] = [kw['directors']]

        return dict(values=kw, genres=genres, directors=directors)
    
    @validate({'title':NotEmpty, 
               'description':NotEmpty, 
               'genre_id':Int(not_empty=True), 
               'release_date':DateConverter(not_empty=True)}, error_handler=new)
    @expose()
    def post(self, title, description, directors=None, genre_id=None, release_date=None):
        if genre_id is not None:
            genre_id = int(genre_id)
        if directors is not None:
            if not isinstance(directors, list):
                directors = [directors]
            directors = [DBSession.query(Director).get(director) for director in directors]
        if release_date is not None:
            release_date = datetime.strptime(release_date, "%m/%d/%y")
        movie = Movie(title=title, description=description, release_date=release_date, directors=directors, genre_id=genre_id)
        DBSession.add(movie)
        redirect('./')