PageRenderTime 181ms CodeModel.GetById 164ms app.highlight 14ms RepoModel.GetById 1ms app.codeStats 0ms

/lib/galaxy/webapps/demo_sequencer/framework/__init__.py

https://bitbucket.org/cistrome/cistrome-harvard/
Python | 207 lines | 174 code | 10 blank | 23 comment | 6 complexity | a388f1cc3e5be7feb84b42bcc10da854 MD5 | raw file
  1"""
  2Demo sequencer web application framework
  3"""
  4
  5import json
  6import os
  7import pkg_resources
  8import random
  9import socket
 10import string
 11import sys
 12import time
 13
 14pkg_resources.require( "Cheetah" )
 15from Cheetah.Template import Template
 16
 17from galaxy.web.framework import helpers
 18
 19from galaxy import util
 20from galaxy.util.json import to_json_string, from_json_string
 21from galaxy.web.framework import url_for, expose, json, json_pretty, require_login, expose_api, error, form
 22from galaxy.web.framework import NOT_SET
 23from galaxy.web.framework import MessageException, FormBuilder, FormInput, FormData, Bunch
 24import galaxy.web.framework.base
 25
 26from galaxy.util import asbool
 27
 28pkg_resources.require( "Mako" )
 29import mako.template
 30import mako.lookup
 31import mako.runtime
 32
 33pkg_resources.require( "pexpect" )
 34pkg_resources.require( "amqp" )
 35
 36import logging
 37log = logging.getLogger( __name__ )
 38
 39class WebApplication( galaxy.web.framework.base.WebApplication ):
 40    def __init__( self, demo_app, session_cookie='demosequencersession' ):
 41        galaxy.web.framework.base.WebApplication.__init__( self )
 42        self.set_transaction_factory( lambda e: self.transaction_chooser( e, demo_app, session_cookie ) )
 43        # Mako support
 44        self.mako_template_lookup = mako.lookup.TemplateLookup(
 45            directories = [ demo_app.config.template_path ] ,
 46            module_directory = demo_app.config.template_cache,
 47            collection_size = 500,
 48            output_encoding = 'utf-8' )
 49        # Security helper
 50        self.security = demo_app.security
 51    def handle_controller_exception( self, e, trans, **kwargs ):
 52        if isinstance( e, MessageException ):
 53            return trans.show_message( e.err_msg, e.type )
 54    def make_body_iterable( self, trans, body ):
 55        if isinstance( body, FormBuilder ):
 56            body = trans.show_form( body )
 57        return galaxy.web.framework.base.WebApplication.make_body_iterable( self, trans, body )
 58    def transaction_chooser( self, environ, demo_app, session_cookie ):
 59        if 'is_api_request' in environ:
 60            return DemoWebAPITransaction( environ, demo_app, self )
 61        else:
 62            return DemoWebUITransaction( environ, demo_app, self, session_cookie )
 63
 64class DemoWebTransaction( galaxy.web.framework.base.DefaultWebTransaction ):
 65    """
 66    Encapsulates web transaction specific state for the Demo application
 67    (specifically the user's "cookie")
 68    """
 69    def __init__( self, environ, app, webapp ):
 70        self.app = app
 71        self.webapp = webapp
 72        self.security = webapp.security
 73        galaxy.web.framework.base.DefaultWebTransaction.__init__( self, environ )
 74        self.debug = asbool( self.app.config.get( 'debug', False ) )
 75    def get_cookie( self, name='demosequencersession' ):
 76        """Convenience method for getting a session cookie"""
 77        try:
 78            # If we've changed the cookie during the request return the new value
 79            if name in self.response.cookies:
 80                return self.response.cookies[name].value
 81            else:
 82                return self.request.cookies[name].value
 83        except:
 84            return None
 85    def set_cookie( self, value, name='demosequencersession', path='/', age=90, version='1' ):
 86        """Convenience method for setting a session cookie"""
 87        # The demosequencersession cookie value must be a high entropy 128 bit random number encrypted
 88        # using a server secret key.  Any other value is invalid and could pose security issues.
 89        self.response.cookies[name] = value
 90        self.response.cookies[name]['path'] = path
 91        self.response.cookies[name]['max-age'] = 3600 * 24 * age # 90 days
 92        tstamp = time.localtime ( time.time() + 3600 * 24 * age )
 93        self.response.cookies[name]['expires'] = time.strftime( '%a, %d-%b-%Y %H:%M:%S GMT', tstamp )
 94        self.response.cookies[name]['version'] = version
 95    def __update_session_cookie( self, name='galaxysession' ):
 96        """
 97        Update the session cookie to match the current session.
 98        """
 99        self.set_cookie( self.security.encode_guid( self.galaxy_session.session_key ), name=name, path=self.app.config.cookie_path )
100    def get_galaxy_session( self ):
101        """
102        Return the current galaxy session
103        """
104        return self.galaxy_session
105    @galaxy.web.framework.base.lazy_property
106    def template_context( self ):
107        return dict()
108    def make_form_data( self, name, **kwargs ):
109        rval = self.template_context[name] = FormData()
110        rval.values.update( kwargs )
111        return rval
112    def set_message( self, message, type=None ):
113        """
114        Convenience method for setting the 'message' and 'message_type'
115        element of the template context.
116        """
117        self.template_context['message'] = message
118        if type:
119            self.template_context['status'] = type
120    def get_message( self ):
121        """
122        Convenience method for getting the 'message' element of the template
123        context.
124        """
125        return self.template_context['message']
126    def show_message( self, message, type='info', refresh_frames=[], cont=None, use_panels=False, active_view="" ):
127        """
128        Convenience method for displaying a simple page with a single message.
129
130        `type`: one of "error", "warning", "info", or "done"; determines the
131                type of dialog box and icon displayed with the message
132
133        `refresh_frames`: names of frames in the interface that should be
134                          refreshed when the message is displayed
135        """
136        return self.fill_template( "message.mako", status=type, message=message, refresh_frames=refresh_frames, cont=cont, use_panels=use_panels, active_view=active_view )
137    def show_error_message( self, message, refresh_frames=[], use_panels=False, active_view="" ):
138        """
139        Convenience method for displaying an error message. See `show_message`.
140        """
141        return self.show_message( message, 'error', refresh_frames, use_panels=use_panels, active_view=active_view )
142    def show_ok_message( self, message, refresh_frames=[], use_panels=False, active_view="" ):
143        """
144        Convenience method for displaying an ok message. See `show_message`.
145        """
146        return self.show_message( message, 'done', refresh_frames, use_panels=use_panels, active_view=active_view )
147    def show_warn_message( self, message, refresh_frames=[], use_panels=False, active_view="" ):
148        """
149        Convenience method for displaying an warn message. See `show_message`.
150        """
151        return self.show_message( message, 'warning', refresh_frames, use_panels=use_panels, active_view=active_view )
152    def show_form( self, form, header=None, template="form.mako", use_panels=False, active_view="" ):
153        """
154        Convenience method for displaying a simple page with a single HTML
155        form.
156        """
157        return self.fill_template( template, form=form, header=header, use_panels=( form.use_panels or use_panels ),
158                                    active_view=active_view )
159    def fill_template(self, filename, **kwargs):
160        """
161        Fill in a template, putting any keyword arguments on the context.
162        """
163        if filename.endswith( ".mako" ):
164            return self.fill_template_mako( filename, **kwargs )
165        else:
166            template = Template( file=os.path.join(self.app.config.template_path, filename),
167                                 searchList=[kwargs, self.template_context, dict(caller=self, t=self, h=helpers, util=util, request=self.request, response=self.response, app=self.app)] )
168            return str( template )
169    def fill_template_mako( self, filename, **kwargs ):
170        template = self.webapp.mako_template_lookup.get_template( filename )
171        template.output_encoding = 'utf-8'
172        data = dict( caller=self, t=self, trans=self, h=helpers, util=util, request=self.request, response=self.response, app=self.app )
173        data.update( self.template_context )
174        data.update( kwargs )
175        return template.render( **data )
176    def stream_template_mako( self, filename, **kwargs ):
177        template = self.webapp.mako_template_lookup.get_template( filename )
178        template.output_encoding = 'utf-8'
179        data = dict( caller=self, t=self, trans=self, h=helpers, util=util, request=self.request, response=self.response, app=self.app )
180        data.update( self.template_context )
181        data.update( kwargs )
182        ## return template.render( **data )
183        def render( environ, start_response ):
184            response_write = start_response( self.response.wsgi_status(), self.response.wsgi_headeritems() )
185            class StreamBuffer( object ):
186                def write( self, d ):
187                    response_write( d.encode( 'utf-8' ) )
188            buffer = StreamBuffer()
189            context = mako.runtime.Context( buffer, **data )
190            template.render_context( context )
191            return []
192        return render
193    def fill_template_string(self, template_string, context=None, **kwargs):
194        """
195        Fill in a template, putting any keyword arguments on the context.
196        """
197        template = Template( source=template_string,
198                             searchList=[context or kwargs, dict(caller=self)] )
199        return str(template)
200
201class DemoWebAPITransaction( DemoWebTransaction ):
202    def __init__( self, environ, app, webapp ):
203        DemoWebTransaction.__init__( self, environ, app, webapp )
204
205class DemoWebUITransaction( DemoWebTransaction ):
206    def __init__( self, environ, app, webapp, session_cookie ):
207        DemoWebTransaction.__init__( self, environ, app, webapp )