PKH4'~iDDEGG-INFO/entry_points.txt [paste.paster_command] controller=pylons.commands:ControllerCommand compile_templates=pylons.commands:CompileCommand [paste.paster_create_template] pylons=pylons.util:PylonsTemplate [distutils.commands] lang_extract = pylons.i18n:LangExtract lang_compile = pylons.i18n:LangCompile PKﳼ4EGG-INFO/not-zip-safePKH46p_EGG-INFO/PKG-INFOMetadata-Version: 1.0 Name: Pylons Version: 0.8.2 Summary: Pylons Web Framework Home-page: http://pylons.groovie.org/ Author: Ben Bangert, James Gardner Author-email: ben@groovie.org License: UNKNOWN Description: The Pylons web framework is aimed at making webapps and large programmatic website development in Python easy. Several key points: * A framework to make writing web applications in Python easy * Inspired by Rails and TurboGears * Utilizes a minimalist, component-based philosophy that makes it easy to expand on * Built mainly as a customization of Myghty with Routes and Paste integration * Harness existing knowledge about Python Knowing Python makes Pylons easy --------------------------------- Pylons makes it easy to expand on your knowledge of Python to master Pylons for web development. Using a MVC style dispath, Python knowledge is used at various levels: * The Controller is just a basic Python class, called for each request. Customizing the response is as easy as overriding __call__ to make your webapp work how you want. * Myghty templating compiles directly to Python byte-code for speed and utilizes Python for template control rather than creating its own template syntax for "for, while, etc" Current Status --------------- Pylons is currently quite stable (built mostly with the mature Myghty package), and is being used in production environments. Dependant packages are automatically installed from the following URL: * `Dependant Packages svn `_ Platform: UNKNOWN Classifier: Development Status :: 4 - Beta Classifier: Intended Audience :: Developers Classifier: License :: OSI Approved :: BSD License Classifier: Programming Language :: Python Classifier: Topic :: Internet :: WWW/HTTP Classifier: Topic :: Internet :: WWW/HTTP :: Dynamic Content Classifier: Topic :: Software Development :: Libraries :: Python Modules PKH4}>y9YYEGG-INFO/requires.txtRoutes>=1.3.2 Myghty>=1.0.1 Paste>=0.9.3 PasteDeploy>=0.5 PasteScript>=0.5 simplejson>=1.3 WSGIUtils>=0.7 WebHelpers>=0.1.2 nose>=0.8.7 [test] py>=0.8.0_alpha2 [cheetah] Cheetah>=1.0 TurboCheetah>=0.9.5 [pudge] docutils>=0.4 elementtree>=1.2.6 kid>=0.9 pudge==dev,>=0.1.1dev buildutils==dev,>=0.1.2dev [kid] kid>=0.9 TurboKid==dev,>=0.9.1devPKH4^QWWEGG-INFO/SOURCES.txtCHANGELOG README.txt setup.cfg setup.py Pylons.egg-info/PKG-INFO Pylons.egg-info/SOURCES.txt Pylons.egg-info/entry_points.txt Pylons.egg-info/not-zip-safe Pylons.egg-info/requires.txt Pylons.egg-info/top_level.txt docs/adding_docs.txt docs/advanced.txt docs/application_configuration.txt docs/application_setup.txt docs/cred.txt docs/deployment.txt docs/development.txt docs/error_documents.txt docs/faq.txt docs/getting_started.txt docs/index.txt docs/install.txt docs/interactive_debugger.txt docs/internationalisation.txt docs/logging.txt docs/pylonsdev.txt docs/security.txt docs/security2.txt docs/strangeness.txt docs/template_plugins.txt docs/testing_web_application.txt docs/webserver_config.txt docs/windowsnotes.txt docs/wsgi.txt docs/pudge_template/class.html docs/pudge_template/common.html docs/pudge_template/document.html docs/pudge_template/layout.css docs/pudge_template/layout.html docs/pudge_template/master-index.html docs/pudge_template/member.html docs/pudge_template/module-index.html docs/pudge_template/module.html docs/pudge_template/package-index.html docs/pudge_template/pudge.css docs/pudge_template/rst.css docs/pudge_template/transitions.html ez_setup/README.txt ez_setup/__init__.py pylons/__init__.py pylons/commands.py pylons/config.py pylons/controllers.py pylons/database.py pylons/error.py pylons/helpers.py pylons/middleware.py pylons/myghtyroutes.py pylons/util.py pylons/wsgiapp.py pylons/decorators/__init__.py pylons/decorators/rest.py pylons/i18n/__init__.py pylons/i18n/msgfmt.py pylons/i18n/pygettext.py pylons/i18n/translation.py pylons/media/img/bar-bg.png pylons/media/img/bg.jpg pylons/media/img/hatch-yellow.png pylons/media/img/header.png pylons/media/img/highlight.png pylons/media/img/icon-16.png pylons/media/img/logo.gif pylons/media/img/main-nav-bg-on.png pylons/media/img/main-nav-bg.png pylons/media/img/plus.jpg pylons/media/img/tab-brown.png pylons/media/img/tab-white.png pylons/media/img/tab-yellow-highlight.png pylons/media/img/tab-yellow.png pylons/media/img/warning.gif pylons/media/style/orange.css pylons/templates/__init__.py pylons/templates/controller.py_tmpl pylons/templates/test_controller.py_tmpl pylons/templates/paster_template/README.txt_tmpl pylons/templates/paster_template/development.ini_tmpl pylons/templates/paster_template/setup.cfg_tmpl pylons/templates/paster_template/setup.py_tmpl pylons/templates/paster_template/+package+/__init__.py_tmpl pylons/templates/paster_template/+package+/websetup.py_tmpl pylons/templates/paster_template/+package+/components/empty.myt pylons/templates/paster_template/+package+/config/__init__.py_tmpl pylons/templates/paster_template/+package+/config/environment.py_tmpl pylons/templates/paster_template/+package+/config/middleware.py_tmpl pylons/templates/paster_template/+package+/config/routing.py_tmpl pylons/templates/paster_template/+package+/controllers/__init__.py_tmpl pylons/templates/paster_template/+package+/controllers/error.py_tmpl pylons/templates/paster_template/+package+/controllers/template.py_tmpl pylons/templates/paster_template/+package+/docs/index.txt_tmpl pylons/templates/paster_template/+package+/i18n/__init__.py_tmpl pylons/templates/paster_template/+package+/lib/__init__.py_tmpl pylons/templates/paster_template/+package+/lib/app_globals.py_tmpl pylons/templates/paster_template/+package+/lib/base.py_tmpl pylons/templates/paster_template/+package+/lib/helpers.py_tmpl pylons/templates/paster_template/+package+/models/__init__.py_tmpl pylons/templates/paster_template/+package+/public/index.html_tmpl pylons/templates/paster_template/+package+/templates/autohandler pylons/templates/paster_template/+package+/tests/__init__.py_tmpl pylons/templates/paster_template/+package+/tests/test_models.py_tmpl pylons/templates/paster_template/+package+/tests/functional/__init__.py_tmpl pylons/templates/paster_template/+project+.egg-info/paste_deploy_config.ini_tmpl_tmpl tests/__init__.py tests/conftest.py tests/test_units/__init__.py tests/test_webapps/test_make_project.py tests/test_webapps/test_files/app_globals.py tests/test_webapps/test_files/controller_test1.py tests/test_webapps/test_files/functional_test_controller_test1.py PKH4zm\ EGG-INFO/top_level.txttests pylons PKB4DFFpylons/__init__.py"""Base objects to be exported for use in Controllers""" from pylons.controllers import Controller, RPCController from pylons.decorators import jsonify from pylons.helpers import SessionProxy, RequestProxy, MyghtyProxy, GlobalsProxy, RequestArgProxy from pylons.util import RequestLocal, Buffet, Helpers m = MyghtyProxy() c = RequestLocal() g = GlobalsProxy() session = SessionProxy() request = RequestProxy() buffet = Buffet() params = RequestArgProxy() h = Helpers(m=m, c=c, session=session, request=request, buffet=buffet) __all__ = ['Controller', 'RPCController', 'jsonify'] PKI4M--pylons/__init__.pyc; qDc @sdZdklZlZdklZdklZlZl Z l Z l Z dk l Z lZlZe Ze Ze ZeZeZeZe Zededededed eZd d d gZd S(s2Base objects to be exported for use in Controllers(s Controllers RPCController(sjsonify(s SessionProxys RequestProxys MyghtyProxys GlobalsProxysRequestArgProxy(s RequestLocalsBuffetsHelperssmscssessionsrequestsbuffets Controllers RPCControllersjsonifyN(s__doc__spylons.controllerss Controllers RPCControllerspylons.decoratorssjsonifyspylons.helperss SessionProxys RequestProxys MyghtyProxys GlobalsProxysRequestArgProxys pylons.utils RequestLocalsBuffetsHelperssmscsgssessionsrequestsbuffetsparamsshs__all__(s RequestProxyscs__all__sgs SessionProxysrequestsjsonifysmsBuffetsRequestArgProxys GlobalsProxys ControllerssessionsHelperss RequestLocalshs RPCControllersparamssbuffets MyghtyProxy((s?build/bdist.darwin-8.6.0-Power_Macintosh/egg/pylons/__init__.pys?s %       'PK Z4[T T pylons/commands.py"""Paster Commands, for use with paster in your project The command(s) listed here are for use with Paste to enable easy creation of various core Pylons templates. Currently available commands are:: controller """ import os import glob from paste.script.command import Command, BadCommand from paste.script.filemaker import FileOp from paste.script import pluginlib, copydir class ControllerCommand(Command): """Create a Controller and functional test for it The Controller command will create the standard controller template file and associated functional test to speed creation of controllers. Example usage:: yourproj% paster controller comments Creating yourproj/yourproj/controllers/comments.py Creating yourproj/yourproj/tests/functional/test_comments.py If you'd like to have controllers underneath a directory, just include the path as the controller name and the necessary directories will be created for you:: yourproj% paster controller admin/trackback Creating yourproj/controllers/admin Creating yourproj/yourproj/controllers/admin/trackback.py Creating yourproj/yourproj/tests/functional/test_admin_trackback.py """ summary = "Create Controller" usage = 'CONTROLLER_NAME' min_args = 1 max_args = 1 group_name = 'pylons' parser = Command.standard_parser(simulate=True) parser.add_option('--no-test', action='store_true', dest='no_test', help="Don't create the test; just the controller") def command(self): try: self.verbose = 3 fo = FileOp(source_dir=os.path.join(os.path.dirname(__file__), 'templates')) try: name, dir = fo.parse_path_name_args(self.args[0]) except: raise BadCommand('No egg_info directory was found') fullname = os.path.join(dir, name) if not fullname.startswith(os.sep): fullname = os.sep + fullname testname = fullname.replace(os.sep, '_')[1:] fo.template_vars.update({'name': name.title().replace('-', '_'), 'fullname': fullname, 'fname': os.path.join(dir, name), 'lname': name}) fo.copy_file(template='controller.py_tmpl', dest=os.path.join('controllers', dir), filename=name) if not self.options.no_test: fo.copy_file(template='test_controller.py_tmpl', dest=os.path.join('tests', 'functional'), filename='test_'+testname) except: import sys msg = str(sys.exc_info()[1]) raise BadCommand('An unknown error ocurred, %s' % msg) PKI4PPpylons/commands.pyc; wxDc@sedZdkZdkZdklZlZdklZdkl Z l Z defdYZ dS(sPaster Commands, for use with paster in your project The command(s) listed here are for use with Paste to enable easy creation of various core Pylons templates. Currently available commands are:: controller N(sCommands BadCommand(sFileOp(s pluginlibscopydirsControllerCommandcBsftZdZdZdZdZdZdZei de Z e i dddd d d d d Z RS(s8Create a Controller and functional test for it The Controller command will create the standard controller template file and associated functional test to speed creation of controllers. Example usage:: yourproj% paster controller comments Creating yourproj/yourproj/controllers/comments.py Creating yourproj/yourproj/tests/functional/test_comments.py If you'd like to have controllers underneath a directory, just include the path as the controller name and the necessary directories will be created for you:: yourproj% paster controller admin/trackback Creating yourproj/controllers/admin Creating yourproj/yourproj/controllers/admin/trackback.py Creating yourproj/yourproj/tests/functional/test_admin_trackback.py sCreate ControllersCONTROLLER_NAMEispylonsssimulates --no-testsactions store_truesdestsno_testshelps*Don't create the test; just the controllercCsyd|_tdtiitiitd}y |i |i d\}}Wnt dnXtii||}|iti oti|}n|itidd}|iihd|iid d<d |<d tii||<d |<|id ddtiid|d||ii o3|id ddtiidddd|nWn6dk}t|id}t d|nXdS(Nis source_dirs templatesisNo egg_info directory was founds_isnames-sfullnamesfnameslnamestemplatescontroller.py_tmplsdests controllerssfilenamestest_controller.py_tmplstestss functionalstest_sAn unknown error ocurred, %s(sselfsverbosesFileOpsosspathsjoinsdirnames__file__sfosparse_path_name_argssargssnamesdirs BadCommandsfullnames startswithssepsreplacestestnames template_varssupdatestitles copy_filesoptionssno_testssyssstrsexc_infosmsg(sselfsnamestestnamessyssmsgsfullnamesdirsfo((s?build/bdist.darwin-8.6.0-Power_Macintosh/egg/pylons/commands.pyscommand2s, * U   (s__name__s __module__s__doc__ssummarysusagesmin_argssmax_argss group_namesCommandsstandard_parsersTruesparsers add_optionscommand(((s?build/bdist.darwin-8.6.0-Power_Macintosh/egg/pylons/commands.pysControllerCommands   ( s__doc__sossglobspaste.script.commandsCommands BadCommandspaste.script.filemakersFileOps paste.scripts pluginlibscopydirsControllerCommand(s pluginlibsglobsControllerCommandsFileOpscopydirsCommandsoss BadCommand((s?build/bdist.darwin-8.6.0-Power_Macintosh/egg/pylons/commands.pys? s    PK Z4  pylons/config.py"""Configuration setup for Myghty, and Paste error middleware This module supplies pylons_config which handles setting up defaults for Myghty, Paste errorware, and prefixing Routes if necessary. """ import os from myghty.resolver import * from paste.deploy.converters import asbool import pylons.myghtyroutes class Config(object): """Pylons configuration object The Pylons configuration object is a per-application instance object that retains the information regarding the global and app conf's as well as per-application instance specific data such as the mapper, the paths for this instance, and the myghty configuration. The Config object is available in your application as a Pylons global ``pylons_config`` under the ``g`` object. There's several useful attributes of the config object most people will be interested in: ``myghty`` The myghty configuration dict that was used to initialize Myghty ``map`` Mapper object used for Routing. Yes, it is possible to add routes after your application has started running. ``paths`` An array of absolute paths that were defined in the applications ``config/environment.py`` module. ``global_conf`` Global configuration passed in from Paste, this corresponds to the DEFAULTS section in the config file. ``app_conf`` Application specific configuration directives, passed in via Paste from the app section of the config file. """ def __init__(self, myghty, map, paths): self.myghty = myghty self.map = map self.paths = paths self.global_conf = {} self.app_conf = {} def init_app(self, global_conf, app_conf, package): """Initialize configuration for the application ``global_config`` Several options are expected to be set for a Pylons web application. They will be loaded from the global_config which has the main Paste options. If ``debug`` is set to ``false`` as a global config option, the following option *must* be set: * error_to - The email address to send the debug error to The optional config options in this case are: * smtp_server - The SMTP server to use, defaults to 'localhost' * error_log - A logfile to write the error to * error_subject_prefix - The prefix of the error email subject * from_address - Whom the error email should be from ``app_conf`` Defaults supplied via the [app:main] section from the Paste config file. ``load_config`` only cares about whether a 'prefix' option is set, if so it will update Routes to ensure URL's take that into account. ``package`` The name of the application package, to be stored in the app_conf. """ self.global_conf = global_conf self.app_conf = app_conf self.package = package app_conf['package'] = package # Setup the prefix to override the routes if necessary. prefix = app_conf.get('prefix') if not prefix: prefix = global_conf.get('prefix') if prefix: self.map.prefix = app_conf['prefix'] self.map._created_regs = False cache_dir = app_conf.get('cache_dir') if not cache_dir: cache_dir = global_conf.get('cache_dir') if not cache_dir: raise Exception("No 'cache_dir' key specified in the config file.") app_uuid = app_conf.get('app_instance_uuid') or global_conf.get('app_instance_uuid') if not app_uuid: raise Exception("No 'app__uuid' key specified in the config file.") cache_dir = os.path.join(cache_dir, app_uuid) myghty_defaults = {} # Where does the sessions/cache/etc. go for this instance of the webapp? myghty_defaults['data_dir'] = cache_dir session_dir = app_conf.get('session_data_dir') or global_conf.get('session_data_dir') if session_dir: myghty_defaults['session_data_dir'] = session_dir myghty_defaults['session_key'] = app_conf.get('session_key') or global_conf.get('session_key') myghty_defaults['session_secret'] = app_conf.get('session_secret') or global_conf.get('session_secret') # Raise a complete error for the error middleware to catch myghty_defaults['raise_error'] = True # Standard Pylons configuration directives for Myghty myghty_defaults.setdefault('allow_globals', []) myghty_defaults['allow_globals'].extend(['c', 'h', 's', 'session', 'request', 'g']) myghty_defaults['component_root'] = [{os.path.basename(path): path} for \ path in self.paths['templates']] # Pylons resolver strategy myghty_defaults['resolver_strategy'] = [ ConditionalGroup( context = 'request', rules = [ PathTranslate(), pylons.myghtyroutes.RoutesResolver( mapper=self.map, controller_root=self.paths['controllers'], scan_controllers=asbool(global_conf.get('debug', 'true'))), NotFound(), ] ), URICache(rule = ResolveFile()), ResolveUpwards(), ResolveFile(), ] errorware = {} # Load the errorware configuration from the Paste configuration file # These all have defaults, and emails are only sent if configured and # if this application is running in production mode errorware['debug'] = asbool(global_conf.get('debug', 'true')) if not errorware['debug']: errorware['debug'] = False errorware['error_email'] = global_conf.get('email_to') errorware['error_log'] = global_conf.get('error_log', None) errorware['smtp_server'] = global_conf.get('smtp_server', 'localhost') errorware['error_subject_prefix'] = global_conf.get('error_subject_prefix', 'WebApp Error: ') errorware['from_address'] = global_conf.get('from_address', global_conf.get('error_email_from', 'pylons@yourapp.com')) errorware['error_message'] = global_conf.get('error_message', 'An internal server error occurred') # Merge in the user-supplied Myghty values myghty_defaults.update(self.myghty) self.myghty = myghty_defaults # Save our errorware values self.errorware = errorware PKI4pylons/config.pyc; wxDc@sFdZdkZdkTdklZdkZdefdYZdS(sConfiguration setup for Myghty, and Paste error middleware This module supplies pylons_config which handles setting up defaults for Myghty, Paste errorware, and prefixing Routes if necessary. N(s*(sasboolsConfigcBs tZdZdZdZRS(sPylons configuration object The Pylons configuration object is a per-application instance object that retains the information regarding the global and app conf's as well as per-application instance specific data such as the mapper, the paths for this instance, and the myghty configuration. The Config object is available in your application as a Pylons global ``pylons_config`` under the ``g`` object. There's several useful attributes of the config object most people will be interested in: ``myghty`` The myghty configuration dict that was used to initialize Myghty ``map`` Mapper object used for Routing. Yes, it is possible to add routes after your application has started running. ``paths`` An array of absolute paths that were defined in the applications ``config/environment.py`` module. ``global_conf`` Global configuration passed in from Paste, this corresponds to the DEFAULTS section in the config file. ``app_conf`` Application specific configuration directives, passed in via Paste from the app section of the config file. cCs1||_||_||_h|_h|_dS(N(smyghtysselfsmapspathss global_confsapp_conf(sselfsmyghtysmapspaths((s=build/bdist.darwin-8.6.0-Power_Macintosh/egg/pylons/config.pys__init__'s     c Cs~||_||_||_||d<|id}| o|id}n|o |d|i_t|i_n|id}| ow|id}| ot dn|idp |id} | ot dnt i i|| }nh}||d<|idp |id} | o| |dtZdZedZdZdZdZdZRS(s|Transparently proxies to an AutoConnectHub for the URI that is appropriate for this package. A package URI is configured via "packagename.dburi" in the global CherryPy settings. If there is no package DB URI configured, the default (provided by "sqlobject.dburi") is used. The hub is not instantiated until an attempt is made to use the database. cCs||_t|_||_dS(N(s packagenamesselfsNoneshubsdburi(sselfs packagenamesdburi((s?build/bdist.darwin-8.6.0-Power_Macintosh/egg/pylons/database.pys__init__es  cCs0|i o|in|ii||SdS(N(sselfshubsset_hubs__get__sobjstype(sselfsobjstype((s?build/bdist.darwin-8.6.0-Power_Macintosh/egg/pylons/database.pys__get__js cCs0|i o|in|ii||SdS(N(sselfshubsset_hubs__set__sobjstype(sselfsobjstype((s?build/bdist.darwin-8.6.0-Power_Macintosh/egg/pylons/database.pys__set__os cCs-|i o|int|i|SdS(N(sselfshubsset_hubsgetattrsname(sselfsname((s?build/bdist.darwin-8.6.0-Power_Macintosh/egg/pylons/database.pys __getattr__ts cCs|i}| oOtidid|it}| o tididt}q`n| o tdnti|t}| ot |}|t|
%s
' % (title, self.quote(s)) else: return '%s: %s' % (title, self.quote(s)) elif isinstance(value, dict): return self.zebra_table(title, value) elif (isinstance(value, (list, tuple)) and self.long_item_list(value)): return '%s: [
\n    %s]
' % ( title, ',
    '.join(map(self.quote, map(repr, value)))) else: return '%s: %s' % (title, self.quote(repr(value))) def zebra_table(self, title, rows, table_class="variables"): if isinstance(rows, dict): rows = rows.items() rows.sort() table = ['' % table_class, '' % self.quote(title)] odd = False for name, value in rows: try: value = repr(value) except Exception, e: value = 'Cannot print: %s' % e odd = not odd table.append( '' % (odd and 'odd' or 'even', self.quote(name))) table.append( '' % make_wrappable(self.quote(value))) table.append('
%s
%s%s
') return '\n'.join(table) def format_combine(self, data_by_importance, lines, exc_info): lines[:0] = [value for n, value in data_by_importance['important']] lines.append(exc_info) for name in 'normal', 'supplemental': lines.extend([value for n, value in data_by_importance[name]]) extra_data = [] if data_by_importance['extra']: #extra_data.append( # '\n' + # '
\n') extra_data.extend([value for n, value in data_by_importance['extra']]) #extra_data.append('
') extra_data_text = self.format_combine_lines(extra_data) text = self.format_combine_lines(lines) if self.include_reusable: return str(error_css + hide_display_js + text), extra_data else: # Usually because another error is already on this page, # and so the js & CSS are unneeded return text, extra_data def format_html(exc_data, include_hidden_frames=False, **ops): if not include_hidden_frames: return HTMLFormatter(**ops).format_collected_data(exc_data) short_er = format_html(exc_data, show_hidden_frames=False, **ops) # @@: This should have a way of seeing if the previous traceback # was actually trimmed at all ops['include_reusable'] = False ops['show_extra_data'] = False long_er = format_html(exc_data, show_hidden_frames=True, **ops) text_er = format_text(exc_data, show_hidden_frames=True, **ops) return """ %s
%s

""" % (short_er, long_er, cgi.escape(text_er)), '' error_template = ''' Server Error %(head)s

Pylons


%(extra_data)s
%(myghty_data)s
%(traceback_data)s


The Pylons Team | Top
''' class InvalidTemplate(Exception): pass from pylons.util import get_prefix class PylonsEvalException(EvalException): def __init__(self, application, global_conf=None, xmlhttp_key=None, error_template=error_template, **errorparams): self.application = application self.error_template=error_template self.debug_infos = {} if xmlhttp_key is None: xmlhttp_key = global_conf.get('xmlhttp_key', '_') self.xmlhttp_key = xmlhttp_key self.errorparams = errorparams self.errorparams['debug_mode'] = self.errorparams['debug'] del self.errorparams['debug'] for s in ['head','traceback_data','extra_data','myghty_data']: if "%("+s+")s" not in self.error_template: raise InvalidTemplate("Could not find %s in template"%("%("+s+")s")) try: error_template%{'head': '', 'traceback_data': '', 'extra_data':'', 'myghty_data':'', 'set_tab':'', 'prefix':''} except: raise Exception('Invalid template. Please ensure all % signs are properly quoted as %% and no extra substitution strings are present.') def eval_javascript(self, base_path, counter): base_path = '/_debug' # Note the difference! return ( '\n' '\n' '\n' % (base_path, base_path, base_path, counter)) #~ def pylons(self, environ, start_response): #~ app = urlparser.StaticURLParser( #~ os.path.join(os.path.dirname(__file__), 'media')) #~ return app(environ, start_response) #~ pylons.exposed = True def respond(self, environ, start_response): base_path = request.construct_url(environ, with_path_info=False, with_query_string=False) environ['paste.throw_errors'] = True started = [] def detect_start_response(status, headers, exc_info=None): try: return start_response(status, headers, exc_info) except: raise else: started.append(True) try: __traceback_supplement__ = Supplement, self, environ app_iter = self.application(environ, detect_start_response) return self.catching_iter(app_iter, environ) except: exc_info = sys.exc_info() if inspect.isclass(exc_info[0]): for expected in environ.get('paste.expected_exceptions', []): if issubclass(exc_info[0], expected): raise count = debug_counter.next() view_uri = self.make_view_url(environ, base_path, count) if not started: headers = [('content-type', 'text/html')] headers.append(('X-Debug-URL', view_uri)) start_response('500 Internal Server Error', headers, exc_info) environ['wsgi.errors'].write('Debug at: %s\n' % view_uri) exc_data = collector.collect_exception(*exc_info) debug_info = DebugInfo(count, exc_info, exc_data, base_path, environ, view_uri) assert count not in self.debug_infos self.debug_infos[count] = debug_info if self.xmlhttp_key: get_vars = wsgilib.parse_querystring(environ) if dict(get_vars).get(self.xmlhttp_key): exc_data = collector.collect_exception(*exc_info) html = formatter.format_html( exc_data, include_hidden_frames=False, include_reusable=False, show_extra_data=False) return [html] base_path = get_prefix(environ) #base_path = environ['SCRIPT_NAME'] # @@: it would be nice to deal with bad content types here html, extra_data = format_eval_html(exc_data, base_path, count) #raise Exception(extra_data) head_html = (formatter.error_css + formatter.hide_display_js) head_html += self.eval_javascript(base_path, count) repost_button = make_repost_button(environ) myghty_data = '

No Myghty information available.

' tab = 'traceback_data' if hasattr(exc_info[1], 'htmlformat'): myghty_data = exc_info[1].htmlformat()[333:-14] tab = 'myghty_data' if hasattr(exc_info[1], 'mtrace'): myghty_data = exc_info[1].mtrace.htmlformat()[333:-14] tab = 'myghty_data' head_html = (""" """%{'prefix':base_path})+head_html traceback_data = """

Error Traceback

%(body)s
Extra Features
>>Display the lines of code near each part of the traceback
Show a debug prompt to allow you to directly debug the code at the traceback
%(repost_button)s"""%{ 'prefix':base_path, 'body':html, 'repost_button': repost_button or '', } page = self.error_template % { 'head': head_html, 'traceback_data': traceback_data, 'extra_data':"""

Extra Data

"""+'\n'.join(extra_data), 'myghty_data':myghty_data.replace('

','

').replace('

',''), 'set_tab':tab, 'prefix':base_path, } return [page] class EvalHTMLFormatter(HTMLFormatter): def __init__(self, base_path, counter, **kw): super(EvalHTMLFormatter, self).__init__(**kw) self.base_path = base_path self.counter = counter def format_source_line(self, filename, frame): line = formatter.HTMLFormatter.format_source_line( self, filename, frame) return (line + '     ' '    ' % (frame.tbid, self.base_path)) def format_eval_html(exc_data, base_path, counter): short_er, extra_data = EvalHTMLFormatter( base_path=base_path, counter=counter, include_reusable=False).format_collected_data(exc_data) #raise Exception(extra_data) long_er, extra_data_none = EvalHTMLFormatter( base_path=base_path, counter=counter, show_hidden_frames=True, show_extra_data=False, include_reusable=False).format_collected_data(exc_data) return """ %s

%s
""" % (short_er, long_er), extra_data PKI4o27 U Upylons/error.pyc; wxDc@sdZgZdkZdkZdkZdkTdkTdei fdYZ de i fdYZ e dZ dZd efd YZd klZd efd YZde fdYZdZdS(sqCustom error middleware subclasses, used for error theme These error middleware sub-classes are used mainly to provide skinning for the Paste middleware. In the future this entire module will likely be little more than a template, as Paste will get the skinning functionality. The only additional thing besides skinning supplied, is the Myghty traceback information. N(s*s SupplementcBstZdZdZRS(sYThis is a supplement used to display standard WSGI information in the traceback. c Csh} h}| ddf
%s
s%s: %ss$%s: [
    %s]
s,
    (s isinstancesvaluesstrsselfspretty_string_reprssstitlesquotesdicts zebra_tablesliststupleslong_item_listsjoinsmapsrepr(sselfs importancestitlesvaluess((s<build/bdist.darwin-8.6.0-Power_Macintosh/egg/pylons/error.pysformat_extra_dataos &0s variablesc Cs t|to|i}|ind|d|i|g}t }x|D]\}}yt|}Wntj o}d|}nX| }|id|odpd|i|f|idt|i|qTW|idd i|SdS( Nss/sCannot print: %sssoddsevenss
%s
%s%s
s (s isinstancesrowssdictsitemsssorts table_classsselfsquotestitlestablesFalsesoddsnamesvaluesreprs Exceptionsesappendsmake_wrappablesjoin( sselfstitlesrowss table_classsnamesvaluestablesoddse((s<build/bdist.darwin-8.6.0-Power_Macintosh/egg/pylons/error.pys zebra_tables   .$ c Cs0gi}|dD]\}}||q~|d*|i|xLddfD]>}|igi}||D]\}}||qm~qOWg} |do<| igi}|dD]\}}||q~n|i | } |i |}|iottt|| fSn || fSdS(Ns importantisnormals supplementalsextra(sappends_[1]sdata_by_importancesnsvalueslinessexc_infosnamesextends extra_datasselfsformat_combine_linessextra_data_textstextsinclude_reusablesstrs error_cssshide_display_js( sselfsdata_by_importanceslinessexc_infosnamestextsvaluesns_[1]sextra_data_texts extra_data((s<build/bdist.darwin-8.6.0-Power_Macintosh/egg/pylons/error.pysformat_combines5  < < (s__name__s __module__sformat_collected_datasformat_extra_datas zebra_tablesformat_combine(((s<build/bdist.darwin-8.6.0-Power_Macintosh/egg/pylons/error.pys HTMLFormatter2s <  cKs| ot|i|Snt|dt|}t|d
%s

s(sinclude_hidden_framess HTMLFormattersopssformat_collected_datasexc_datas format_htmlsFalsesshort_ersTrueslong_ers format_textstext_erscgisescape(sexc_datasinclude_hidden_framessopsslong_erstext_ersshort_er((s<build/bdist.darwin-8.6.0-Power_Macintosh/egg/pylons/error.pys format_htmls  s Server Error %(head)s

Pylons


%(extra_data)s
%(myghty_data)s
%(traceback_data)s


The Pylons Team | Top
sInvalidTemplatecBstZRS(N(s__name__s __module__(((s<build/bdist.darwin-8.6.0-Power_Macintosh/egg/pylons/error.pysInvalidTemplates(s get_prefixsPylonsEvalExceptioncBs,tZeeedZdZdZRS(NcKs||_||_h|_|tjo|idd}n||_||_|id|id<|id=xNddddgD]:}d |d |ijot d d |d qqWyB|hdd <dd <dd <dd <d d <dd <Wnt dnXdS(Ns xmlhttp_keys_sdebugs debug_modesheadstraceback_datas extra_datas myghty_datas%(s)ssCould not find %s in templatessset_tabsprefixstInvalid template. Please ensure all % signs are properly quoted as %% and no extra substitution strings are present.( s applicationsselfserror_templates debug_infoss xmlhttp_keysNones global_confsgets errorparamssssInvalidTemplates Exception(sselfs applications global_confs xmlhttp_keyserror_templates errorparamsss((s<build/bdist.darwin-8.6.0-Power_Macintosh/egg/pylons/error.pys__init__s"        BcCsd}d||||fSdS(Ns/_debugs (s base_pathscounter(sselfs base_pathscounter((s<build/bdist.darwin-8.6.0-Power_Macintosh/egg/pylons/error.pyseval_javascript-sc sti|dtdt}t|d|<d|i?d"d#i?d$d%<d&|<d|<}|gSnXdS('Nswith_path_infoswith_query_stringspaste.throw_errorscs2y|||SWn nXitdS(N(sstart_responsesstatussheaderssexc_infosstartedsappendsTrue(sstatussheaderssexc_info(sstartedsstart_response(s<build/bdist.darwin-8.6.0-Power_Macintosh/egg/pylons/error.pysdetect_start_responseEs ispaste.expected_exceptionss content-types text/htmls X-Debug-URLs500 Internal Server Errors wsgi.errorss Debug at: %s sinclude_hidden_framessinclude_reusablesshow_extra_datas'

No Myghty information available.

straceback_datais htmlformatiMis myghty_datasmtracesP sprefixs

Error Traceback

%(body)s
Extra Features
>>Display the lines of code near each part of the traceback
Show a debug prompt to allow you to directly debug the code at the traceback
%(repost_button)ssbodys repost_buttonssheads extra_datas7

Extra Data

s s

s

s

ssset_tab(Asrequests construct_urlsenvironsFalses base_pathsTruesstartedsNonesdetect_start_responses Supplementsselfs__traceback_supplement__s applicationsapp_iters catching_iterssyssexc_infosinspectsisclasssgetsexpecteds issubclasss debug_countersnextscounts make_view_urlsview_urisheaderssappendsstart_responseswrites collectorscollect_exceptionsexc_datas DebugInfos debug_infos debug_infossAssertionErrors xmlhttp_keyswsgilibsparse_querystringsget_varssdicts formatters format_htmlshtmls get_prefixsformat_eval_htmls extra_datas error_cssshide_display_jss head_htmlseval_javascriptsmake_repost_buttons repost_buttons myghty_datastabshasattrs htmlformatsmtracestraceback_dataserror_templatesjoinsreplacespage(sselfsenvironsstart_responsesdetect_start_responses head_htmls__traceback_supplement__stabsapp_itersexc_datashtmls repost_buttons debug_infosexpectedsstartedsview_uris base_pathsget_varss myghty_datastraceback_datascounts extra_datasheaderssexc_infospage((sstart_responsesstarteds<build/bdist.darwin-8.6.0-Power_Macintosh/egg/pylons/error.pysrespond@sl            -,h(s__name__s __module__sNoneserror_templates__init__seval_javascriptsrespond(((s<build/bdist.darwin-8.6.0-Power_Macintosh/egg/pylons/error.pysPylonsEvalExceptions sEvalHTMLFormattercBstZdZdZRS(NcKs,tt|i|||_||_dS(N(ssupersEvalHTMLFormattersselfs__init__skws base_pathscounter(sselfs base_pathscounterskw((s<build/bdist.darwin-8.6.0-Power_Macintosh/egg/pylons/error.pys__init__s cCs4tii|||}|d|i|ifSdS(Ns        ( s formatters HTMLFormattersformat_source_linesselfsfilenamesframeslinestbids base_path(sselfsfilenamesframesline((s<build/bdist.darwin-8.6.0-Power_Macintosh/egg/pylons/error.pysformat_source_lines(s__name__s __module__s__init__sformat_source_line(((s<build/bdist.darwin-8.6.0-Power_Macintosh/egg/pylons/error.pysEvalHTMLFormatters c Csxtd|d|dti|\}}td|d|dtdtdti|\}}d||f|fSdS(Ns base_pathscountersinclude_reusablesshow_hidden_framessshow_extra_datas %s

%s
( sEvalHTMLFormatters base_pathscountersFalsesformat_collected_datasexc_datasshort_ers extra_datasTrueslong_ersextra_data_none(sexc_datas base_pathscounterslong_ers extra_datasshort_ersextra_data_none((s<build/bdist.darwin-8.6.0-Power_Macintosh/egg/pylons/error.pysformat_eval_htmls  (s__doc__s__all__sinspectsmyghty.exceptionsmyghtyssysspaste.evalexception.middlewarespaste.exceptions.formatterserrormiddlewares Supplements formatters HTMLFormattersFalses format_htmlserror_templates ExceptionsInvalidTemplates pylons.utils get_prefixs EvalExceptionsPylonsEvalExceptionsEvalHTMLFormattersformat_eval_html( s format_htmlsmyghtys__all__sPylonsEvalExceptionsinspectsEvalHTMLFormattersformat_eval_htmlssyss Supplements HTMLFormattersInvalidTemplateserror_templates get_prefix((s<build/bdist.darwin-8.6.0-Power_Macintosh/egg/pylons/error.pys? s!{ G PKe4LM2g pylons/helpers.py""""Magic" helper objects (``session``, ``request``, ``m``) and ``etag_cache`` Additional helper object available for use in Controllers is the etag_cache. These helper objects provide convenient proxy access to the thread-local objects a web developer will want to use frequently. Any thread-local object can easily be proxy'd by sub-classing ObjectProxy and providing a ``_get_object`` method that will retrieve the desired thread-local for access. """ from myghty import request import pylons class ObjectProxy(object): """Proxy access to an object ObjectProxy provides direct access to an object that normally requires a function call of some sort to retrieve. """ def _get_object(self): raise NotImplementedError() def __getitem__(self, key): return self._get_object()[key] def __setitem__(self, key, value): self._get_object()[key] = value def __delitem__(self, key): self._get_object().__delitem__(key) def __getattr__(self, name): return getattr(self._get_object(), name) def __setattr__(self, name, value): setattr(self._get_object(), name, value) def __delattr__(self, name): self._get_object().__delattr__(name) def __repr__(self): return self._get_object().__repr__() def __iter__(self): return iter(self._get_object().keys()) def __len__(self): return len(self._get_object()) class SessionProxy(ObjectProxy): """Retrieves the session thread-local from the Myghty request""" def _get_object(self): inst = request.instance() return inst.get_session() class RequestProxy(ObjectProxy): """Retrieves the http request object from the Myghty request""" def _get_object(self): inst = request.instance() return inst.request_impl.httpreq class MyghtyProxy(ObjectProxy): """Retrieves the Myghty request object from the Myghty thread-local""" def _get_object(self): return request.instance() class GlobalsProxy(ObjectProxy): """Retrieves the environ globals var pylons.g""" def _get_object(self): req = request.instance().request_impl.httpreq return req.environ['pylons.g'] class RequestArgProxy(ObjectProxy): """Retrieves the request args from the Myghty request object""" def _get_object(self): inst = request.instance() return inst.request_args def etag_cache(key=None): """Use the HTTP Entity Tag cache for Browser side caching If a "If-None-Match" header is found, and equivilant to ``key``, then a ``304`` HTTP message will be returned with the ETag to tell the browser that it should use its current cache of the page. Otherwise, the ETag header will be added to the response for use in future request cycles. Suggested use is within a Controller Action like so:: import pylons class YourController(BaseController): def index(self): if pylons.etag_cache(key=1): return m.subexec('/splash.myt') """ if_none_match = pylons.request.environ.get('HTTP_IF_NONE_MATCH', None) pylons.request.headers_out['ETag'] = key if str(key) == if_none_match: pylons.m.abort(304) return True else: return False __all__ = ['SessionProxy', 'RequestProxy', 'MyghtyProxy', 'GlobalsProxy', 'etag_cache', 'RequestArgProxy'] PKI4ZNpylons/helpers.pyc; |Dc@sdZdklZdkZdefdYZdefdYZdefdYZd efd YZd efd YZ d efdYZ e dZ ddd d dd gZ dS(s"Magic" helper objects (``session``, ``request``, ``m``) and ``etag_cache`` Additional helper object available for use in Controllers is the etag_cache. These helper objects provide convenient proxy access to the thread-local objects a web developer will want to use frequently. Any thread-local object can easily be proxy'd by sub-classing ObjectProxy and providing a ``_get_object`` method that will retrieve the desired thread-local for access. (srequestNs ObjectProxycBshtZdZdZdZdZdZdZdZdZ dZ d Z d Z RS( sProxy access to an object ObjectProxy provides direct access to an object that normally requires a function call of some sort to retrieve. cCs tdS(N(sNotImplementedError(sself((s>build/bdist.darwin-8.6.0-Power_Macintosh/egg/pylons/helpers.pys _get_objectscCs|i|SdS(N(sselfs _get_objectskey(sselfskey((s>build/bdist.darwin-8.6.0-Power_Macintosh/egg/pylons/helpers.pys __getitem__scCs||i|build/bdist.darwin-8.6.0-Power_Macintosh/egg/pylons/helpers.pys __setitem__scCs|ii|dS(N(sselfs _get_objects __delitem__skey(sselfskey((s>build/bdist.darwin-8.6.0-Power_Macintosh/egg/pylons/helpers.pys __delitem__scCst|i|SdS(N(sgetattrsselfs _get_objectsname(sselfsname((s>build/bdist.darwin-8.6.0-Power_Macintosh/egg/pylons/helpers.pys __getattr__ scCst|i||dS(N(ssetattrsselfs _get_objectsnamesvalue(sselfsnamesvalue((s>build/bdist.darwin-8.6.0-Power_Macintosh/egg/pylons/helpers.pys __setattr__#scCs|ii|dS(N(sselfs _get_objects __delattr__sname(sselfsname((s>build/bdist.darwin-8.6.0-Power_Macintosh/egg/pylons/helpers.pys __delattr__&scCs|iiSdS(N(sselfs _get_objects__repr__(sself((s>build/bdist.darwin-8.6.0-Power_Macintosh/egg/pylons/helpers.pys__repr__)scCst|iiSdS(N(sitersselfs _get_objectskeys(sself((s>build/bdist.darwin-8.6.0-Power_Macintosh/egg/pylons/helpers.pys__iter__,scCst|iSdS(N(slensselfs _get_object(sself((s>build/bdist.darwin-8.6.0-Power_Macintosh/egg/pylons/helpers.pys__len__/s( s__name__s __module__s__doc__s _get_objects __getitem__s __setitem__s __delitem__s __getattr__s __setattr__s __delattr__s__repr__s__iter__s__len__(((s>build/bdist.darwin-8.6.0-Power_Macintosh/egg/pylons/helpers.pys ObjectProxys          s SessionProxycBstZdZdZRS(s:Retrieves the session thread-local from the Myghty requestcCsti}|iSdS(N(srequestsinstancesinsts get_session(sselfsinst((s>build/bdist.darwin-8.6.0-Power_Macintosh/egg/pylons/helpers.pys _get_object5s (s__name__s __module__s__doc__s _get_object(((s>build/bdist.darwin-8.6.0-Power_Macintosh/egg/pylons/helpers.pys SessionProxy3s s RequestProxycBstZdZdZRS(s9Retrieves the http request object from the Myghty requestcCsti}|iiSdS(N(srequestsinstancesinsts request_implshttpreq(sselfsinst((s>build/bdist.darwin-8.6.0-Power_Macintosh/egg/pylons/helpers.pys _get_object;s (s__name__s __module__s__doc__s _get_object(((s>build/bdist.darwin-8.6.0-Power_Macintosh/egg/pylons/helpers.pys RequestProxy9s s MyghtyProxycBstZdZdZRS(s@Retrieves the Myghty request object from the Myghty thread-localcCstiSdS(N(srequestsinstance(sself((s>build/bdist.darwin-8.6.0-Power_Macintosh/egg/pylons/helpers.pys _get_objectAs(s__name__s __module__s__doc__s _get_object(((s>build/bdist.darwin-8.6.0-Power_Macintosh/egg/pylons/helpers.pys MyghtyProxy?s s GlobalsProxycBstZdZdZRS(s*Retrieves the environ globals var pylons.gcCs!tiii}|idSdS(Nspylons.g(srequestsinstances request_implshttpreqsreqsenviron(sselfsreq((s>build/bdist.darwin-8.6.0-Power_Macintosh/egg/pylons/helpers.pys _get_objectFs(s__name__s __module__s__doc__s _get_object(((s>build/bdist.darwin-8.6.0-Power_Macintosh/egg/pylons/helpers.pys GlobalsProxyDs sRequestArgProxycBstZdZdZRS(s9Retrieves the request args from the Myghty request objectcCsti}|iSdS(N(srequestsinstancesinsts request_args(sselfsinst((s>build/bdist.darwin-8.6.0-Power_Macintosh/egg/pylons/helpers.pys _get_objectLs (s__name__s __module__s__doc__s _get_object(((s>build/bdist.darwin-8.6.0-Power_Macintosh/egg/pylons/helpers.pysRequestArgProxyJs cCs[tiiidt}|tiidbuild/bdist.darwin-8.6.0-Power_Macintosh/egg/pylons/helpers.pys etag_cacheQss etag_cache(s__doc__smyghtysrequestspylonssobjects ObjectProxys SessionProxys RequestProxys MyghtyProxys GlobalsProxysRequestArgProxysNones etag_caches__all__( s ObjectProxys RequestProxyspylonss__all__s SessionProxysrequestsRequestArgProxys GlobalsProxys MyghtyProxys etag_cache((s>build/bdist.darwin-8.6.0-Power_Macintosh/egg/pylons/helpers.pys? s  % PKB4`T{eepylons/middleware.py"EvalException, Error Documents, and Globals middleware" from paste.deploy.converters import asbool import os.path media_path = os.path.join(os.path.dirname(__file__), 'media') # # Global g variable # class Globals: pass class register_app_globals: """Small middleware application that saves per-application globals""" def __init__(self, app, globals): """Saves a reference to the WSGI app and globals for later use""" self.app = app self.globals = globals def __call__(self, environ, start_response): """Sets environ variable for globals before calling app""" environ['pylons.g'] = self.globals return self.app(environ, start_response) # # Customized Error Handling # def ErrorHandler(app, global_conf, **errorware): """ErrorHandler Toggle If debug is set, and true, this function will return the app wrapped in our customized Paste EvalException middleware we have called the ``PylonsEvalException``. Otherwise, the app will be wrapped in the Paste ErrorMiddleware, and the ``errorware`` dict will be passed into it. """ if asbool(global_conf.get('debug', 'true')): from pylons.error import PylonsEvalException app = PylonsEvalException(app, global_conf, **errorware) else: from paste.exceptions.errormiddleware import ErrorMiddleware if errorware.has_key('error_template'): del errorware['error_template'] app = ErrorMiddleware(app, global_conf, **errorware) return app # # Error Document Handling # from pylons.util import run_wsgi from paste.recursive import RecursiveMiddleware from paste.errordocument import custom_forward from urllib import urlencode from paste.deploy.converters import asbool from pylons.util import get_prefix def error_mapper(code, message, environ, global_conf={}, kw={}): codes = [401, 403, 404] if not asbool(global_conf.get('debug', 'true')): codes.append(500) if code in codes: url = '%s/error/document/?%s'%(get_prefix(environ), urlencode({'message':message, 'code':code})) return url def ErrorDocuments(app, global_conf={}, mapper=None, **kw): """Wraps the app in error docs using Paste RecursiveMiddleware and ErrorDocumentsMiddleware All the args are passed directly into the ErrorDocumentsMiddleware. If no mapper is given, a default error_mapper is passed in. """ if mapper == None: mapper = error_mapper app = RecursiveMiddleware(app) return custom_forward(app, global_conf=global_conf, mapper=mapper, **kw) error_document_template = """ Server Error %(code)s

Pylons


Error %(code)s

%(message)s

The Pylons Team | Top
""" __pudge_all__ = ['register_app_globals', 'ErrorHandler', 'ErrorDocuments']PKI4Jpylons/middleware.pyc; qDc@sdZdklZdkZeiieiiedZ dfdYZ dfdYZ dZ d k lZd klZd klZd klZdklZd k lZhhdZhedZdZdddgZdS(s6EvalException, Error Documents, and Globals middleware(sasboolNsmediasGlobalscBstZRS(N(s__name__s __module__(((sAbuild/bdist.darwin-8.6.0-Power_Macintosh/egg/pylons/middleware.pysGlobals ssregister_app_globalscBs tZdZdZdZRS(s?Small middleware application that saves per-application globalscCs||_||_dS(s;Saves a reference to the WSGI app and globals for later useN(sappsselfsglobals(sselfsappsglobals((sAbuild/bdist.darwin-8.6.0-Power_Macintosh/egg/pylons/middleware.pys__init__s cCs!|i|d<|i||SdS(s4Sets environ variable for globals before calling appspylons.gN(sselfsglobalssenvironsappsstart_response(sselfsenvironsstart_response((sAbuild/bdist.darwin-8.6.0-Power_Macintosh/egg/pylons/middleware.pys__call__s (s__name__s __module__s__doc__s__init__s__call__(((sAbuild/bdist.darwin-8.6.0-Power_Macintosh/egg/pylons/middleware.pysregister_app_globals s  cKs~t|iddo#dkl}||||}n;dkl}|i do |d=n||||}|SdS(sLErrorHandler Toggle If debug is set, and true, this function will return the app wrapped in our customized Paste EvalException middleware we have called the ``PylonsEvalException``. Otherwise, the app will be wrapped in the Paste ErrorMiddleware, and the ``errorware`` dict will be passed into it. sdebugstrue(sPylonsEvalException(sErrorMiddlewareserror_templateN( sasbools global_confsgets pylons.errorsPylonsEvalExceptionsapps errorwares paste.exceptions.errormiddlewaresErrorMiddlewareshas_key(sapps global_confs errorwaresErrorMiddlewaresPylonsEvalException((sAbuild/bdist.darwin-8.6.0-Power_Macintosh/egg/pylons/middleware.pys ErrorHandlers    (srun_wsgi(sRecursiveMiddleware(scustom_forward(s urlencode(s get_prefixcCsdddg}t|idd o|idn||jo6dt|thd|<d |<f}|SndS( Niiisdebugstrueis%s/error/document/?%ssmessagescode( scodessasbools global_confsgetsappendscodes get_prefixsenvirons urlencodesmessagesurl(scodesmessagesenvirons global_confskwsurlscodes((sAbuild/bdist.darwin-8.6.0-Power_Macintosh/egg/pylons/middleware.pys error_mapper=s  .cKs@|tjo t}nt|}t|d|d||SdS(sWraps the app in error docs using Paste RecursiveMiddleware and ErrorDocumentsMiddleware All the args are passed directly into the ErrorDocumentsMiddleware. If no mapper is given, a default error_mapper is passed in. s global_confsmapperN(smappersNones error_mappersRecursiveMiddlewaresappscustom_forwards global_confskw(sapps global_confsmapperskw((sAbuild/bdist.darwin-8.6.0-Power_Macintosh/egg/pylons/middleware.pysErrorDocumentsEs    s Server Error %(code)s

Pylons


Error %(code)s

%(message)s

The Pylons Team | Top
s ErrorHandlersErrorDocuments(s__doc__spaste.deploy.converterssasboolsos.pathsosspathsjoinsdirnames__file__s media_pathsGlobalssregister_app_globalss ErrorHandlers pylons.utilsrun_wsgispaste.recursivesRecursiveMiddlewarespaste.errordocumentscustom_forwardsurllibs urlencodes get_prefixs error_mappersNonesErrorDocumentsserror_document_templates __pudge_all__(s urlencodes error_mapperscustom_forwardsasboolsRecursiveMiddlewaresrun_wsgiserror_document_templatesErrorDocumentss ErrorHandlersregister_app_globalssGlobalss media_paths __pudge_all__soss get_prefix((sAbuild/bdist.darwin-8.6.0-Power_Macintosh/egg/pylons/middleware.pys?s   !        PKB40PKrf"f"pylons/myghtyroutes.py"""Myghty Routes Resolver and ComponentSource classes for controllers MyghtyRoutes implements Routes-based dispatching and controller setup using subclasses of Myghty ModuleComponentSource with a custom resolver called RoutesResolver. The custom Myghty Routes Resolver is used with Myghty's `Advanced Resolver Configuration `_ and is setup in `pylons.config `_. The ComponentSource and RoutesComponentSource classes are used to setup the controller and environment thread-locals for every request. They also ensure that the controller is reloaded if the file has been updated. """ import os import string import re, inspect from myghty.resolver import ResolverRule import myghty.csource as csource import myghty.component as comp from myghty.resolver import Resolution import myghty.importer as importer import myghty.escapes as escapes from myghty import request from routes import request_config from pylons.util import * import pylons.controllers as controllers import pylons class RoutesComponentSource(csource.ModuleComponentSource): """Holds a reference to the controller source file If the source file is updated, the module will be reloaded """ def __init__(self, objpath, module): arg = module for t in objpath: arg = getattr(arg, t) name = "class:" + objpath[0] self.has_method = False last_modified = importer.mod_time(module) csource.ComponentSource.__init__(self, "module|%s:%s" % (module.__name__, name), last_modified = last_modified) self.module = module self.objpath = objpath self.name = name self.class_ = RoutesComponent self.callable_ = arg def reload(self, module): self.module = module arg = module for t in self.objpath: arg = getattr(arg, t) self.callable_ = arg def can_compile(self): return False class RoutesComponent(comp.ModuleComponent): """Makes the Controller act like a ModuleComponent The RoutesComponent holds a reference to the Controller object, and instantiates/calls it during the request cycle. The environ dict is also setup here. """ def component_init(self): self.callable_ = self.component_source.callable_ def do_run_component(self, m, r, **params): # Clear thread-locals pylons.c._clear() pylons.buffet._clear() # Setup matchargs matchargs = m.resolution.override_args.copy() matchargs['ARGS'] = params['ARGS'] # Setup Myghty globals m.global_args.update(dict(session=pylons.session, request=pylons.request, c=pylons.c, h=pylons.h(), s=pylons.session, g=pylons.request.environ.get('pylons.g')) ) # Setup testing info if using paste fixture testing if r.environ.get('paste.testing'): self._load_test_env(r, m, params) if inspect.isclass(self.callable_) and issubclass(self.callable_, controllers.Controller): controller = self.callable_() # Instantiate the controller controller.c = pylons.c return controller(**matchargs) else: self.run_wsgi_app(self.callable_, **matchargs) def run_wsgi_app(self, controller, **params): # pylons.g key already there env = pylons.request.environ env['myghty.r'] = pylons.request env['myghty.m'] = pylons.m env['myghty.s'] = pylons.session env['pylons.h'] = pylons.h env['pylons.m'] = env['myghty.m'] env['pylons.request'] = env['myghty.r'] env['pylons.session'] = env['myghty.s'] # Fixup the PATH_INFO and SCRIPT_NAME if we have a url parameter config = request_config() oldpath = env['PATH_INFO'] newpath = params.get('path_info') or params.get('url') or '' env['PATH_INFO'] = newpath if not env['PATH_INFO'].startswith('/'): env['PATH_INFO'] = '/' + env['PATH_INFO'] env['SCRIPT_NAME'] += re.sub(r'^(.*?)/' + newpath + '$', r'\1', oldpath) if env['SCRIPT_NAME'].endswith('/'): env['SCRIPT_NAME'] = env['SCRIPT_NAME'][:-1] from pylons.util import run_wsgi run_wsgi(controller, pylons.m._get_object(), pylons.request._get_object(), env) def _load_test_env(self, r, m, params): """Sets up our Paste testing environment and Myghty mock objects""" testenv = r.environ['paste.testing_variables'] testenv['session'] = m.get_session() testenv['request'] = r testenv['m'] = m comprecord = testenv['comp_calls'] = [] def test_comp(func, call_name, comprecord): def record_call(*args, **kw): comprecord.append(dict(comptype=call_name, template=args[0], params=kw)) return func(*args, **kw) return record_call m.comp = test_comp(m.comp, 'comp', comprecord) m.scomp = test_comp(m.scomp, 'scomp', comprecord) def test_subrequest(func, comprecord): def record_subreq(*args, **kw): comprecord.append(dict(comptype='subrequest', template=args[0], params=kw)) return func(*args, **kw) return record_subreq m.make_subrequest = test_subrequest(m.make_subrequest, comprecord) testenv['params'] = params class RoutesResolver(ResolverRule): """A Myghty ResolverRule Subclass that implements Routes-base dispatching RoutesResolver subclasses ResolverRule and is used to implement Routes-based dispatching. The RoutesResolver currently is heavily bound to the Pylons run-time environment and is not usable outside of Pylons. """ name = 'routeresolver' def __init__(self, mapper=None, controller_root=None, scan_controllers=False, **params): """Initialize the RoutesResolver ``mapper`` Store a reference to the mapper used for this application ``controller_root`` Used to locate the controller module to load ``scan_controllers`` Indicates whether the controllers dir should be scanned every reuqest """ self.mapper = mapper self.controller_root = controller_root self.scan_controllers = scan_controllers def do_init_resolver(self, resolver, remaining_rules, **params): """Myghty Routes Resolver init Called by Myghty to initialize the RoutesResolver. Also initializes the Pylons module globals. """ self.mapper.always_scan = self.scan_controllers def do(self, uri, remaining, resolution_detail, **params): """Called per-Request by Myghty to Resolve the uri""" if resolution_detail is not None: resolution_detail.append("resolverouteresolver:" + uri) config = request_config() config.mapper = self.mapper m = request.instance() env = m.request_impl.httpreq.environ env['PATH_INFO'] = uri config.environ = env match = config.mapper_dict if match: config.redirect = m.send_redirect controller = match['controller'] action = match['action'] if action.startswith('_'): return remaining.next().do(uri, remaining, resolution_detail, **params) # Sanitaze keys for k,v in match.iteritems(): if v: match[k] = escapes.url_unescape(v) match = match.copy() # Remove the action/controller, rest of the args pass to the function del match['controller'] filename = self.controller_root + '/' + controller + '.py' controller_name = controller.split('/')[-1].title().replace('-', '_') classname = controller_name + 'Controller' module = importer.filemodule(filename) resolution_detail.append("\nController:%s, Action:%s" % (controller, action)) cs = RoutesComponentSource( module=module, objpath=[classname], ) #raise repr(cs.__dict__) return Resolution(cs, resolution_detail, override_args = match) else: return remaining.next().do(uri, remaining, resolution_detail, **params) PKI4@F!.!.pylons/myghtyroutes.pyc; qDc@sdZdkZdkZdkZdkZdklZdkiZdk i Z dkl Z dk iZdkiZdklZdklZdkTdkiZdkZdeifdYZd e ifd YZd efd YZdS( sMyghty Routes Resolver and ComponentSource classes for controllers MyghtyRoutes implements Routes-based dispatching and controller setup using subclasses of Myghty ModuleComponentSource with a custom resolver called RoutesResolver. The custom Myghty Routes Resolver is used with Myghty's `Advanced Resolver Configuration `_ and is setup in `pylons.config `_. The ComponentSource and RoutesComponentSource classes are used to setup the controller and environment thread-locals for every request. They also ensure that the controller is reloaded if the file has been updated. N(s ResolverRule(s Resolution(srequest(srequest_config(s*sRoutesComponentSourcecBs)tZdZdZdZdZRS(sxHolds a reference to the controller source file If the source file is updated, the module will be reloaded cCs|}x|D]}t||}q Wd|d}t|_t i |}t i i|d|i|fd|||_||_||_t|_||_dS(Nsclass:is module|%s:%ss last_modified(smodulesargsobjpathstsgetattrsnamesFalsesselfs has_methodsimportersmod_times last_modifiedscsourcesComponentSources__init__s__name__sRoutesComponentsclass_s callable_(sselfsobjpathsmodulesnames last_modifiedstsarg((sCbuild/bdist.darwin-8.6.0-Power_Macintosh/egg/pylons/myghtyroutes.pys__init__'s &    cCs?||_|}x |iD]}t||}qW||_dS(N(smodulesselfsargsobjpathstsgetattrs callable_(sselfsmodulestsarg((sCbuild/bdist.darwin-8.6.0-Power_Macintosh/egg/pylons/myghtyroutes.pysreload9s   cCstSdS(N(sFalse(sself((sCbuild/bdist.darwin-8.6.0-Power_Macintosh/egg/pylons/myghtyroutes.pys can_compileAs(s__name__s __module__s__doc__s__init__sreloads can_compile(((sCbuild/bdist.darwin-8.6.0-Power_Macintosh/egg/pylons/myghtyroutes.pysRoutesComponentSource"s   sRoutesComponentcBs2tZdZdZdZdZdZRS(sMakes the Controller act like a ModuleComponent The RoutesComponent holds a reference to the Controller object, and instantiates/calls it during the request cycle. The environ dict is also setup here. cCs|ii|_dS(N(sselfscomponent_sources callable_(sself((sCbuild/bdist.darwin-8.6.0-Power_Macintosh/egg/pylons/myghtyroutes.pyscomponent_initKscKs"tiitii|iii}|d|d<|i i t dti dtidtidtidti dtiiid|iid o|i|||nti|iot|itio&|i}ti|_||Sn|i|i|dS( NsARGSssessionsrequestscshsssgspylons.gs paste.testing(spylonsscs_clearsbuffetsms resolutions override_argsscopys matchargssparamss global_argssupdatesdictssessionsrequestshsenvironsgetsrsselfs_load_test_envsinspectsisclasss callable_s issubclasss controllerss Controllers controllers run_wsgi_app(sselfsmsrsparamss controllers matchargs((sCbuild/bdist.darwin-8.6.0-Power_Macintosh/egg/pylons/myghtyroutes.pysdo_run_componentNs"      )  cKs_tii}ti|d             %  ( s__name__s __module__s__doc__snamesNonesFalses__init__sdo_init_resolversdo(((sCbuild/bdist.darwin-8.6.0-Power_Macintosh/egg/pylons/myghtyroutes.pysRoutesResolvers  (s__doc__sossstringsresinspectsmyghty.resolvers ResolverRulesmyghty.csourcescsourcesmyghty.components componentscomps Resolutionsmyghty.importersimportersmyghty.escapessescapessmyghtysrequestsroutessrequest_configs pylons.utilspylons.controllerss controllersspylonssModuleComponentSourcesRoutesComponentSourcesModuleComponentsRoutesComponentsRoutesResolver(sRoutesComponentsstringsescapess ResolverRulescompsinspectsrequestsrequest_configs Resolutions controllerssresimportersRoutesResolversRoutesComponentSourcescsourcesosspylons((sCbuild/bdist.darwin-8.6.0-Power_Macintosh/egg/pylons/myghtyroutes.pys?s"            "VPKe4PM00pylons/util.py"""Helpers object, Buffet template plug-in, RequestLocal object, and Paste Template config The util module provides the main Helper object used by Pylons, in addition to the Buffet object which enables usage of template engines supporting the template plug-in scheme TurboGears utilizes. The RequestLocal thread-local is utilized by Pylons as the ``c`` object that is available via ``pylons.c`` and is cleared every request by Pylons. PylonsTemplate is a Paste Template sub-class that configures the source directory and default plug-ins for a new Pylons project. """ import sys import os.path, gettext import pkg_resources from paste.script.templates import Template import pylons from routes import threadinglocal from paste.deploy.config import CONFIG available_engines = {} for entry_point in pkg_resources.iter_entry_points('python.templating.engines'): Engine = entry_point.load() available_engines[entry_point.name] = Engine def get_prefix(environ): prefix = environ['paste.config']['app'].get('prefix') if not prefix: if environ.get('SCRIPT_NAME', '') != '': prefix = environ['SCRIPT_NAME'] if not prefix: prefix = '' return prefix def run_wsgi(app, m, request, environ=None): if environ == None: environ = request.environ def pylons_response(status, headers, exc_info=None): request.status = status if exc_info != None: raise exc_info request.headers_out.clear() for h,v in headers: if h.lower() == 'content-type': request.content_type=v else: request.headers_out[h] = v for data in app(environ, pylons_response): m.write(data) class RequestLocal(object): """This object emulates a dict and supports the full set of dict functions and operations. Internally, the dict is attached to a threading local object and all access is passed through to the thread-safe object. This difference means that the object must be initialized per-thread with a _clear() call before the object can be used, and it should be _clear()'ed every request call. The RequestLocal object also support attribute assignment, which is then internally stored as if they used item assignment. Attribute get is also supported, and is used to 'get' the name requested. Unlike normal attribute access, this will return an empty string if the attribute does not exist. """ def __init__(self): self.__dict__['_local'] = threadinglocal.local() def __getattr__(self, name): if name.startswith('_'): return object.__getattribute__(self, name) else: try: result = getattr(self._local.request, name) except AttributeError: result = self._local.request.get(name, '') return result def __setattr__(self, key, value): if key.startswith('_'): raise AttributeError("You cannot set attributes begining with '_' on the 'temp' object use temp['%s'] instead"%key) #object.__setattr__(self, key, value) else: self.__setitem__(key, value) def __len__(self): return self._local.request.__len__() def __getitem__(self, key): return self._local.request.__getitem__(key) def __setitem__(self, key, value): self._local.request.__setitem__(key, value) def __delitem__(self, key): self._local.request.__delitem__(key) def __iter__(self): return self._local.request.__iter__() def __contains__(self, item): return self._local.request.__contains__(item) def _clear(self): self._local.request = {} def __repr__(self): return self._local.request.__repr__() class LanguageError(Exception): """Exception raised when a problem occurs with changing languages""" pass class _Translator(object): """An empty gettext translator which just returns the original string""" def gettext(self, value): return value class Helpers(object): def __init__(self, **_pylons): self.__dict__['_local'] = RequestLocal() self.__dict__['_pylons'] = _pylons def __call__(self): """Initialize Helpers object for request with helpers module/object When called, the Helpers object will return itself, after initializing itself for the current thread/request. It is intended to be run at the begginning of every request to clear the thread local it uses and setup the helpers space that will be used for fetching helper names as well as translation. """ self.__dict__['_local']._clear() project_name = CONFIG['app']['package'] try: helpers_name = project_name + '.config.helpers' __import__(helpers_name) except: helpers_name = project_name + '.lib.helpers' __import__(helpers_name) helpers = sys.modules[helpers_name] self.__dict__['_local'].helpers = helpers self.__dict__['_local'].translator = _Translator() self.__dict__['_local'].config = CONFIG if CONFIG['app'].has_key('lang'): self.set_lang(CONFIG['app']['lang']) else: self.__dict__['_local'].lang = None return self def __getattr__(self, name): if hasattr(self.__dict__['_local'].helpers, name): return getattr(self.__dict__['_local'].helpers, name) elif name in self.__dict__['_local'].keys() and name != '_local' and len(str(name))>0 and str(name)[0] != '_': return getattr(self.__dict__['_local'],name) else: raise AttributeError('No such helper %s'%repr(name)) def __setattr__(self, name, value): if name not in ['lang']:# or not self.__dict__['_local'].has_key(name): raise AttributeError("Helper attributes cannot be set. You should use the context object 'c' to store conext information.") else: self.set_lang(value) def log(self, msg): """Log a message to the output log.""" self.__dict__['_pylons']['request'].environ['wsgi.errors'].write('=> %s\n'%str(msg)) def translate(self, value): """Deprecated, use _()""" raise NotImplementedError('Use h._() instead') def _(self, value): """Mark a string for translation Mark a string to be internationalised as follows: h._('This should be in lots of langauges') """ return self.__dict__['_local'].translator.gettext(value) def set_lang(self, lang): """Set the language used""" project_name = CONFIG['app']['package'] self.__dict__['_local'].lang = lang if lang == None: self.__dict__['_local'].translator = _Translator() else: from pkg_resources import resource_string, resource_stream, resource_exists, resource_filename from pylons.i18n.translation import egg_translation catalog_path = os.path.join('i18n', lang, 'LC_MESSAGES') if not resource_exists(project_name, catalog_path): raise LanguageError('Langauge catalog %s not found' % \ os.path.join(project_name, catalog_path)) self.__dict__['_local'].translator = \ egg_translation(project_name, lang=catalog_path) def get_lang(self): return self.__dict__['_local'].lang class BuffetError(Exception): pass class Buffet(object): """Buffet style plug-in template rendering Buffet implements template language plug-in support modeled highly on the `Buffet Project `_ from which this class inherits its name. """ def __init__(self): self._local = RequestLocal() def _clear(self): self._local._clear() def prepare(self, engine_name, template_root=None): """Prepare a template engine for use This method must be run every request before the `render <#render>`_ method is called so that the ``template_root`` can be set. """ Engine = available_engines.get(engine_name, None) if not Engine: raise TemplateEngineMissing('Please install a plugin for "%s" to use its functionality' % engine_name) setattr(self._local, engine_name, dict(engine=Engine(), root=template_root)) def render(self, engine_name, template_name, as_string=False, include_pylons_variables=True, namespace=None, **options): """Render a template using a template engine plug-in To use templates it is expected that you will attach data to be used in the template to the ``c`` variable which is available in the controller and the template. When porting code from other projects it is sometimes easier to use an exisitng dictionary which can be specified with ``namespace``. ``engine_name`` The name of the template engine to use, which must be 'prepared' first. ``template_name`` Name of the template to render ``as_string`` Whether or not to directly render the output to the browser, or return the rendered template as a string. ``include_pylons_variables`` If a custom namespace is specified this determines whether Pylons variables are included in the namespace or not. Defaults to ``True``. ``namespace`` A custom dictionary of names and values to be substituted in the template. If ``include_pylons_variables`` is ``True`` and any keys in ``namespace`` conflict with names of Pylons variables, an error is raised. All other keyword options are passed directly to the template engine used. """ for char in ['/','\\']: if char in template_name: raise BuffetError('Templates should be specified as module ' 'paths relative to the template root and therefore cannot ' 'contain %s characters' % repr(char)) def update_namespace(namespace): d = {} for k,v in namespace.items(): d[k] = v d.update( dict( c=pylons.c, h=pylons.h, m=pylons.m, request=pylons.request, g=pylons.request.environ['pylons.g'], session=pylons.session, ) ) return d if namespace==None: if include_pylons_variables is False: raise BuffetError('You must specify ``namespace`` if ``include_pylons_variables`` is ' 'False') else: namespace = update_namespace({}) elif isinstance(namespace, dict): if include_pylons_variables is True: keys = namespace.keys() for k in ['c','m','h','g','request','session']: if k in keys: raise Exception('The variable %s specified in namespace conflicts ' 'with the Pylons variable of the same name. Set ``include_pylons_variables`` ' 'to ``False`` if you do not want to use Pylons variables in your template'%k) namespace = update_namespace(namespace) else: namespace = update_namespace(namespace) engine_config = getattr(self._local, engine_name) full_path = os.path.join(engine_config['root'], template_name) dotted_path = full_path.replace(os.path.sep, '.').lstrip('.') page_data = engine_config['engine'].render(namespace, template=dotted_path, **options) if as_string: return page_data return pylons.m.write(page_data) class TemplateEngineMissing(Exception): pass class PylonsTemplate(Template): _template_dir = 'templates/paster_template' summary = 'Pylons application template' egg_plugins = ['Pylons', 'WebHelpers'] __all__ = ['RequestLocal', 'Helpers', 'Buffet'] __pudge_all__ = ['RequestLocal', 'Helpers', 'Buffet', 'PylonsTemplate'] PKI4.+JJpylons/util.pyc; |Dc@s}dZdkZdkZdkZdkZdklZdkZdk l Z dk l Z hZ x0eidD]ZeiZee eiException raised when a problem occurs with changing languages(s__name__s __module__s__doc__(((s;build/bdist.darwin-8.6.0-Power_Macintosh/egg/pylons/util.pys LanguageErrorus s _TranslatorcBstZdZdZRS(sBAn empty gettext translator which just returns the original stringcCs|SdS(N(svalue(sselfsvalue((s;build/bdist.darwin-8.6.0-Power_Macintosh/egg/pylons/util.pysgettext{s(s__name__s __module__s__doc__sgettext(((s;build/bdist.darwin-8.6.0-Power_Macintosh/egg/pylons/util.pys _Translatorys sHelperscBsYtZdZdZdZdZdZdZdZdZ d Z RS( NcKs!t|id<||id %s N(sselfs__dict__senvironswritesstrsmsg(sselfsmsg((s;build/bdist.darwin-8.6.0-Power_Macintosh/egg/pylons/util.pyslogscCstddS(sDeprecated, use _()sUse h._() insteadN(sNotImplementedError(sselfsvalue((s;build/bdist.darwin-8.6.0-Power_Macintosh/egg/pylons/util.pys translatescCs|idii|SdS(sMark a string for translation Mark a string to be internationalised as follows: h._('This should be in lots of langauges') s_localN(sselfs__dict__s translatorsgettextsvalue(sselfsvalue((s;build/bdist.darwin-8.6.0-Power_Macintosh/egg/pylons/util.pys_sc Cstdd}||id_|tjot|id_ndkl }l }l }l }dk l}tiid|d}||| o#tdtii||n||d ||id_d S( sSet the language usedsappspackages_local(sresource_stringsresource_streamsresource_existssresource_filename(segg_translationsi18ns LC_MESSAGESsLangauge catalog %s not foundslangN(sCONFIGs project_nameslangsselfs__dict__sNones _Translators translators pkg_resourcessresource_stringsresource_streamsresource_existssresource_filenamespylons.i18n.translationsegg_translationsosspathsjoins catalog_paths LanguageError( sselfslangs project_namesegg_translationsresource_existssresource_stringsresource_streamsresource_filenames catalog_path((s;build/bdist.darwin-8.6.0-Power_Macintosh/egg/pylons/util.pysset_langs  #cCs|idiSdS(Ns_local(sselfs__dict__slang(sself((s;build/bdist.darwin-8.6.0-Power_Macintosh/egg/pylons/util.pysget_langs( s__name__s __module__s__init__s__call__s __getattr__s __setattr__slogs translates_sset_langsget_lang(((s;build/bdist.darwin-8.6.0-Power_Macintosh/egg/pylons/util.pysHelpers~s       s BuffetErrorcBstZRS(N(s__name__s __module__(((s;build/bdist.darwin-8.6.0-Power_Macintosh/egg/pylons/util.pys BuffetErrorssBuffetcBs>tZdZdZdZedZeeedZ RS(sBuffet style plug-in template rendering Buffet implements template language plug-in support modeled highly on the `Buffet Project `_ from which this class inherits its name. cCst|_dS(N(s RequestLocalsselfs_local(sself((s;build/bdist.darwin-8.6.0-Power_Macintosh/egg/pylons/util.pys__init__scCs|iidS(N(sselfs_locals_clear(sself((s;build/bdist.darwin-8.6.0-Power_Macintosh/egg/pylons/util.pys_clearscCsWti|t}| otd|nt|i|t d|d|dS(sPrepare a template engine for use This method must be run every request before the `render <#render>`_ method is called so that the ``template_root`` can be set. s9Please install a plugin for "%s" to use its functionalitysenginesrootN( savailable_enginessgets engine_namesNonesEnginesTemplateEngineMissingssetattrsselfs_localsdicts template_root(sselfs engine_names template_rootsEngine((s;build/bdist.darwin-8.6.0-Power_Macintosh/egg/pylons/util.pysprepares cKsx;ddgD]-}||jotdt|q q Wd}|tjo-|tjotdq|h}nt |t oq|t jo`|i } xAdddd d d gD]'} | | jotd | qqW||}qn ||}t|i|} tii| d |}|itiidid} | di|d| |} |o| Snt i!i"| SdS(s2Render a template using a template engine plug-in To use templates it is expected that you will attach data to be used in the template to the ``c`` variable which is available in the controller and the template. When porting code from other projects it is sometimes easier to use an exisitng dictionary which can be specified with ``namespace``. ``engine_name`` The name of the template engine to use, which must be 'prepared' first. ``template_name`` Name of the template to render ``as_string`` Whether or not to directly render the output to the browser, or return the rendered template as a string. ``include_pylons_variables`` If a custom namespace is specified this determines whether Pylons variables are included in the namespace or not. Defaults to ``True``. ``namespace`` A custom dictionary of names and values to be substituted in the template. If ``include_pylons_variables`` is ``True`` and any keys in ``namespace`` conflict with names of Pylons variables, an error is raised. All other keyword options are passed directly to the template engine used. s/s\svTemplates should be specified as module paths relative to the template root and therefore cannot contain %s characterscCsh}x$|iD]\}}|||build/bdist.darwin-8.6.0-Power_Macintosh/egg/pylons/wsgiapp.pys__init__scCst|iiddoy|ii||SWqti i j oS}|i }t|d|do||d_n|d|d|dqXn|ii||SdS(Nsdebugstrues raw_excinfoiii(sasboolsselfs global_confsgetsappshandlesenvironsstart_responsesmyghtys exceptionsErrorses raw_excinfostbacksdelattrsmtrace(sselfsenvironsstart_responsesestback((s>build/bdist.darwin-8.6.0-Power_Macintosh/egg/pylons/wsgiapp.pys__call__s   !(s__name__s __module__s__init__s__call__(((s>build/bdist.darwin-8.6.0-Power_Macintosh/egg/pylons/wsgiapp.pys PylonsWSGIApps cCst|i|i}t|hd|i<d|i<d|i<d|i<}tii }y)t |i dt tdg}Wntj on X|i |i|id|}||_tii||}|SdS(Nsdefaultsappsapp_confs global_confs.lib.app_globalssGlobalssconfig(s PylonsWSGIAppsconfigs global_confsmyghtysappsConfigMiddlewaresapp_confspylonss middlewaresGlobalssgs __import__spackagesglobalsslocalss ImportErrors pylons_configsregister_app_globals(sconfigsgspackagesapp((s>build/bdist.darwin-8.6.0-Power_Macintosh/egg/pylons/wsgiapp.pysmake_app%s?) ( s__doc__spaste.deploy.configsConfigMiddlewarespaste.deploy.converterssasbools myghty.https WSGIHandlersmyghtyspylons.middlewarespylonssobjects PylonsWSGIAppsmake_app(smyghtyspylonssasbools PylonsWSGIAppsmake_appsConfigMiddlewares WSGIHandler((s>build/bdist.darwin-8.6.0-Power_Macintosh/egg/pylons/wsgiapp.pys?s     PKB4G, YEAR. # msgid "" msgstr "" "Project-Id-Version: PACKAGE VERSION\\n" "POT-Creation-Date: %%(time)s\\n" "PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\\n" "Last-Translator: %s <%s>\\n" "Language-Team: LANGUAGE \\n" "MIME-Version: 1.0\\n" "Content-Type: text/plain; charset=UTF-8\\n" "Content-Transfer-Encoding: ENCODING\\n" "Generated-By: Pylons %%(version)s\\n" ''' % ( project, self.distribution.get_author().lower(), self.distribution.get_author_email().lower(), ) # These could be filled in from setup.py pylons.i18n.pygettext.main() print "\nSucessfully created langauage template in %s\n" % pot_path print """Now create your langauge files, save them in i18n/lang replacing lang with the language code and changing the file extension to .po then run setup.py lang_compile mode to produce your .mo files""" sys.argv = oldsys class LangCompile(setuptools.Command): description = "compile strings for internationalisation" user_options = [('lang=', 'l', "language to compile"),] boolean_options = [] def finalize_options(self): pass def initialize_options(self): self.lang = None def compile_lang(self, lang): project = re.compile('[^a-zA-Z0-9_]').sub('', self.distribution.get_name().lower()) lang_path = os.path.join(project, 'i18n', lang) po_path = os.path.join(lang_path, '%s.po' % project) lc_path = os.path.join(lang_path, 'LC_MESSAGES') mo_path = os.path.join(lc_path, '%s.mo' % project) if not os.path.exists(lang_path) or not os.path.exists(po_path): print "Error: Could not find the directory %s" % lang_path sys.exit(1) if not os.path.exists(lc_path): os.mkdir(lc_path) oldsys = sys.argv sys.argv = [sys.argv[0], '-o', mo_path, po_path] import pylons.i18n.msgfmt pylons.i18n.msgfmt.main() print "Sucessfully generated '%s' catalog" % lang sys.argv = oldsys def run(self): project = re.compile('[^a-zA-Z0-9_]').sub('', self.distribution.get_name().lower()) if not self.lang: print "No langauge specified, compiling all languages" i18n_path = os.path.join(project, 'i18n') for lang in os.listdir(i18n_path): if os.path.isdir(os.path.join(i18n_path, lang)) and \ lang not in exclude_dirs: self.compile_lang(lang) else: self.compile_lang(self.lang) PKI4pT&&pylons/i18n/__init__.pyc; wxDc@srdZdkZdkZdkZdkZddddfZdeifdYZdeifd YZdS( sB Setuptools extensions and tools to add multiple language support Ns .AppleDoubles.svnsCVSs_darcss LangExtractcBs5tZdZgZgZdZdZdZRS(Ns(extract strings for internationalisationcCsdS(N((sself((sDbuild/bdist.darwin-8.6.0-Power_Macintosh/egg/pylons/i18n/__init__.pysinitialize_optionsscCsdS(N((sself((sDbuild/bdist.darwin-8.6.0-Power_Macintosh/egg/pylons/i18n/__init__.pysfinalize_optionssc CsAtidid|iii}ti i |dti }d|}ti i ||}ti i|od|GHtidnti}tiidtiiddd d |d |d gdk}d ||iii|iiif|ii_|iiid|GHdGH|t_dS(Ns [^a-zA-Z0-9_]ssi18n%ss%s.potsError: File %s already existsis-Ks-ks_s-os-ps*s# Pylons Project %s Translation File # Copyright (C) YEAR ORGANIZATION # FIRST AUTHOR , YEAR. # msgid "" msgstr "" "Project-Id-Version: PACKAGE VERSION\n" "POT-Creation-Date: %%(time)s\n" "PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n" "Last-Translator: %s <%s>\n" "Language-Team: LANGUAGE \n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: ENCODING\n" "Generated-By: Pylons %%(version)s\n" s. Sucessfully created langauage template in %s sNow create your langauge files, save them in i18n/lang replacing lang with the language code and changing the file extension to .po then run setup.py lang_compile mode to produce your .mo files(srescompilessubsselfs distributionsget_nameslowersprojectsosspathsjoinsseps i18n_paths pot_filenamespot_pathsexistsssyssexitsargvsoldsysspopsextendspylons.i18n.pygettextspylonss get_authorsget_author_emailsi18ns pygettexts pot_headersmain(sselfspot_pathspylonss pot_filenames i18n_pathsprojectsoldsys((sDbuild/bdist.darwin-8.6.0-Power_Macintosh/egg/pylons/i18n/__init__.pysruns *   ( : (s__name__s __module__s descriptions user_optionssboolean_optionssinitialize_optionssfinalize_optionssrun(((sDbuild/bdist.darwin-8.6.0-Power_Macintosh/egg/pylons/i18n/__init__.pys LangExtract s   s LangCompilecBsJtZdZdddfgZgZdZdZdZdZRS( Ns(compile strings for internationalisationslang=slslanguage to compilecCsdS(N((sself((sDbuild/bdist.darwin-8.6.0-Power_Macintosh/egg/pylons/i18n/__init__.pysfinalize_optionsCscCs t|_dS(N(sNonesselfslang(sself((sDbuild/bdist.darwin-8.6.0-Power_Macintosh/egg/pylons/i18n/__init__.pysinitialize_optionsEsc CsDtidid|iii}ti i |d|}ti i |d|}ti i |d}ti i |d|}ti i| pti i| od|GHtidnti i| oti|nti}tid d ||gt_dk}|iiid |GH|t_dS( Ns [^a-zA-Z0-9_]ssi18ns%s.pos LC_MESSAGESs%s.mos&Error: Could not find the directory %siis-os"Sucessfully generated '%s' catalog(srescompilessubsselfs distributionsget_nameslowersprojectsosspathsjoinslangs lang_pathspo_pathslc_pathsmo_pathsexistsssyssexitsmkdirsargvsoldsysspylons.i18n.msgfmtspylonssi18nsmsgfmtsmain( sselfslangslc_pathspylonss lang_pathsprojectsmo_pathspo_pathsoldsys((sDbuild/bdist.darwin-8.6.0-Power_Macintosh/egg/pylons/i18n/__init__.pys compile_langHs *(    cCstidid|iii}|i oxdGHt i i |d}xkt i |D]F}t i it i i ||o |tjo|i|q_q_Wn|i|idS(Ns [^a-zA-Z0-9_]ss.No langauge specified, compiling all languagessi18n(srescompilessubsselfs distributionsget_nameslowersprojectslangsosspathsjoins i18n_pathslistdirsisdirs exclude_dirss compile_lang(sselfslangs i18n_pathsproject((sDbuild/bdist.darwin-8.6.0-Power_Macintosh/egg/pylons/i18n/__init__.pysrun^s* /( s__name__s __module__s descriptions user_optionssboolean_optionssfinalize_optionssinitialize_optionss compile_langsrun(((sDbuild/bdist.darwin-8.6.0-Power_Macintosh/egg/pylons/i18n/__init__.pys LangCompile?s   ( s__doc__s setuptoolsssyssossres exclude_dirssCommands LangExtracts LangCompile(s exclude_dirss LangExtracts LangCompilessyssres setuptoolssos((sDbuild/bdist.darwin-8.6.0-Power_Macintosh/egg/pylons/i18n/__init__.pys?s$6PKe4`*pylons/i18n/msgfmt.py#! /usr/bin/env python # -*- coding: iso-8859-1 -*- # Written by Martin v. Lwis """Generate binary message catalog from textual translation description. This program converts a textual Uniforum-style message catalog (.po file) into a binary GNU catalog (.mo file). This is essentially the same function as the GNU msgfmt program, however, it is a simpler implementation. Usage: msgfmt.py [OPTIONS] filename.po Options: -o file --output-file=file Specify the output file to write to. If omitted, output will go to a file named filename.mo (based off the input file name). -h --help Print this message and exit. -V --version Display version information and exit. """ import sys import os import getopt import struct import array __version__ = "1.1" MESSAGES = {} def usage(code, msg=''): print >> sys.stderr, __doc__ if msg: print >> sys.stderr, msg sys.exit(code) def add(id, str, fuzzy): "Add a non-fuzzy translation to the dictionary." global MESSAGES if not fuzzy and str: MESSAGES[id] = str def generate(): "Return the generated output." global MESSAGES keys = MESSAGES.keys() # the keys are sorted in the .mo file keys.sort() offsets = [] ids = strs = '' for id in keys: # For each string, we need size and file offset. Each string is NUL # terminated; the NUL does not count into the size. offsets.append((len(ids), len(id), len(strs), len(MESSAGES[id]))) ids += id + '\0' strs += MESSAGES[id] + '\0' output = '' # The header is 7 32-bit unsigned integers. We don't use hash tables, so # the keys start right after the index tables. # translated string. keystart = 7*4+16*len(keys) # and the values start after the keys valuestart = keystart + len(ids) koffsets = [] voffsets = [] # The string table first has the list of keys, then the list of values. # Each entry has first the size of the string, then the file offset. for o1, l1, o2, l2 in offsets: koffsets += [l1, o1+keystart] voffsets += [l2, o2+valuestart] offsets = koffsets + voffsets output = struct.pack("Iiiiiii", 0x950412deL, # Magic 0, # Version len(keys), # # of entries 7*4, # start of key index 7*4+len(keys)*8, # start of value index 0, 0) # size and offset of hash table output += array.array("i", offsets).tostring() output += ids output += strs return output def make(filename, outfile): ID = 1 STR = 2 # Compute .mo name from .po name and arguments if filename.endswith('.po'): infile = filename else: infile = filename + '.po' if outfile is None: outfile = os.path.splitext(infile)[0] + '.mo' try: lines = open(infile).readlines() except IOError, msg: print >> sys.stderr, msg sys.exit(1) section = None fuzzy = 0 # Parse the catalog lno = 0 for l in lines: lno += 1 # If we get a comment line after a msgstr, this is a new entry if l[0] == '#' and section == STR: add(msgid, msgstr, fuzzy) section = None fuzzy = 0 # Record a fuzzy mark if l[:2] == '#,' and l.find('fuzzy'): fuzzy = 1 # Skip comments if l[0] == '#': continue # Now we are in a msgid section, output previous section if l.startswith('msgid'): if section == STR: add(msgid, msgstr, fuzzy) section = ID l = l[5:] msgid = msgstr = '' # Now we are in a msgstr section elif l.startswith('msgstr'): section = STR l = l[6:] # Skip empty lines l = l.strip() if not l: continue # XXX: Does this always follow Python escape semantics? l = eval(l) if section == ID: msgid += l elif section == STR: msgstr += l else: print >> sys.stderr, 'Syntax error on %s:%d' % (infile, lno), \ 'before:' print >> sys.stderr, l sys.exit(1) # Add last entry if section == STR: add(msgid, msgstr, fuzzy) # Compute output output = generate() try: open(outfile,"wb").write(output) except IOError,msg: print >> sys.stderr, msg def main(): try: opts, args = getopt.getopt(sys.argv[1:], 'hVo:', ['help', 'version', 'output-file=']) except getopt.error, msg: usage(1, msg) outfile = None # parse options for opt, arg in opts: if opt in ('-h', '--help'): usage(0) elif opt in ('-V', '--version'): print >> sys.stderr, "msgfmt.py", __version__ sys.exit(0) elif opt in ('-o', '--output-file'): outfile = arg # do it if not args: print >> sys.stderr, 'No input file given' print >> sys.stderr, "Try `msgfmt --help' for more information." return for filename in args: make(filename, outfile) if __name__ == '__main__': main() PKI4C pylons/i18n/msgfmt.pyc; |Dc@sdZdkZdkZdkZdkZdkZdZhaddZdZ dZ dZ dZ e d jo e ndS( sGenerate binary message catalog from textual translation description. This program converts a textual Uniforum-style message catalog (.po file) into a binary GNU catalog (.mo file). This is essentially the same function as the GNU msgfmt program, however, it is a simpler implementation. Usage: msgfmt.py [OPTIONS] filename.po Options: -o file --output-file=file Specify the output file to write to. If omitted, output will go to a file named filename.mo (based off the input file name). -h --help Print this message and exit. -V --version Display version information and exit. Ns1.1scCs6titIJ|oti|IJnti|dS(N(ssyssstderrs__doc__smsgsexitscode(scodesmsg((sBbuild/bdist.darwin-8.6.0-Power_Macintosh/egg/pylons/i18n/msgfmt.pysusage(s cCs!| o|o|t| # # Minimally patched to make it even more xgettext compatible # by Peter Funk # # 2002-11-22 Jrgen Hermann # Added checks that _() only contains string literals, and # command line args are resolved to module lists, i.e. you # can now pass a filename, a module or package name, or a # directory (including globbing chars, important for Win32). # Made docstring fit in 80 chars wide displays using pydoc. # # for selftesting try: import fintl _ = fintl.gettext except ImportError: _ = lambda s: s __doc__ = _("""pygettext -- Python equivalent of xgettext(1) Many systems (Solaris, Linux, Gnu) provide extensive tools that ease the internationalization of C programs. Most of these tools are independent of the programming language and can be used from within Python programs. Martin von Loewis' work[1] helps considerably in this regard. There's one problem though; xgettext is the program that scans source code looking for message strings, but it groks only C (or C++). Python introduces a few wrinkles, such as dual quoting characters, triple quoted strings, and raw strings. xgettext understands none of this. Enter pygettext, which uses Python's standard tokenize module to scan Python source code, generating .pot files identical to what GNU xgettext[2] generates for C and C++ code. From there, the standard GNU tools can be used. A word about marking Python strings as candidates for translation. GNU xgettext recognizes the following keywords: gettext, dgettext, dcgettext, and gettext_noop. But those can be a lot of text to include all over your code. C and C++ have a trick: they use the C preprocessor. Most internationalized C source includes a #define for gettext() to _() so that what has to be written in the source is much less. Thus these are both translatable strings: gettext("Translatable String") _("Translatable String") Python of course has no preprocessor so this doesn't work so well. Thus, pygettext searches only for _() by default, but see the -k/--keyword flag below for how to augment this. [1] http://www.python.org/workshops/1997-10/proceedings/loewis.html [2] http://www.gnu.org/software/gettext/gettext.html NOTE: pygettext attempts to be option and feature compatible with GNU xgettext where ever possible. However some options are still missing or are not fully implemented. Also, xgettext's use of command line switches with option arguments is broken, and in these cases, pygettext just defines additional switches. Usage: pygettext [options] inputfile ... Options: -a --extract-all Extract all strings. -d name --default-domain=name Rename the default output file from messages.pot to name.pot. -E --escape Replace non-ASCII characters with octal escape sequences. -D --docstrings Extract module, class, method, and function docstrings. These do not need to be wrapped in _() markers, and in fact cannot be for Python to consider them docstrings. (See also the -X option). -h --help Print this help message and exit. -k word --keyword=word Keywords to look for in addition to the default set, which are: %(DEFAULTKEYWORDS)s You can have multiple -k flags on the command line. -K --no-default-keywords Disable the default set of keywords (see above). Any keywords explicitly added with the -k/--keyword option are still recognized. --no-location Do not write filename/lineno location comments. -n --add-location Write filename/lineno location comments indicating where each extracted string is found in the source. These lines appear before each msgid. The style of comments is controlled by the -S/--style option. This is the default. -o filename --output=filename Rename the default output file from messages.pot to filename. If filename is `-' then the output is sent to standard out. -p dir --output-dir=dir Output files will be placed in directory dir. -S stylename --style stylename Specify which style to use for location comments. Two styles are supported: Solaris # File: filename, line: line-number GNU #: filename:line The style name is case insensitive. GNU style is the default. -v --verbose Print the names of the files being processed. -V --version Print the version of pygettext and exit. -w columns --width=columns Set width of output to columns. -x filename --exclude-file=filename Specify a file that contains a list of strings that are not be extracted from the input files. Each string to be excluded must appear on a line by itself in the file. -X filename --no-docstrings=filename Specify a file that contains a list of files (one per line) that should not have their docstrings extracted. This is only useful in conjunction with the -D option above. If `inputfile' is -, standard input is read. """) import os import imp import sys import glob import time import getopt import token import tokenize import operator __version__ = '1.5' default_keywords = ['_'] DEFAULTKEYWORDS = ', '.join(default_keywords) EMPTYSTRING = '' # The normal pot-file header. msgmerge and Emacs's po-mode work better if it's # there. pot_header = _('''\ # SOME DESCRIPTIVE TITLE. # Copyright (C) YEAR ORGANIZATION # FIRST AUTHOR , YEAR. # msgid "" msgstr "" "Project-Id-Version: PACKAGE VERSION\\n" "POT-Creation-Date: %(time)s\\n" "PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\\n" "Last-Translator: FULL NAME \\n" "Language-Team: LANGUAGE \\n" "MIME-Version: 1.0\\n" "Content-Type: text/plain; charset=CHARSET\\n" "Content-Transfer-Encoding: ENCODING\\n" "Generated-By: pygettext.py %(version)s\\n" ''') def usage(code, msg=''): print >> sys.stderr, __doc__ % globals() if msg: print >> sys.stderr, msg sys.exit(code) escapes = [] def make_escapes(pass_iso8859): global escapes if pass_iso8859: # Allow iso-8859 characters to pass through so that e.g. 'msgid # "Hhe"' would result not result in 'msgid "H\366he"'. Otherwise we # escape any character outside the 32..126 range. mod = 128 else: mod = 256 for i in range(256): if 32 <= (i % mod) <= 126: escapes.append(chr(i)) else: escapes.append("\\%03o" % i) escapes[ord('\\')] = '\\\\' escapes[ord('\t')] = '\\t' escapes[ord('\r')] = '\\r' escapes[ord('\n')] = '\\n' escapes[ord('\"')] = '\\"' def escape(s): global escapes s = list(s) for i in range(len(s)): s[i] = escapes[ord(s[i])] return EMPTYSTRING.join(s) def safe_eval(s): # unwrap quotes, safely return eval(s, {'__builtins__':{}}, {}) def normalize(s): # This converts the various Python string types into a format that is # appropriate for .po files, namely much closer to C style. lines = s.split('\n') if len(lines) == 1: s = '"' + escape(s) + '"' else: if not lines[-1]: del lines[-1] lines[-1] = lines[-1] + '\n' for i in range(len(lines)): lines[i] = escape(lines[i]) lineterm = '\\n"\n"' s = '""\n"' + lineterm.join(lines) + '"' return s def containsAny(str, set): """Check whether 'str' contains ANY of the chars in 'set'""" return 1 in [c in str for c in set] def _visit_pyfiles(list, dirname, names): """Helper for getFilesForName().""" # get extension for python source files if not globals().has_key('_py_ext'): global _py_ext _py_ext = [triple[0] for triple in imp.get_suffixes() if triple[2] == imp.PY_SOURCE][0] # don't recurse into CVS directories if 'CVS' in names: names.remove('CVS') # add all *.py files to list list.extend( [os.path.join(dirname, file) for file in names if os.path.splitext(file)[1] == _py_ext] ) def _get_modpkg_path(dotted_name, pathlist=None): """Get the filesystem path for a module or a package. Return the file system path to a file for a module, and to a directory for a package. Return None if the name is not found, or is a builtin or extension module. """ # split off top-most name parts = dotted_name.split('.', 1) if len(parts) > 1: # we have a dotted path, import top-level package try: file, pathname, description = imp.find_module(parts[0], pathlist) if file: file.close() except ImportError: return None # check if it's indeed a package if description[2] == imp.PKG_DIRECTORY: # recursively handle the remaining name parts pathname = _get_modpkg_path(parts[1], [pathname]) else: pathname = None else: # plain name try: file, pathname, description = imp.find_module( dotted_name, pathlist) if file: file.close() if description[2] not in [imp.PY_SOURCE, imp.PKG_DIRECTORY]: pathname = None except ImportError: pathname = None return pathname def getFilesForName(name): """Get a list of module files for a filename, a module or package name, or a directory. """ if not os.path.exists(name): # check for glob chars if containsAny(name, "*?[]"): files = glob.glob(name) list = [] for file in files: list.extend(getFilesForName(file)) return list # try to find module or package name = _get_modpkg_path(name) if not name: return [] if os.path.isdir(name): # find all python files in directory list = [] os.path.walk(name, _visit_pyfiles, list) return list elif os.path.exists(name): # a single file return [name] return [] class TokenEater: def __init__(self, options): self.__options = options self.__messages = {} self.__state = self.__waiting self.__data = [] self.__lineno = -1 self.__freshmodule = 1 self.__curfile = None def __call__(self, ttype, tstring, stup, etup, line): # dispatch ## import token ## print >> sys.stderr, 'ttype:', token.tok_name[ttype], \ ## 'tstring:', tstring self.__state(ttype, tstring, stup[0]) def __waiting(self, ttype, tstring, lineno): opts = self.__options # Do docstring extractions, if enabled if opts.docstrings and not opts.nodocstrings.get(self.__curfile): # module docstring? if self.__freshmodule: if ttype == tokenize.STRING: self.__addentry(safe_eval(tstring), lineno, isdocstring=1) self.__freshmodule = 0 elif ttype not in (tokenize.COMMENT, tokenize.NL): self.__freshmodule = 0 return # class docstring? if ttype == tokenize.NAME and tstring in ('class', 'def'): self.__state = self.__suiteseen return if ttype == tokenize.NAME and tstring in opts.keywords: self.__state = self.__keywordseen def __suiteseen(self, ttype, tstring, lineno): # ignore anything until we see the colon if ttype == tokenize.OP and tstring == ':': self.__state = self.__suitedocstring def __suitedocstring(self, ttype, tstring, lineno): # ignore any intervening noise if ttype == tokenize.STRING: self.__addentry(safe_eval(tstring), lineno, isdocstring=1) self.__state = self.__waiting elif ttype not in (tokenize.NEWLINE, tokenize.INDENT, tokenize.COMMENT): # there was no class docstring self.__state = self.__waiting def __keywordseen(self, ttype, tstring, lineno): if ttype == tokenize.OP and tstring == '(': self.__data = [] self.__lineno = lineno self.__state = self.__openseen else: self.__state = self.__waiting def __openseen(self, ttype, tstring, lineno): if ttype == tokenize.OP and tstring == ')': # We've seen the last of the translatable strings. Record the # line number of the first line of the strings and update the list # of messages seen. Reset state for the next batch. If there # were no strings inside _(), then just ignore this entry. if self.__data: self.__addentry(EMPTYSTRING.join(self.__data)) self.__state = self.__waiting elif ttype == tokenize.STRING: self.__data.append(safe_eval(tstring)) elif ttype not in [tokenize.COMMENT, token.INDENT, token.DEDENT, token.NEWLINE, tokenize.NL]: # warn if we see anything else than STRING or whitespace print >> sys.stderr, _( '*** %(file)s:%(lineno)s: Seen unexpected token "%(token)s"' ) % { 'token': tstring, 'file': self.__curfile, 'lineno': self.__lineno } self.__state = self.__waiting def __addentry(self, msg, lineno=None, isdocstring=0): if lineno is None: lineno = self.__lineno if not msg in self.__options.toexclude: entry = (self.__curfile, lineno) self.__messages.setdefault(msg, {})[entry] = isdocstring def set_filename(self, filename): self.__curfile = filename self.__freshmodule = 1 def write(self, fp): options = self.__options timestamp = time.strftime('%Y-%m-%d %H:%M+%Z') # The time stamp in the header doesn't have the same format as that # generated by xgettext... print >> fp, pot_header % {'time': timestamp, 'version': __version__} # Sort the entries. First sort each particular entry's keys, then # sort all the entries by their first item. reverse = {} for k, v in self.__messages.items(): keys = v.keys() keys.sort() reverse.setdefault(tuple(keys), []).append((k, v)) rkeys = reverse.keys() rkeys.sort() for rkey in rkeys: rentries = reverse[rkey] rentries.sort() for k, v in rentries: isdocstring = 0 # If the entry was gleaned out of a docstring, then add a # comment stating so. This is to aid translators who may wish # to skip translating some unimportant docstrings. if reduce(operator.__add__, v.values()): isdocstring = 1 # k is the message string, v is a dictionary-set of (filename, # lineno) tuples. We want to sort the entries in v first by # file name and then by line number. v = v.keys() v.sort() if not options.writelocations: pass # location comments are different b/w Solaris and GNU: elif options.locationstyle == options.SOLARIS: for filename, lineno in v: d = {'filename': filename, 'lineno': lineno} print >>fp, _( '# File: %(filename)s, line: %(lineno)d') % d elif options.locationstyle == options.GNU: # fit as many locations on one line, as long as the # resulting line length doesn't exceeds 'options.width' locline = '#:' for filename, lineno in v: d = {'filename': filename, 'lineno': lineno} s = _(' %(filename)s:%(lineno)d') % d if len(locline) + len(s) <= options.width: locline = locline + s else: print >> fp, locline locline = "#:" + s if len(locline) > 2: print >> fp, locline if isdocstring: print >> fp, '#, docstring' print >> fp, 'msgid', normalize(k) print >> fp, 'msgstr ""\n' def main(): global default_keywords try: opts, args = getopt.getopt( sys.argv[1:], 'ad:DEhk:Kno:p:S:Vvw:x:X:', ['extract-all', 'default-domain=', 'escape', 'help', 'keyword=', 'no-default-keywords', 'add-location', 'no-location', 'output=', 'output-dir=', 'style=', 'verbose', 'version', 'width=', 'exclude-file=', 'docstrings', 'no-docstrings', ]) except getopt.error, msg: usage(1, msg) # for holding option values class Options: # constants GNU = 1 SOLARIS = 2 # defaults extractall = 0 # FIXME: currently this option has no effect at all. escape = 0 keywords = [] outpath = '' outfile = 'messages.pot' writelocations = 1 locationstyle = GNU verbose = 0 width = 78 excludefilename = '' docstrings = 0 nodocstrings = {} options = Options() locations = {'gnu' : options.GNU, 'solaris' : options.SOLARIS, } # parse options for opt, arg in opts: if opt in ('-h', '--help'): usage(0) elif opt in ('-a', '--extract-all'): options.extractall = 1 elif opt in ('-d', '--default-domain'): options.outfile = arg + '.pot' elif opt in ('-E', '--escape'): options.escape = 1 elif opt in ('-D', '--docstrings'): options.docstrings = 1 elif opt in ('-k', '--keyword'): options.keywords.append(arg) elif opt in ('-K', '--no-default-keywords'): default_keywords = [] elif opt in ('-n', '--add-location'): options.writelocations = 1 elif opt in ('--no-location',): options.writelocations = 0 elif opt in ('-S', '--style'): options.locationstyle = locations.get(arg.lower()) if options.locationstyle is None: usage(1, _('Invalid value for --style: %s') % arg) elif opt in ('-o', '--output'): options.outfile = arg elif opt in ('-p', '--output-dir'): options.outpath = arg elif opt in ('-v', '--verbose'): options.verbose = 1 elif opt in ('-V', '--version'): print _('pygettext.py (xgettext for Python) %s') % __version__ sys.exit(0) elif opt in ('-w', '--width'): try: options.width = int(arg) except ValueError: usage(1, _('--width argument must be an integer: %s') % arg) elif opt in ('-x', '--exclude-file'): options.excludefilename = arg elif opt in ('-X', '--no-docstrings'): fp = open(arg) try: while 1: line = fp.readline() if not line: break options.nodocstrings[line[:-1]] = 1 finally: fp.close() # calculate escapes make_escapes(options.escape) # calculate all keywords options.keywords.extend(default_keywords) # initialize list of strings to exclude if options.excludefilename: try: fp = open(options.excludefilename) options.toexclude = fp.readlines() fp.close() except IOError: print >> sys.stderr, _( "Can't read --exclude-file: %s") % options.excludefilename sys.exit(1) else: options.toexclude = [] # resolve args to module lists expanded = [] for arg in args: if arg == '-': expanded.append(arg) else: expanded.extend(getFilesForName(arg)) args = expanded # slurp through all the files eater = TokenEater(options) for filename in args: if filename == '-': if options.verbose: print _('Reading standard input') fp = sys.stdin closep = 0 else: if options.verbose: print _('Working on %s') % filename fp = open(filename) closep = 1 try: eater.set_filename(filename) try: tokenize.tokenize(fp.readline, eater) except tokenize.TokenError, e: print >> sys.stderr, '%s: %s, line %d, column %d' % ( e[0], filename, e[1][0], e[1][1]) finally: if closep: fp.close() # write the output if options.outfile == '-': fp = sys.stdout closep = 0 else: if options.outpath: options.outfile = os.path.join(options.outpath, options.outfile) fp = open(options.outfile, 'w') closep = 1 try: eater.write(fp) finally: if closep: fp.close() if __name__ == '__main__': main() # some more test strings _(u'a unicode string') # this one creates a warning _('*** Seen unexpected token "%(token)s"') % {'token': 'test'} _('more' 'than' 'one' 'string') PKI4ůYYpylons/i18n/pygettext.pyc; |Dc@sydkZeiZWnej odZnXedZdkZdkZdkZdkZdk Z dk Z dk Z dk Z dk Z dZdgaditZdZedZddZgad Zd Zd Zd Zd ZdZedZdZdfdYZdZ e!djo6e ededhdd<edndS(NcCs|S(N(ss(ss((sEbuild/bdist.darwin-8.6.0-Power_Macintosh/egg/pylons/i18n/pygettext.pyssspygettext -- Python equivalent of xgettext(1) Many systems (Solaris, Linux, Gnu) provide extensive tools that ease the internationalization of C programs. Most of these tools are independent of the programming language and can be used from within Python programs. Martin von Loewis' work[1] helps considerably in this regard. There's one problem though; xgettext is the program that scans source code looking for message strings, but it groks only C (or C++). Python introduces a few wrinkles, such as dual quoting characters, triple quoted strings, and raw strings. xgettext understands none of this. Enter pygettext, which uses Python's standard tokenize module to scan Python source code, generating .pot files identical to what GNU xgettext[2] generates for C and C++ code. From there, the standard GNU tools can be used. A word about marking Python strings as candidates for translation. GNU xgettext recognizes the following keywords: gettext, dgettext, dcgettext, and gettext_noop. But those can be a lot of text to include all over your code. C and C++ have a trick: they use the C preprocessor. Most internationalized C source includes a #define for gettext() to _() so that what has to be written in the source is much less. Thus these are both translatable strings: gettext("Translatable String") _("Translatable String") Python of course has no preprocessor so this doesn't work so well. Thus, pygettext searches only for _() by default, but see the -k/--keyword flag below for how to augment this. [1] http://www.python.org/workshops/1997-10/proceedings/loewis.html [2] http://www.gnu.org/software/gettext/gettext.html NOTE: pygettext attempts to be option and feature compatible with GNU xgettext where ever possible. However some options are still missing or are not fully implemented. Also, xgettext's use of command line switches with option arguments is broken, and in these cases, pygettext just defines additional switches. Usage: pygettext [options] inputfile ... Options: -a --extract-all Extract all strings. -d name --default-domain=name Rename the default output file from messages.pot to name.pot. -E --escape Replace non-ASCII characters with octal escape sequences. -D --docstrings Extract module, class, method, and function docstrings. These do not need to be wrapped in _() markers, and in fact cannot be for Python to consider them docstrings. (See also the -X option). -h --help Print this help message and exit. -k word --keyword=word Keywords to look for in addition to the default set, which are: %(DEFAULTKEYWORDS)s You can have multiple -k flags on the command line. -K --no-default-keywords Disable the default set of keywords (see above). Any keywords explicitly added with the -k/--keyword option are still recognized. --no-location Do not write filename/lineno location comments. -n --add-location Write filename/lineno location comments indicating where each extracted string is found in the source. These lines appear before each msgid. The style of comments is controlled by the -S/--style option. This is the default. -o filename --output=filename Rename the default output file from messages.pot to filename. If filename is `-' then the output is sent to standard out. -p dir --output-dir=dir Output files will be placed in directory dir. -S stylename --style stylename Specify which style to use for location comments. Two styles are supported: Solaris # File: filename, line: line-number GNU #: filename:line The style name is case insensitive. GNU style is the default. -v --verbose Print the names of the files being processed. -V --version Print the version of pygettext and exit. -w columns --width=columns Set width of output to columns. -x filename --exclude-file=filename Specify a file that contains a list of strings that are not be extracted from the input files. Each string to be excluded must appear on a line by itself in the file. -X filename --no-docstrings=filename Specify a file that contains a list of files (one per line) that should not have their docstrings extracted. This is only useful in conjunction with the -D option above. If `inputfile' is -, standard input is read. s1.5s_s, ss# SOME DESCRIPTIVE TITLE. # Copyright (C) YEAR ORGANIZATION # FIRST AUTHOR , YEAR. # msgid "" msgstr "" "Project-Id-Version: PACKAGE VERSION\n" "POT-Creation-Date: %(time)s\n" "PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n" "Last-Translator: FULL NAME \n" "Language-Team: LANGUAGE \n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=CHARSET\n" "Content-Transfer-Encoding: ENCODING\n" "Generated-By: pygettext.py %(version)s\n" cCs=tittIJ|oti|IJnti|dS(N(ssyssstderrs__doc__sglobalssmsgsexitscode(scodesmsg((sEbuild/bdist.darwin-8.6.0-Power_Macintosh/egg/pylons/i18n/pygettext.pysusagescCs|o d}nd}x^tdD]P}d||jo djnotit|q$tid|q$Wdttd | i| i| _nt$| idD}d}z|i?|Wd|o|i)nXdS(ENisad:DEhk:Kno:p:S:Vvw:x:X:s extract-allsdefault-domain=sescapeshelpskeyword=sno-default-keywordss add-locations no-locationsoutput=s output-dir=sstyle=sverbosesversionswidth=s exclude-file=s docstringss no-docstringssOptionscBs\tZdZdZdZdZgZdZdZdZ eZ dZ dZ dZ dZhZRS(Niiiss messages.potiN(s__name__s __module__sGNUsSOLARISs extractallsescapeskeywordssoutpathsoutfileswritelocationss locationstylesverboseswidthsexcludefilenames docstringss nodocstrings(((sEbuild/bdist.darwin-8.6.0-Power_Macintosh/egg/pylons/i18n/pygettext.pysOptions ssgnussolariss-hs--helpis-as --extract-alls-ds--default-domains.pots-Es--escapes-Ds --docstringss-ks --keywords-Ks--no-default-keywordss-ns--add-locations --no-locations-Ss--stylesInvalid value for --style: %ss-os--outputs-ps --output-dirs-vs --verboses-Vs --versions%pygettext.py (xgettext for Python) %ss-ws--widths'--width argument must be an integer: %ss-xs--exclude-files-Xs--no-docstringsisCan't read --exclude-file: %ss-sReading standard inputs Working on %ss%s: %s, line %d, column %dsw(@sgetoptssyssargvsoptssargsserrorsmsgsusagesOptionssoptionssGNUsSOLARISs locationssoptsargs extractallsoutfilesescapes docstringsskeywordssappendsdefault_keywordsswritelocationssgetslowers locationstylesNones_soutpathsverboses __version__sexitsintswidths ValueErrorsexcludefilenamesopensfpsreadlineslines nodocstringsscloses make_escapessextends readliness toexcludesIOErrorsstderrsexpandedsgetFilesForNames TokenEaterseatersfilenamesstdinscloseps set_filenamestokenizes TokenErrorsesstdoutsosspathsjoinswrite(sfps locationssargsclosepsfilenamesoptseatersargssmsgslinesOptionssesexpandedsoptionssopts((sEbuild/bdist.darwin-8.6.0-Power_Macintosh/egg/pylons/i18n/pygettext.pysmainsF                           :   "s__main__ua unicode strings%*** Seen unexpected token "%(token)s"stokenstestsmorethanonestring("sfintlsgettexts_s ImportErrors__doc__sossimpssyssglobstimesgetoptstokenstokenizesoperators __version__sdefault_keywordssjoinsDEFAULTKEYWORDSs EMPTYSTRINGs pot_headersusagesescapess make_escapessescapes safe_evals normalizes containsAnys_visit_pyfilessNones_get_modpkg_pathsgetFilesForNames TokenEatersmains__name__(s_visit_pyfilessescapesoperators normalizesDEFAULTKEYWORDSsimpsfintlstokenizesusagesgetopts __version__s__doc__sgetFilesForNames pot_headersglobs make_escapesssyss TokenEaters_s safe_evalsmains_get_modpkg_paths EMPTYSTRINGs containsAnystokenstimesos((sEbuild/bdist.darwin-8.6.0-Power_Macintosh/egg/pylons/i18n/pygettext.pys?sH                     '   PK Z4oݯpylons/i18n/translation.pyimport os from gettext import * from pkg_resources import resource_stream def egg_translation(domain, lang): """ This method doesn't do all the checking etc of the gettext.translation method but it seems to work. We can't just use gettext.translation because the .mo files might be in eggs """ class_ = GNUTranslations return class_(resource_stream(domain, os.path.join(lang, '%s.mo' % domain))) PKI4xApylons/i18n/translation.pyc; wxDc@s*dkZdkTdklZdZdS(N(s*(sresource_streamcCs0t}|t|tii|d|SdS(s This method doesn't do all the checking etc of the gettext.translation method but it seems to work. We can't just use gettext.translation because the .mo files might be in eggs s%s.moN(sGNUTranslationssclass_sresource_streamsdomainsosspathsjoinslang(sdomainslangsclass_((sGbuild/bdist.darwin-8.6.0-Power_Macintosh/egg/pylons/i18n/translation.pysegg_translations(sossgettexts pkg_resourcessresource_streamsegg_translation(sresource_streamsossegg_translation((sGbuild/bdist.darwin-8.6.0-Power_Macintosh/egg/pylons/i18n/translation.pys?s  PKB4 pylons/media/img/bar-bg.pngPNG  IHDRfmF,tEXtCreation TimeSat 26 Nov 2005 00:07:39 -000088tIME 0"5 H pHYs B4gAMA aUIDATxIR0ENێ 8(0d `QEUҫzb Zk ˭,ּ2_ɁU#V{Oz/;l9B}|ϖ4n90ͱk >}v~jܞU;d 'i|]*e}bHv7̀WwW<03- p{q)ۇq(KeO ׏'Y$)L#}+lyYk+%F)5GTV@48sa>{S{US/?2IENDB`PKB46HG)G)pylons/media/img/bg.jpgJFIFddDuckyXAdobed  Yc  a!Q1qA"2Br#3R$tu6b457cs%!1AQaq ?Wl)l)l)l)l)l)l)l)l)l)l)l)l)l)l)l)l)l)l)l)l)l)l)l)l)l)l`:YdhMLLn9Tg>EAo{^ø!`eZݏ88y~*enfb ܬnǵoeo"]2+񠻝6Oi {$Cxbe"۱ꐼ|(-0w$}q, D\m80su,tA 8!M= З+bϲ;s)Z#&Ecc|lG iF4%CE# ]&:3cz>pbv wQ>GH$3a+CD5B?u#B9ҒM:,ionNzy'`%͓:Yڟ+%i*`0d.ײeoC (O[tc^jUfўf 4tZ:F립#C⨿Ն2 ks.*kq6Bg3taˎ5(aݗ/t wLn8kꠇv.! 6k Z杆y1b# {0cTr1} ͷ>3Ƭ$Ƀ)ۮ_báE$<ЙDOwl]S0B>*;VmtR7ɒ?T[vow iВ᧭ZtQf4h%AB7:Pw R R R R R R R R R R R R R R R R R R R R R R R R R R R R R R R R R R R R R R R R R R R R R R R R Q@E (P(Q@E (P(Q@E (P(Q@GRv=_ ^zyQ#GƪPun4xyYIX˾韲zӫu6ݣ]{sjMRas I^9P|1 <A]_̓ LJd|:2-w u# m#RY nle"Ǿ?#Cq>#O$bۼIa/#4|0BYbY{׈{y9̡ ɑW#TTAqa!tP-$ODWퟃMa5^+]!HOJ6pZyyBn3|"թcBbe_G"ѥ˄>]#ѰkBWJwDdcӛxvt/d63** GF/?,7$PƖʊY[1kâǽQ.vs#OAe3)ᰴaVΧ|@\J-B=P>a}>@E (P(Q@E (P(Q@E (P(Q@E (P(Q@E (P(Q@E (P(( !@( !@( !@( !@( !@( !@( !A598" (~KZ$hAc.pk Q{&X>!2'8H4#w:{k7~8џpe{~XGI` x>B'BG$@GTRa3kZj#l#xl8&n23/k924tS A}N{fCHng|IɴetrGFu:Ag52鰰ٮ$9ah hsX8bZKE 8v^ǭ@:䂵t,2ݱnSk;Ds~u$NL]r. )@ђ C$|]<°[lEԦ~wɆ>V'q<v:8m52\4xgUi-a3@cdcF駙g=ٽ?]$m䱹+# 4<|fܢ@wc6DZ:-.kNQ,zmldw$Lu05eh? :9\a|n)['S\4sLr0VkIݛO+eth5 3^ctf0鿲/ P)lPy{qw̼m8 uj[ us:{8ݒ\[L66N:ߪz 簖W&o)x ɣtofYLOw &(Gd ; Qv@(Gd ; Qv@(Gd ; Qv@(Gd ; Q:崎xcƤ{ ķ22SgvA,cϣh,z5өrAZn1һ L3'H<0~aF18pu Ѥ!h=J/TvP(Gd^DDl8H:5iGj`c2٧]J&$4yq$R.ֶmt_{ <3[()_SmZHن"y!v=9nU4C)vF~niZ֗COVϧr#1XˉVV+'H fN%(>d,H;\V h  v= Il^֖ۮc+. LKKk.̾%$\SKz;<6:(,FH?x _1pKwGG4v@(Gd ; Qv@(Gd ; Qv@(Gd ; Qv@(Gd ; Qv@(Gd ; Qv@(Gd ; Q-KbKbKbKbKbKbKbKbKbKbKbKbKbKbKbKbKbKbKbKbKbKbKbKbKbKbKbKbKbKb͗1:'4 ^qU]kp2A~AKbZ:9C#y&htI4 c-gVR.G4ԟ&6.cB쥱Au-wr{kv3kG(5j_[nZ7t\nt8Sm]AW?'ᦊ̳3tt8:<4G%oq8n$:8?Iyy'udlS'm6Z[&|tZVd7_%-&1B_›\t5mpdñ?0gzz$k[lyl7qJۻ fZhaԽޡ̐} U#i83ť0NZ-t/-av)m},kK{84DCuܗYo\7]mwhH-wKii ^V E<&wtp׃`KC}w~WVk@=8,ָjH gbk,ݜLz:w :hRب((((( { W{l#Fţ}BtWxcm;uzCc/OXT>ên#B?!'2lP)lP)lP)lP)lP)lP)lP)lP)lP)lP)lP)lP)lP)lP)lP)lP)lP)lP)lP)lP)lP)lP)lP)lP)lP)lP)lP)lP)lP)lP)lP)lP)lP)lP)lP)lP)lP)lP)lP)lP)lP)lP)lP)lP)lP)lP)lPI@E (P(Q@E (P(Q@E (P(Q@E (P(źDz屝ilw86y#+.'T (1 zPd(B/S]:W /|ّa㈏BEze{-ghˉ&6{WGh'U+g1ݥ0~l2vși|tIrw>.7L>@5i|Uo2=ml>)kO]Ed(Q@E (#h-bp)\j8ﳈU09^jWlH]d xj Vg>]mt؟$P(Q@E (P(Q@E (P(Q@E (P(Q@E (P(Q@E (P(Q@E JGE))))))))))))))))`X4F[R5%EO޸uc|x>Q :Y@dA/Tzi4DPrȳ1C]ܙF;gL$8Bf#kLe% z75sq̩QCE]ǖk-la`Ź$qqk ~#U{t8ՖCc+W6ats17Gxy)prg;&np1|m1Mqd/2G@?r {mclfk <j(_Krxt}؞'ncvMVFs8 袚[5:߀xP~!_#d~'R9YӵY$# R># R># 蹲mռj+H.`(4nb.Hp$G nIlnD.d_mz4:fsG܂BJG@| G@| G@| G@| G@| G@| G@| G@| G@| G@| G@| G@| G@| G@| G@| G@| G@| G@| G@| G@| G@| G@| GA)G@GD >}( Q@GD >}( Q@GD >}( Q@GD >}( Q@̟Y{6<}m$ozG=H$kXM)xWj96{wUm[2rR[f\Dp~9S<dD;;cs[{_î|j`p+]܏&s|qv.ô[{7PIm ]q@-*k Yf]YnǧIPt; VIveC뼍YdėޗxooY Ƴ]iY6 GkYw^ӺձJ^u -C백9'qV&; / 'YgR&xia{k,L|eu`xK~6-Ǹǐ͉isA$cРYYdmwau崟'PGvYwpd?v2_#[=NV.ڌ.<\x|V?ErR짛4vIGF7]`?ܷl]ŀ"-&&28,}RD >}( Q@&XimE;> Xj*2bd%d"Jx9ڙ{cҨВN:]P|{.`]Z;MD >}( Q@GD >}( Q@GD >}( Q@GD >}( Q@GD >}( Q@GD >}( QA'HHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHH`{uC.zC0Cw/Ӌn/d7v3CqglBX ziׇܻ5ܽ3+?k$֢#:[o65\y^tjHgGؾu'WsptHoH:uO;3ocNk\FR| Gd\yPyK\vatd/xs:(ȭFYE9٥G=1͜qqy!~Ǵ<=d|cڴ[8f"ݷxx݊ž6{YM{7OYusw /?غ&9ͷ-ϼkҞFݱ=\JFI.{@t:u+8<}Pcq}6lG, a:rZ"+kg9سۮ׫Fj@;oGe)))))))t%8PcXHo>j#K_-vFZ[>FxI:Xn~V^,<fCBCy t7Cy t7Cy t7Cy t7Cy t7Cy t7Cy t7Cy t7Cy t7Cy t7Cy t7Cy t7Cy t7Cy t7Cy t7Cy t7Cy t7Cy ·dv:ӫi,6z]{o5y8;#N ok!Ksc:%$[oe -PqP5[P^v g}wUC$Wkض-> Llri0h0kؽ6VA{Ѡs{AY켆~Kߝ'*KojO=BojY}76X4#:Fߚ֍Ug` =b夓t=a`hxvo\d`1xc% s27-};'H H H H .G2%w2#O@uA?/*(7)O6(3D`v7J%PKB41!pylons/media/img/hatch-yellow.pngPNG  IHDRJ"+tEXtCreation TimeWed 2 Mar 2005 01:35:41 -0000Ja5tIME +_ pHYs B4gAMA aIDATxc0`b ,0H]KXIENDB`PKB4h3pylons/media/img/header.pngPNG  IHDRM+tEXtCreation TimeMon 9 May 2005 22:40:47 -0000?tIME+ pHYs B4gAMA a.IDATxc bb`` # /$$0!@jIENDB`PKB4?Apylons/media/img/highlight.pngPNG  IHDRJ"+tEXtCreation TimeSat 5 Feb 2005 02:45:25 -0000LCCtIME (b pHYs B4gAMA aIDATxc0`b ,0H]KXIENDB`PKB4tQt77pylons/media/img/icon-16.pngPNG  IHDRh6,tEXtCreation TimeFri 28 Oct 2005 14:54:36 -0000[tIME | pHYs B4gAMA aIDATxc`w^CCCTWWWǎ#h$E@x8wQN^tQغu+a0񓓓1 )) }0J ]ÇHIDyJY̞IENDB`PKB4H-%%pylons/media/img/logo.gifGIF89a4990 LLIeebzzJ{{z~~|NooErrH~墢333rrq,,(HHE??>``>fff]]APP:{{JttrWԨZ`QWnnmX"" vvGMM7T==<⒒QPPNiiAkkiEECbb?TTQBB6))&ppn[[>II9NNKeeB**'$$"[VV?fEE:R//,;;1M\00/``]GGDXX>9??;772@@;==922/..*YN00-~~I;;6??://+~~J::5XY_Ḹ_99444/c885>>:UçZK^KJNOTwwHZZ=33.::7ؓRǬllk[[?WW@WXX@ҥS@@5yyx11,ἼWW;b[Ѩ22-AA>!K,4H.9` NJHŋ3jL!*lIɓ;:ʗ0cʬV//3sif < 'PH4ӓLJj1*ի px`!4l]t6ZZXf%ǂRm fc' .j-|șFLHpB)eB$$8tg6 =13{l, wv2VLF%xxd1ct^HQgc^2H%q"qL#9gdx U|qyi y$@-؋! o66F"!wՂ*q p}-BG(Ap ,1lJ9 qDGTI.GZ Ԣ"KfPzd 8'&g]8BE'xD A  pژ !vpbGtJ/&E)!5 V"NZiZHk8Epgar&i&An gWX[p q@*@B ʊV d-U#Gi"z†\r*i nh&AF_}#yt&*nl-Jo*o#,3 o tXj<ٸa(/GڌyJ/aGP|PDf wΗ@Dе`f,,KVE7]p$6!Hޔhvƃ5{-:lPK ͺK:BsCScR 0 fDIGt$0oyt$m-eg9k!dLtA =2q" `)c]>A~7 *s)jD"Ab%@"kX+qj+lBIǛ <ؤ xE) tA[Dφ$!z\Y'ZMep趴:1"3ۃA,R\ "q78ac8= ݚXD7*dC#y"B5 0\jx%; Z4cS+*)!d*8IKъ3;X!rՁ3f.wi͕YhiH&YDt3q "Јt0`A 2ΔAl9R<8!A0WXlDH8Z!g& 6b!ZJF$H=R,X"Z4]B,ކ!Ǖq0-MEB9SG6*Q`bf5\dn в vӈW!RX.$ @jD"rp]|D@^DiD$aDxq$6 #a\1T8 %KjI%E,H8&B6\{ oĈH [,B2E\\Axib]-!x#fA1R`gG>qf)Q+1>Vʬ)0H>'D$. JH&@(<@%T@QJ8Z ƅ `Z1F4\mDD@{D @n @@$:G(D !msD!1qGKC!Qm<1(Da튐~ɽmM<"HD)I f'B8a("`x V@ ht!B"E!0B`!FnSB _BBty"Ns0!0l".Mj $ 6 !Lp BD &Qo4<E * MB!PB! B!0bh(D E lC! Ki0ʻQ(A6"dH!R (__X"+B$0AiE]Ri D@`E LQR@,D C~Ly$2r P,ZJ$!t K_7 xP= xo ~YP`~z ~>7rN)@ ܷx )pڲinWs- T 1 '` H6| & %P'Gr` zrn)PrwS&3}pY ~"r7 .7r ~ wX b` z1 F2Pg 'P`@ C@P nP P@ P-Ljz xy}ϗ zP py؄X gT yf0w}vϷiP70 Ө Yp W P}p0 iq ɀp gȋ7ЊhX.sI I3 NEf8P 0 ַZcvɒ`B}DY@,dOI@UIO"6 D.)0 gP da` 0 q P p0Kp z9 iy {9 vYp L 0 `I99 i|(p Gp iƩyI ͙‰^sigy;PKB4,#pylons/media/img/main-nav-bg-on.pngPNG  IHDRUh?,tEXtCreation TimeFri 21 Oct 2005 03:03:42 -0000_2tIME \i] pHYs B4gAMA a$IDATxcdbFFF&2iBllvc\4|4/IENDB`PKB4A pylons/media/img/main-nav-bg.pngPNG  IHDRUh?,tEXtCreation TimeFri 21 Oct 2005 03:03:42 -0000_2tIME 4/̗ pHYs B4gAMA aKIDATxcqT2` iAf@iĘ.!ы)HU fߵ PǏfTIENDB`PKB4#>iipylons/media/img/plus.jpgJFIFC    $.' ",#(7),01444'9=82<.342C  2!!22222222222222222222222222222222222222222222222222 "#"#4Ts! ?gnIe=%iȑ>󧼎n.sU1}\p7?/Z2Y?PKB4Cpylons/media/img/tab-brown.pngPNG  IHDR,^\,tEXtCreation TimeThu 20 Oct 2005 13:22:14 -0000 9tIME=b+ pHYs B4gAMA a[IDATxA @@Q 8 HV A.a;<4noXz>cNcD1BL!D1BL!D1BL!D1BL!D1BL˲3Ԇ56*M1b^@l݄07b"(lBb !&BD%_Q@qbC'b"!&Bb"!&Bb"!&Bb"!&Bb"!&Bb"!&Bb"!&Bb"!&Bb"!&Bb"!&Bb"!&Bb"!&Bb"K4}MsIENDB`PKB4ǘpylons/media/img/tab-white.pngPNG  IHDR,^\,tEXtCreation TimeThu 20 Oct 2005 13:22:14 -0000 9tIME':% pHYs B4gAMA a9,tEXtCreation TimeThu 20 Oct 2005 13:22:14 -0000 9tIME 6 pHYs B4gAMA aPLTEB9BJRRRZZZZccckk!ckssJ{{քքք֌ބބJޜ!!!!!!)c) tRNSYjAIDATxJBQ@.L#V?\ &sf]'ðّjziZڱ~ղIcMXeylg,`ƪ{Lcuoz\xcG=><:cˋZ~4Vه7!iVՊ=ʶX[̎]4VM%iInqc 0`,Xc 0`,Xc 0`,Xc 0`,Xc 0`,Xc 0`,Xc 0`,Xc!qwg(rIENDB`PKB4^Й7CCpylons/media/img/tab-yellow.pngPNG  IHDR,^\,tEXtCreation TimeThu 20 Oct 2005 13:22:14 -0000 9tIME*va; pHYs B4gAMA aIDATx1N0܏p $$fԉVο*qb//'|^^พs=cǀ!D1BL!D1BL!D1BL!D1BL!D1Blݶk=,!*B BXO"df dY"z BE`9̌ ̈zfqY?`'d m@!oz7ဝY,Be=wB3,Gz~ĉD1BL!D1BL!D1BL!D1BL!D1BL!D1BL!D1BL!D1BL!D1BL!D1BL!D1BL!D1BL!DNDIENDB`PKB4SOpylons/media/img/warning.gifGIF89a!!ZZsk{s{Ƶν޽B޽J޽R޽ZJZckBBJJRks{ΌJ{֌֔ޥޭJJR֔ޔޜޥJJRJ1J!1B)19BJ!,H A**\ J!B'bXDH! &Jx# 'ryFhbC"@BXY1b I!BE0Ҡ )> "B 40ac̞TH0"?vѐRaɠ?PPcC$5HpX   @p6!k3THB .8тo$F_1B8-;PKB4;,#,#pylons/media/style/orange.cssbody{ margin: 0px; padding: 0px;/* 4% 0 0;*/ background: #494943 url(../img/bg.jpg) top repeat-x; font-family: Verdana, Arial, sans-serif; font-size: 75%; line-height: 160%; color: #333; /*min-width:770px; max-width: 1100px;*/ } /* Layout Styles */ /*.top-bar{background: #fff url(../img/bar.png) right top no-repeat;} */ div.main-content-bg{ } div.main-content-bar{ } div#nav-bar{ border-top: 1px solid #fff; float: left; width: 100%; margin-top: 16px; background: #fff url(../img/bar-bg.png) right top repeat-x; } div#main-content{ float: left; width: 100%; background: #fff; } div#side-content{ /*background: #FFf url(../img/bar.png) top right no-repeat;*/ padding-top: 42px; float: left; margin-top: 0px; width: 30%; clear: right; height: 550px; } div.three, div.two, div.one{ width: 746px; padding: 0 12px 0px 12px; clear: both; } div.three div.a, div.two div.a{ float: left; clear: left; width: 204px; /*background-color: #ddd;*/ } div.a div.padding, div.b div.padding, div.c div.padding, div.one div.padding{ padding: 0px 12px 20px 12px; } div.three div.b{ float: left; width: 271px; /*background-color: #ccc;*/ } div.three div.c{ float: left; clear: right; width: 271px; /*background-color: #bbb;*/ } div.two div.b{ float: left; clear: right; width: 542px; /* background-color: #333;*/ } /* Logo */ h1#logo{ margin: 20px 5% 0 5%; padding: 0; float: left; width: 155px; height: 52px; /*padding: 25px 5% 0 5%; margin: 0 0 0 -2px; float: left;*/ } /* Nav Bar */ #nav-global { margin:0; white-space:nowrap; float: right; /*position: absolute; margin:0; left:380px; top: 0px;*/ padding-right: 5%; clear: right; padding-bottom: 20px; } #nav-global li { display:block; float:left; list-style-type:none; margin:0; padding:0; } #nav-global a { display:block; float:left; /*font-family:"Trebuchet MS"; font-size: 110%; */ padding:42px 18px 7px 18px; background:#000000; color: #ccc; border: 0px; text-decoration: underline; } #nav-global a:hover { color:white; background: url(../img/main-nav-bg-on.png) bottom repeat-x; border: 0px; } #homepage #nav-homepage a, #overview #nav-overview a, #download #nav-download a, #documentation #nav-documentation a, #weblog #nav-weblog a, #community #nav-community a, #code #nav-code a { color:white; background:#000 url(../img/main-nav-bg.png) bottom repeat-x; } ul#navlist { /*background: url(../img/bar.png) left top no-repeat;*/ margin: 0; padding:0; padding-left: 5%; padding-top: 8px; color: #eee; line-height: 34px; } ul#navlist li { display: inline; } ul#navlist li a { /*font-family: Tahoma, sans-serif; font-size: 11px;font-weight: bold;*/ border: 0px; border-left: 1px solid #49A200; /*padding: 0em 1em;*/ padding: 0 18px 0 18px; color: #fff; margin-right: 9px; text-decoration: none; float: left; background: url('../img/tab-brown.png') no-repeat top right; } ul#navlist li a#highlight , ul#navlist li a#highlight:hover { background: url('../img/tab-yellow-highlight.png') no-repeat top right; color: #fff; padding-right: 33px; } ul#navlist li a:hover { background: url('../img/tab-yellow.png') no-repeat top right; color: #fff; } ul#navlist li.active a.active, ul#main-nav li.active a.active:hover { background: url('../img/tab-white.png') no-repeat top left; color: #333; } /* Font Styles */ a, a:link, a:visited, a:active { color: #0040BB; text-decoration: none; border-bottom: 1px dotted #ccc; } a:hover{ color: #000; border-bottom: 1px dotted #000; } a.no-underline, a.no-underline:link, a.no-underline:visited, a.no-underline:active { border: 0px; } img.no-border{ border: 0px; } /* Paragraph Styles */ .last{ padding-bottom: 0px; margin-bottom: 0px; } .first{ margin-top: 0px; } blockquote { padding-left: 10px; padding-right: 10px; margin-left: 5px; margin-right: 0; border-left: #ddd; border-width: 0 0 0 1px; border-style: none none none solid; } p.first, form{ padding: 0px; margin: 0px; } .medium{ font-family: Verdana, Geneva, Arial, sans-serif; font-size: 11px; line-height: 19px; } .large{ font-size: 110%; } .small{ font-size: 90%; line-height: 150%; font-family: Verdana, sans-serif; color: #000; } p.indent{ padding-left: 15px; padding-bottom: 15px; } tt, code{ font-size: 130%; color: #800000; } pre{ /* border-top: 1px dotted #000; border-left: 1px dotted #000; border-right: 1px solid #999; border-bottom: 1px solid #999; background: #eee;*/ font-size: 120%; padding: 3px 5px 3px 10px; margin-right: 10px; } .go{ background: url(../img/go.png) no-repeat right bottom; padding-right: 20px; } .help, a.help{ cursor: help; font-weight: normal; } .highlight{ background: #ffffcc url(../img/highlight.png) repeat; } /* Horizontal Rule */ div.hr { clear: both; line-height: 0px; font-size: 0px; margin: 0px; padding: 0px; /*height: 4px; url(../img/horizontal-rule.png) no-repeat;background: #000; margin-bottom: 20px; width: 770px;*/ } hr { height: 1em; visibility: hidden; margin: 0px; padding: 0px; } /* Form Styles */ .form-style input[type=submit]{ background: #87CD15; color: #fff; border-top: 1px solid #999; border-left: 1px solid #999; border-bottom: 1px solid #333; border-right: 1px solid #333; } .form-style input[type=text], textarea, input[type=file]{ font-family: Tahoma, sans-serif; font-size: 11px; color: #444; background: #EAFEC2; border: solid 1px #aaa; padding: 3px; } .form-style select{ font-family: Tahoma, sans-serif; font-size: 11px; color: #444; background: #EAFEC2; border: solid 1px #aaa; } /* Lists */ ul.large{ padding: 0 0 0 15px; margin: 0 0 15px 0px; } ul.large li a { font-weight: normal; } /* Header Styles */ h1.first{ margin-top: 0px; border-bottom: 1px solid #666; background: #fFF; padding: 3px; } h1, h2, h3 { font-size: 170%; line-height: normal; font-weight: normal; font-family: Arial, sans-serif; color: #000000; text-decoration: none; /*margin: 0 0 12px 0; padding: 0;*/ text-align: left; } h2{ font-size: 140%; } h3 { font-size: 120%; } h4{ font-size: 100%; } h4.asterix{ background: url(../img/box-small.png) no-repeat left center; padding: 0px 0px 0px 15px; margin: 0px; /*font-size: 110%; */ color: #000000; } /* Boxes */ div.faq-box{ /*border-style: solid; border-color: #C6F27A; border-width: 1px;*/ background:url('../img/hatch-green.png'); padding: 10px; /*font-family: Verdana, Geneva, Arial, sans-serif; font-size: 11px; line-height: 17px;*/ } div.highlight-box{ border-style: solid; border-color: #cccccc; border-width: 1px; background:url('../img/hatch-yellow.png'); padding: 10px; color: #555; /*font-family: Verdana, Geneva, Arial, sans-serif; font-size: 11px; line-height: 17px;*/ } .box-top{ width: 518px; background: url(../img/box-top.png) no-repeat left top; padding-top: 7px; margin-bottom: 15px; } .box-middle{ background: url(../img/box-middle.png) repeat-y left top; } .box-bottom{ background: url(../img/box-bottom.png) no-repeat left bottom; padding: 0 10px 11px 12px; } /* Utility Styles */ .content-padding{ padding: 20px 6.5% 40px 6.5%; } .sidebar-padding{ padding: 15px 15px 40px 25px; } .invisible{ visibility: hidden; font-size: 1px; padding: 0px; line-height: 0px; margin: 0px; } a.no-underline{ border: 0px; } img.no-border{ border: 0px; } br.clear{ clear: both; width: 100%; } /* Quotes */ .quote-top p{ padding: 0px; margin: 0px; } .quote-top{ font-family: tahoma; /*background: url(../img/quote-top.png) no-repeat left top;*/ padding-left: 25px; padding-top: 4px; } .quote-bottom{ /*background: url(../img/quote-bottom.png) no-repeat right bottom;*/ padding-right: 17px; padding-bottom: 7px; } .quote-author{ background: url(../img/quote-author.png) no-repeat left top; padding-left: 20px; padding-bottom: 20px; } /* Footer Styles */ #footer{padding: 5px 5% 40px 5%;} #footer p{ color: #333; } #footer a{ font-weight: normal; } #footer a:visited{ color: #666; text-decoration: none; border-bottom: 1px dotted; } #footer a{ color: #888; font-weight: normal; } #footer a:hover{ color: #000; text-decoration: none; border-bottom: 1px dotted; } PKB4pylons/templates/__init__.pyPKI4pylons/templates/__init__.pyc; qDc@sdS(N((((sIbuild/bdist.darwin-8.6.0-Power_Macintosh/egg/pylons/templates/__init__.pys?sPKB4?tdrr#pylons/templates/controller.py_tmplfrom ${base_package}.lib.base import * class ${name}Controller(BaseController): def index(self): passPKB4 "(pylons/templates/test_controller.py_tmplfrom ${base_package}.tests import * class Test${name}Controller(TestController): def test_index(self): response = self.app.get(url_for(controller='${fname}')) # Test response...PKe4[85pylons/templates/paster_template/development.ini_tmpl[DEFAULT] debug = true email_to = you@yourdomain.com smtp_server = localhost error_email_from = paste@exceptions.com [server:main] use = egg:PasteScript#wsgiutils host = 0.0.0.0 port = 5000 [app:main] use = egg:${package} cache_dir = %(here)s/cache session_key = ${package} session_secret = somesecret # If you are using SQLObject you will need to specify a # dburi. You can do this with a line similar to the # one below but adjusted for your database connection # according to the SQLObject documentation. The %(here)s # part is replaced with the current directory which is # useful when using sqlite on UNIX based platforms. # For Windows you should look at the SQLObject # documentation for a special syntax to use because the # path returned by %(here)s contains a : character. #sqlobject.dburi = sqlite:%(here)s/somedb.db # Do not set debug to true or uncomment the line below # on a production environment otherwise in the event of # an error occurring the visitor will be presented with # interactive debugging tools and these could be used to # execute malicious code. # For development purposes debug should be set to true # to enable the debugging code but be sure to set it back # to false before releasing your application. #set debug = false PKe4w30pylons/templates/paster_template/README.txt_tmplThis file is for you to describe the ${package} application. Typically you would include information such as the information below: Installation and Setup ====================== Install ``${package}`` using easy_install:: easy_install ${package} Make a config file as follows:: paster make-config ${package} config.ini Tweak the config file as appropriate and then setup the applicaiton:: paster setup-app config.ini Then you are ready to go.PKB4_߈/pylons/templates/paster_template/setup.cfg_tmpl[egg_info] tag_build = dev tag_svn_revision = true [pudge] theme = pythonpaste.org # Add extra doc files here with spaces between them docs = ${package}/docs/index.txt # Doc Settings doc_base = ${package}/docs/ dest = ${package}/docs/html # Add extra modules here separated with commas modules = ${package} title = ${package.capitalize()} organization = Pylons # Optionally add extra links #organization_url = http://pylons.groovie.org/ #trac_url=http://pylons.groovie.org/ settings = no_about=true # Optionally add extra settings # link1=/community/ Community # link2=/download/ Download [publish] doc-dir=${package}/docs/html make-dirs=1 PK4H.pylons/templates/paster_template/setup.py_tmplfrom setuptools import setup, find_packages setup( name=${repr(project)|empty}, version=${repr(version)|empty}, #description="", #author="", #author_email="", #url="", install_requires=["Pylons>=0.8.2"], packages=find_packages(), include_package_data=True, test_suite = 'nose.collector', package_data={'${package}': ['i18n/*/LC_MESSAGES/*.mo']}, entry_points=""" [paste.app_factory] main=${package}:make_app [paste.app_install] main=paste.script.appinstall:Installer """, )PKB4OZ;pylons/templates/paster_template/+package+/__init__.py_tmpl""" ${package} This file loads the finished app from ${package}.config.middleware. """ from ${package}.config.middleware import make_app PKB41UsD}};pylons/templates/paster_template/+package+/websetup.py_tmpldef setup_config(command, filename, section, vars): """ Place any commands to setup ${package} here. """ passPKB4j'jj?pylons/templates/paster_template/+package+/components/empty.myt<%doc> # Feel free to remove this, its here purely to ensure the components directory is created PKB4Bpylons/templates/paster_template/+package+/config/__init__.py_tmpl# PK Z4b<Epylons/templates/paster_template/+package+/config/environment.py_tmplimport sys, os import pylons.config from ${package}.config.routing import make_map def load_environment(): map = make_map() # Setup our paths root_path = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) paths = {'root_path': root_path, 'controllers': os.path.join(root_path, 'controllers'), 'templates': [os.path.join(root_path, path) for path in \ ('components', 'templates')], 'static_files': os.path.join(root_path, 'public') } sys.path.append(os.path.join(root_path, 'lib')) # The following options are passed directly into Myghty, so all configuration options # available to the Myghty handler are available for your use here myghty = {} myghty['log_errors'] = True # Add your own Myghty config options here, note that all config options will override # any Pylons config options # Return our loaded config object return pylons.config.Config(myghty, map, paths) PKB4S^ xxDpylons/templates/paster_template/+package+/config/middleware.py_tmplfrom paste import httpexceptions from paste.cascade import Cascade from paste.urlparser import StaticURLParser from pylons.error import error_template from pylons.middleware import ErrorHandler, ErrorDocuments, error_mapper import pylons.wsgiapp from ${package}.config.environment import load_environment def make_app(global_conf, **app_conf): """ Create a WSGI application and return it global_conf is a dict representing the Paste configuration options, the paste.deploy.converters should be used when parsing Paste config options to ensure they're treated properly. """ # Load our Pylons configuration defaults config = load_environment() config.init_app(global_conf, app_conf, package='${package}') # Load our default Pylons WSGI app and make g available app = pylons.wsgiapp.make_app(config) g = app.globals # YOUR MIDDLEWARE # Put your own middleware here, so that any problems are caught by the error # handling middleware underneath # @@@ Change HTTPExceptions to HTTP responses @@@ app = httpexceptions.make_middleware(app, global_conf) # @@@ Error Handling @@@ app = ErrorHandler(app, global_conf, error_template=error_template, **config.errorware) # @@@ Static Files in public directory @@@ staticapp = StaticURLParser(config.paths['static_files']) # @@@ Cascade @@@ app = Cascade([staticapp, app]) # @@@ Display error documents for 401, 403, 404 status codes (if debug is False also intercepts 500) @@@ app = ErrorDocuments(app, global_conf, mapper=error_mapper, **app_conf) return app PKe4+2eeApylons/templates/paster_template/+package+/config/routing.py_tmpl""" Setup your Routes options here """ import sys, os from routes.base import Mapper def make_map(): root_path = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) map = Mapper(directory=os.path.join(root_path, 'controllers')) # Define your routes. The more specific and detailed routes should be defined first, # so they may take precedent over the more generic routes. For more information, refer # to the routes manual @ http://routes.groovie.org/docs/ map.connect(':controller/:action/:id') map.connect('*url', controller='template', action='view') return map PKB4Gpylons/templates/paster_template/+package+/controllers/__init__.py_tmplPKB4P)**Dpylons/templates/paster_template/+package+/controllers/error.py_tmplfrom ${package}.lib.base import * from paste import fileapp from pylons.middleware import media_path, error_document_template, run_wsgi import os.path from pylons.util import get_prefix class ErrorController(BaseController): """ Class to generate error documents as and when they are required. This behaviour of this class can be altered by changing the parameters to the ErrorDocuments middleware in your config/middleware.py file. """ def document(self): """ Change this method to change how error documents are displayed """ page = error_document_template % { 'prefix':get_prefix(request.environ), 'code':params.get('code', ''), 'message':params.get('message', ''), } m.write(page) def img(self, id): self._serve_file(os.path.join(media_path, 'img', id)) def style(self, id): self._serve_file(os.path.join(media_path, 'style', id)) def _serve_file(self, path): run_wsgi(fileapp.FileApp(path), m, request)PKB4[Gpylons/templates/paster_template/+package+/controllers/template.py_tmplfrom ${package}.lib.base import * class TemplateController(BaseController): def view(self, url): """ This is the last place which is tried during a request to try to find a file to serve. It could be used for example to display a template:: def view(self, url): from pkg_resources import resource_exists if resource_exists('${package}', url+'.myt'): m.subexec(url+'.myt') else: m.abort(404, "File not found") The default is just to abort the request with a 404 File not found status message. """ m.abort(404, "File not found")PKB4cOjAA>pylons/templates/paster_template/+package+/docs/index.txt_tmpl${package} ${len(package)*'+'} This is the main index page of your documentation. It should be written in reStructuredText format. You can generate your documentation in HTML format by running this command:: setup.py pudge For this to work you will need to download and install ``buildutils`` and ``pudge``. PKB4@pylons/templates/paster_template/+package+/i18n/__init__.py_tmplPKB4?pylons/templates/paster_template/+package+/lib/__init__.py_tmplPKB4cBpylons/templates/paster_template/+package+/lib/app_globals.py_tmplimport pylons.middleware class Globals(pylons.middleware.Globals): def __init__(self, global_conf, app_conf, **extra): """ You can put any objects which need to be initialised only once here as class attributes and they will be available as globals everywhere in your application and will be intialised only once, not on every request. ``global_conf`` The same as variable used throughout ``config/middleware.py`` namely, the variables from the ``[DEFAULT]`` section of the configuration file. ``app_conf`` The same as the ``kw`` dictionary used throughout ``config/middleware.py`` namely, the variables the section in the config file for your application. ``extra`` The configuration returned from ``load_config`` in ``config/middleware.py`` which may be of use in the setup of your global variables. """ pass def __del__(self): """ Put any cleanup code to be run when the application finally exits here. """ pass PKB45i;pylons/templates/paster_template/+package+/lib/base.py_tmplfrom pylons import Controller, m, h, c, g, session, request, params import ${package}.models as model class BaseController(Controller): def __call__(self, action, **params): # Insert any code to be run per request here Controller.__call__(self, action, **params)PKB4=MD>pylons/templates/paster_template/+package+/lib/helpers.py_tmpl""" Helper functions All names available in this module will be available under the Pylons h object. """ from webhelpers import * PKB44[[Bpylons/templates/paster_template/+package+/models/__init__.py_tmpl## NOTE ## If you plan on using SQLObject, the following should be un-commented and provides ## a starting point for setting up your schema #from sqlobject import * #from pylons.database import PackageHub #hub = PackageHub("${package}") #__connection__ = hub # You should then import your SQLObject classes # from myclass import MyDataClass PKB4uuApylons/templates/paster_template/+package+/public/index.html_tmpl Pylons Default Page

Welcome to your Pylons Web Application

Weren't expecting to see this page?

The ${package}/public/ directory is searched for static files before your controllers are run. Remove this file (${package}/public/index.html) and edit the routes in ${package}/config/routing.py like so:

 map.connect('', controller='hello', action='index')

Getting Started

You're now ready to start creating your own web application. Here's what a basic controller looks like to print out 'Hello World' and respond to http://localhost:5000/hello:

# ${package}/controllers/hello.py
# Note that the line above is the file you should create and put the following into...

from ${package}.lib.base import *

class HelloController(BaseController):
    def index(self):
        m.write('Hello World')
        

Using a template

If you want to call a template and do something a little more complex, here's an example printing out some request information from a Myghty template.

# ${package}/templates/serverinfo.myt

<p>Hi, here's the server environment: <br />
<% str(r.environ) %></p>

<p>
here's the URL you called: <% h.url_for() %>
</p>

<p>
and here's the name you set: <% c.name %>
</p>

Then add this to your hello controller class:
    def serverinfo(self):
        c.name = 'The Black Knight'
        m.subexec('/serverinfo.myt')
You can now view the page at: http://localhost:5000/hello/serverinfo

PKB4`@pylons/templates/paster_template/+package+/templates/autohandler% m.call_next()PKB4!XvOApylons/templates/paster_template/+package+/tests/__init__.py_tmplimport os, sys from unittest import TestCase here_dir = os.path.dirname(__file__) conf_dir = os.path.dirname(os.path.dirname(here_dir)) sys.path.insert(0, conf_dir) import pkg_resources pkg_resources.working_set.add_entry(conf_dir) pkg_resources.require('Paste') pkg_resources.require('PasteScript') from paste.deploy import loadapp import paste.fixture from ${package}.config.routing import * from pylons.myghtyroutes import RoutesResolver from routes import request_config, url_for class TestController(TestCase): def __init__(self, *args): wsgiapp = loadapp('config:development.ini', relative_to=conf_dir) self.app = paste.fixture.TestApp(wsgiapp) TestCase.__init__(self, *args) __all__ = ['url_for', 'TestController'] PKB4Dpylons/templates/paster_template/+package+/tests/test_models.py_tmplPKB4Lpylons/templates/paster_template/+package+/tests/functional/__init__.py_tmplPKe4֗@{{Upylons/templates/paster_template/+project+.egg-info/paste_deploy_config.ini_tmpl_tmpl[DEFAULT] debug = true email_to = you@yourdomain.com smtp_server = localhost error_email_from = paste@exceptions.com [server:main] use = egg:Paste#http host = 0.0.0.0 port = 5000 [app:main] use = egg:${package} cache_dir = %(here)s/cache app_instance_uuid = $${app_instance_uuid} session_key = ${package} session_secret = $${app_instance_secret} # If you are using SQLObject you will need to specify a # dburi. You can do this with a line similar to the # one below but adjusted for your database connection # according to the SQLObject documentation. The %(here)s # part is replaced with the current directory which is # useful when using sqlite on UNIX based platforms. # For Windows you should look at the SQLObject # documentation for a special syntax to use because the # path returned by %(here)s contains a : character. #sqlobject.dburi = sqlite:%(here)s/somedb.db # Do not set debug to true or uncomment the line below # on a production environment otherwise in the event of # an error occurring the visitor will be presented with # interactive debugging tools and these could be used to # execute malicious code. set debug = falsePKB4tests/__init__.py# PKI4gӎtests/__init__.pyc; qDc@sdS(N((((s>build/bdist.darwin-8.6.0-Power_Macintosh/egg/tests/__init__.pys?sPKB4?@tests/conftest.pyimport sys import os import shutil import pkg_resources here = os.path.dirname(__file__) base = os.path.dirname(here) sys.path.append(here) sys.path.insert(0, base) here = os.path.dirname(__file__) pkg_resources.working_set.add_entry(base) if not os.environ.get('PASTE_TESTING'): output_dir = os.path.join(here, 'test_webapps', 'output') if os.path.exists(output_dir): shutil.rmtree(output_dir) PKI4ûtests/conftest.pyc; qDc@sdkZdkZdkZdkZeiieZeiieZeii eeii deeiieZei i eei id o@eiieddZeiieoeieqndS(Nis PASTE_TESTINGs test_webappssoutput(ssyssossshutils pkg_resourcesspathsdirnames__file__sheresbasesappendsinserts working_sets add_entrysenvironsgetsjoins output_dirsexistssrmtree(s pkg_resourcessheressyssbases output_dirsshutilsos((s>build/bdist.darwin-8.6.0-Power_Macintosh/egg/tests/conftest.pys?s    PKB4tests/test_units/__init__.pyPKI4>ztests/test_units/__init__.pyc; qDc@sdS(N((((sIbuild/bdist.darwin-8.6.0-Power_Macintosh/egg/tests/test_units/__init__.pys?sPKH4'~iDDEGG-INFO/entry_points.txtPKﳼ4{EGG-INFO/not-zip-safePKH46p_EGG-INFO/PKG-INFOPKH4}>y9YYi EGG-INFO/requires.txtPKH4^QWW EGG-INFO/SOURCES.txtPKH4zm\ ~EGG-INFO/top_level.txtPKB4DFFpylons/__init__.pyPKI4M--5pylons/__init__.pycPK Z4[T T $pylons/commands.pyPKI4PP0pylons/commands.pycPK Z4  >pylons/config.pyPKI4Ypylons/config.pycPK Z4 MSqpylons/controllers.pyPKI4FP(P(pylons/controllers.pycPKB4Vlpylons/database.pyPKI4zpylons/database.pycPK Z4 QQpylons/error.pyPKI4o27 U U7pylons/error.pycPKe4LM2g ьpylons/helpers.pyPKI4ZNpylons/helpers.pycPKB4`T{ee]pylons/middleware.pyPKI4Jpylons/middleware.pycPKB40PKrf"f"8pylons/myghtyroutes.pyPKI4@F!.!.pylons/myghtyroutes.pycPKe4PM00(Apylons/util.pyPKI4.+JJOrpylons/util.pycPKB4Eaepylons/wsgiapp.pyPKI4òU #pylons/wsgiapp.pycPKB4Gii:pylons/media/img/plus.jpgPKB4C<pylons/media/img/tab-brown.pngPKB4ǘ>pylons/media/img/tab-white.pngPKB4XT)@pylons/media/img/tab-yellow-highlight.pngPKB4^Й7CCWFpylons/media/img/tab-yellow.pngPKB4SOHpylons/media/img/warning.gifPKB4;,#,#Mpylons/media/style/orange.cssPKB4xppylons/templates/__init__.pyPKI4ppylons/templates/__init__.pycPKB4?tdrr#qpylons/templates/controller.py_tmplPKB4 "(9rpylons/templates/test_controller.py_tmplPKe4[85Espylons/templates/paster_template/development.ini_tmplPKe4w30xpylons/templates/paster_template/README.txt_tmplPKB4_߈/zpylons/templates/paster_template/setup.cfg_tmplPK4H.}pylons/templates/paster_template/setup.py_tmplPKB4OZ;pylons/templates/paster_template/+package+/__init__.py_tmplPKB41UsD}};pylons/templates/paster_template/+package+/websetup.py_tmplPKB4j'jj?pylons/templates/paster_template/+package+/components/empty.mytPKB4Bpylons/templates/paster_template/+package+/config/__init__.py_tmplPK Z4b<Epylons/templates/paster_template/+package+/config/environment.py_tmplPKB4S^ xxDIpylons/templates/paster_template/+package+/config/middleware.py_tmplPKe4+2eeA#pylons/templates/paster_template/+package+/config/routing.py_tmplPKB4Gpylons/templates/paster_template/+package+/controllers/__init__.py_tmplPKB4P)**DLpylons/templates/paster_template/+package+/controllers/error.py_tmplPKB4[Gؕpylons/templates/paster_template/+package+/controllers/template.py_tmplPKB4cOjAA>pylons/templates/paster_template/+package+/docs/index.txt_tmplPKB4@pylons/templates/paster_template/+package+/i18n/__init__.py_tmplPKB4?pylons/templates/paster_template/+package+/lib/__init__.py_tmplPKB4cBWpylons/templates/paster_template/+package+/lib/app_globals.py_tmplPKB45i;wpylons/templates/paster_template/+package+/lib/base.py_tmplPKB4=MD>pylons/templates/paster_template/+package+/lib/helpers.py_tmplPKB44[[Bˢpylons/templates/paster_template/+package+/models/__init__.py_tmplPKB4uuApylons/templates/paster_template/+package+/public/index.html_tmplPKB4`@Zpylons/templates/paster_template/+package+/templates/autohandlerPKB4!XvOAǭpylons/templates/paster_template/+package+/tests/__init__.py_tmplPKB4Dpylons/templates/paster_template/+package+/tests/test_models.py_tmplPKB4Lpylons/templates/paster_template/+package+/tests/functional/__init__.py_tmplPKe4֗@{{Upylons/templates/paster_template/+project+.egg-info/paste_deploy_config.ini_tmpl_tmplPKB4׶tests/__init__.pyPKI4gӎtests/__init__.pycPKB4?@Ʒtests/conftest.pyPKI4ûtests/conftest.pycPKB4tests/test_units/__init__.pyPKI4>z޼tests/test_units/__init__.pycPK]]