PK42EGG-INFO/dependency_links.txt PK4sBٕEGG-INFO/entry_points.txt [paste.paster_command] controller=pylons.commands:ControllerCommand shell=pylons.commands:ShellCommand [paste.paster_create_template] pylons=pylons.util:PylonsTemplate [distutils.commands] lang_extract = pylons.i18n:LangExtract lang_compile = pylons.i18n:LangCompile [python.templating.engines] pylonsmyghty = pylons.templating:MyghtyTemplatePlugin PKQ4EGG-INFO/not-zip-safePK4+3 EGG-INFO/PKG-INFOMetadata-Version: 1.0 Name: Pylons Version: 0.9 Summary: Pylons Web Framework Home-page: http://www.pylonshq.com/ Author: Ben Bangert, James Gardner Author-email: ben@groovie.org License: UNKNOWN Description: Pylons ====== 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 0.9 described on this page is stable. There is also an unstable `develoment version `_ of Pylons. Download and Installation ------------------------- Pylons can be installed with `Easy Install `_ by typing:: > easy_install Pylons Dependant packages are automatically installed from the `Pylons download page `_ . 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 PK4'J%%EGG-INFO/requires.txtRoutes>=1.4 Myghty>=1.0.2 Paste>=0.9.6 PasteDeploy>=0.9.6 PasteScript>=0.9.6 FormEncode>=0.4 simplejson>=1.3 WSGIUtils==0.7 WebHelpers>=0.1.3 nose>=0.8.7 Beaker>=0.6 [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 [full] docutils>=0.4 elementtree>=1.2.6 pudge==dev,>=0.1.1dev buildutils==dev,>=0.1.2dev py>=0.8.0_alpha2 Cheetah>=1.0 TurboCheetah>=0.9.5 kid>=0.9 TurboKid==dev,>=0.9.1dev [kid] kid>=0.9 TurboKid==dev,>=0.9.1devPK43nnEGG-INFO/SOURCES.txtCHANGELOG LICENSE README.txt setup.cfg setup.py Pylons.egg-info/PKG-INFO Pylons.egg-info/SOURCES.txt Pylons.egg-info/dependency_links.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/flickrsearch.txt docs/getting_started.txt docs/index.txt docs/install.txt docs/interactive_debugger.txt docs/internationalization.txt docs/logging.txt docs/pylonsdev.txt docs/quick_wiki.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/wsgi_theory.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/decorator.py pylons/error.py pylons/helpers.py pylons/legacy.py pylons/middleware.py pylons/templating.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/+egg+.egg-info/paste_deploy_config.ini_tmpl_tmpl pylons/templates/paster_template/+package+/__init__.py_tmpl pylons/templates/paster_template/+package+/websetup.py_tmpl 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 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_sample.py tests/test_webapps/test_files/development.ini tests/test_webapps/test_files/functional_sample_controller_sample1.py tests/test_webapps/test_files/functional_sample_controller_sample2.py tests/test_webapps/test_files/functional_sample_controller_sample3.py tests/test_webapps/test_files/functional_sample_controller_sample4.py tests/test_webapps/test_files/middleware_def_engine.py tests/test_webapps/test_files/middleware_two_engines.py tests/test_webapps/test_files/test_myghty.myt tests/test_webapps/test_files/testkid.kid PK4zm\ EGG-INFO/top_level.txttests pylons PKL4>qpylons/__init__.py"""Base objects to be exported for use in Controllers""" from paste.registry import StackedObjectProxy from paste.wsgiwrappers import WSGIResponse as Response from pylons.controllers import Controller, RPCController from pylons.decorators import jsonify from pylons.util import Helpers from pylons.legacy import m, params c = StackedObjectProxy(name="C") g = StackedObjectProxy(name="G") cache = StackedObjectProxy(name="Cache") session = StackedObjectProxy(name="Session") request = StackedObjectProxy(name="Request") buffet = StackedObjectProxy(name="Buffet") h = Helpers(c=c, session=session, request=request, buffet=buffet) __all__ = ['Controller', 'RPCController', 'jsonify'] PK4`pylons/__init__.pyc; ,wDc @sdZdklZdklZdklZlZdk l Z dk l Z dk lZlZeddZedd Zedd Zedd Zedd Zedd Ze dedededeZdddgZdS(s2Base objects to be exported for use in Controllers(sStackedObjectProxy(s WSGIResponse(s Controllers RPCController(sjsonify(sHelpers(smsparamssnamesCsGsCachesSessionsRequestsBuffetscssessionsrequestsbuffets Controllers RPCControllersjsonifyN(s__doc__spaste.registrysStackedObjectProxyspaste.wsgiwrapperss WSGIResponsesResponsespylons.controllerss Controllers RPCControllerspylons.decoratorssjsonifys pylons.utilsHelperss pylons.legacysmsparamsscsgscachessessionsrequestsbuffetshs__all__(scscaches__all__sgsrequestsjsonifysmsbuffets ControllerssessionsHelperssparamss RPCControllersStackedObjectProxyshsResponse((s?build/bdist.darwin-7.9.0-Power_Macintosh/egg/pylons/__init__.pys?s    !PK\4pylons/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, shell """ import os import os.path import sys import glob from paste.script.command import Command, BadCommand from paste.script.filemaker import FileOp from paste.script import pluginlib, copydir from paste.deploy import loadapp, appconfig import paste.deploy.config import paste.fixture 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 = __doc__ 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) class ShellCommand(Command): """Open an interactive shell with the Pylons app loaded The optional CONFIG_FILE argument specifies the config file to use for the interactive shell. CONFIG_FILE defaults to 'development.ini'. This allows you to test your mapper, models, and simulate web requests using ``paste.fixture``. Example:: $ paster shell my-development.ini """ summary = __doc__ usage = '[CONFIG_FILE]' min_args = 0 max_args = 1 group_name = 'pylons' parser = Command.standard_parser(simulate=True) def command(self): if len(self.args) == 0: # Assume the .ini file is ./development.ini config_file = 'development.ini' if not os.path.isfile(config_file): raise BadCommand('%sError: CONFIG_FILE not found at: .%s%s\n' 'Please specify a CONFIG_FILE' % \ (self.parser.get_usage(), os.path.sep, config_file)) else: config_file = self.args[0] config_name = 'config:%s' % config_file here_dir = os.getcwd() locs = dict(__name__="pylons-admin") pkg_name = here_dir.split(os.path.sep)[-1].lower() # Load app config into paste.deploy to simulate request config app_conf = appconfig(config_name, relative_to=here_dir) conf = dict(app=app_conf, app_conf=app_conf) paste.deploy.config.CONFIG.push_thread_config(conf) # Load locals and populate with objects for use in shell sys.path.insert(0, here_dir) # Load the wsgi app first so that everything is initialized right wsgiapp = loadapp(config_name, relative_to=here_dir) # Start the rest of our imports now that the app is loaded routing_package = pkg_name + '.config.routing' models_package = pkg_name + '.models' helpers_package = pkg_name + '.lib.helpers' # Import all the modules for pack in [routing_package, models_package, helpers_package]: __import__(pack) make_map = getattr(sys.modules[routing_package], 'make_map') mapper = make_map() locs.update( dict( model=sys.modules[models_package], mapper=mapper, wsgiapp=wsgiapp, app=paste.fixture.TestApp(wsgiapp), h=sys.modules[helpers_package], ) ) banner = "Pylons Interactive Shell\nPython %s\n\n" % sys.version banner += "Additional Objects:\n" banner += " %-10s - %s\n" % ('mapper', 'Routes mapper object') banner += " %-10s - %s\n" % ('h', 'Helper object') banner += " %-10s - %s\n" % ('model', 'Models from models package') banner += " %-10s - %s\n" % ('wsgiapp', 'This projects WSGI App instance') banner += " %-10s - %s\n" % ('app', 'paste.fixture wrapped around wsgiapp') try: # try to use IPython if possible import IPython class CustomIPShell(IPython.iplib.InteractiveShell): def raw_input(self, *args, **kw): try: return IPython.iplib.InteractiveShell.raw_input(self, *args, **kw) except EOFError: # In the future, we'll put our own override as needed to save # models, TG style raise EOFError shell = IPython.Shell.IPShell(user_ns=locs, shell_class=CustomIPShell) shell.mainloop() except ImportError: import code class CustomShell(code.InteractiveConsole): def raw_input(self, *args, **kw): try: return code.InteractiveConsole.raw_input(self, *args, **kw) except EOFError: # In the future, we'll put our own override as needed to save # models, TG style raise EOFError shell = CustomShell(locals=locs) shell.interact(banner) PK4bMH0!0!pylons/commands.pyc; ;MDc@sdZdkZdkZdkZdkZdklZlZdkl Z dk l Z l Z dk lZlZdkZdkZdefdYZdefd YZdS( 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, shell N(sCommands BadCommand(sFileOp(s pluginlibscopydir(sloadapps appconfigsControllerCommandcBsftZdZeZdZdZdZdZei de Z e i ddddd 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 sCONTROLLER_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-7.9.0-Power_Macintosh/egg/pylons/commands.pyscommand8s, * U   (s__name__s __module__s__doc__ssummarysusagesmin_argssmax_argss group_namesCommandsstandard_parsersTruesparsers add_optionscommand(((s?build/bdist.darwin-7.9.0-Power_Macintosh/egg/pylons/commands.pysControllerCommands   s ShellCommandcBsGtZdZeZdZdZdZdZei de Z dZ RS(sOpen an interactive shell with the Pylons app loaded The optional CONFIG_FILE argument specifies the config file to use for the interactive shell. CONFIG_FILE defaults to 'development.ini'. This allows you to test your mapper, models, and simulate web requests using ``paste.fixture``. Example:: $ paster shell my-development.ini s [CONFIG_FILE]iispylonsssimulatec st|idjoJd}tii| o,td|ii tii |fqmn|id}d|}ti }tdd}|itii di} t|d|}td |d |}tiiii|tiid|t|d|}| d } | d }| d }x!| ||gD]}t#|qAWt$ti%| d}|}|i(tdti%|d|d|d ti)i*|dti%|dti+}|d7}|dddf7}|dddf7}|dddf7}|dddf7}|dd df7}yQdk-di.i/fdY} i1i2d|d| } | i4WnTt5j oHdk6di7fd Y} | d!|} | i9|nXdS("Nisdevelopment.inisE%sError: CONFIG_FILE not found at: .%s%s Please specify a CONFIG_FILEs config:%ss__name__s pylons-adminis relative_tosappsapp_confs.config.routings.modelss .lib.helperssmake_mapsmodelsmapperswsgiappshs$Pylons Interactive Shell Python %s sAdditional Objects: s %-10s - %s sRoutes mapper objects Helper objectsModels from models packagesThis projects WSGI App instances$paste.fixture wrapped around wsgiapps CustomIPShellcstZdZRS(Ncs=yiii|||SWntj o tnXdS(N(sIPythonsiplibsInteractiveShells raw_inputsselfsargsskwsEOFError(sselfsargsskw(sIPython(s?build/bdist.darwin-7.9.0-Power_Macintosh/egg/pylons/commands.pys raw_inputs(s__name__s __module__s raw_input((sIPython(s?build/bdist.darwin-7.9.0-Power_Macintosh/egg/pylons/commands.pys CustomIPShellssuser_nss shell_classs CustomShellcstZdZRS(Ncs:yii|||SWntj o tnXdS(N(scodesInteractiveConsoles raw_inputsselfsargsskwsEOFError(sselfsargsskw(scode(s?build/bdist.darwin-7.9.0-Power_Macintosh/egg/pylons/commands.pys raw_inputs(s__name__s __module__s raw_input((scode(s?build/bdist.darwin-7.9.0-Power_Macintosh/egg/pylons/commands.pys CustomShellsslocals(:slensselfsargss config_filesosspathsisfiles BadCommandsparsers get_usagesseps config_namesgetcwdshere_dirsdictslocsssplitslowerspkg_names appconfigsapp_confsconfspastesdeploysconfigsCONFIGspush_thread_configssyssinsertsloadappswsgiappsrouting_packagesmodels_packageshelpers_packagespacks __import__sgetattrsmodulessmake_mapsmappersupdatesfixturesTestAppsversionsbannersIPythonsiplibsInteractiveShells CustomIPShellsShellsIPShellsshellsmainloops ImportErrorscodesInteractiveConsoles CustomShellsinteract(sselfscodeswsgiappslocssconfsIPythonsmodels_packageshelpers_packagesapp_confspkg_namesrouting_packages CustomShells CustomIPShellsshells config_filesmappers config_nameshere_dirsbannersmake_mapspack((scodesIPythons?build/bdist.darwin-7.9.0-Power_Macintosh/egg/pylons/commands.pyscommandhsX0             ( s__name__s __module__s__doc__ssummarysusagesmin_argssmax_argss group_namesCommandsstandard_parsersTruesparserscommand(((s?build/bdist.darwin-7.9.0-Power_Macintosh/egg/pylons/commands.pys ShellCommandRs (s__doc__sossos.pathssyssglobspaste.script.commandsCommands BadCommandspaste.script.filemakersFileOps paste.scripts pluginlibscopydirs paste.deploysloadapps appconfigspaste.deploy.configspastes paste.fixturesControllerCommands ShellCommand( s pluginlibspastesglobs ShellCommandsControllerCommandsFileOpssyssloadappscopydirsCommands appconfigsoss BadCommand((s?build/bdist.darwin-7.9.0-Power_Macintosh/egg/pylons/commands.pys? s       ""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 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. ``environ_config`` Dict of environ keys for where in the environ to pickup various objects for registering with Pylons. If these are present then PylonsApp will use them from environ rather than using default middleware from Beaker. Valid keys are: ``session, cache`` ``template_engines`` List of template engines to configure. The first one in the list will be configured as the default template engine. Each item in the list is a dict indicating how to configure the template engine with keys: ``engine``, ``template_root``, ``template_options``, and ``alias`` """ def __init__(self, myghty, map, paths, environ_config=None): if environ_config is None: environ_config = {} self.myghty = myghty self.map = map self.paths = paths self.global_conf = {} self.app_conf = {} self.template_engines = [] self.environ_config = environ_config def add_template_engine(self, engine, root, options, alias=None): """Add additional template engines for configuration on Pylons WSGI init ``engine`` The name of the template engine ``root`` Template root for the engine ``options`` Dict of additional options used during engine initialization ``alias`` Name engine should respond to when actually used. This allows for multiple configurations of the same engine and lets you alias the additional ones to other names. Example of Kid addition:: # In yourproj/middleware.py # ... config.init_app(global_conf, app_conf, package='yourproj') # Load additional template engines kidopts = {'kid.assume_encoding':'utf-8', 'kid.encoding':'utf-8'} config.add_template_engine('kid', 'yourproj.kidtemplates', kidopts) Example of changing the default template engine:: # In yourproj/middleware.py # ... config.init_app(global_conf, app_conf, package='yourproj') # Remove existing template engine old_default = config.template_engines.pop() # Load additional template engines kidopts = {'kid.assume_encoding':'utf-8', 'kid.encoding':'utf-8'} config.add_template_engine('kid', 'yourproj.kidtemplates', kidopts) # Add old default as additional engine config.template_engines.append(old_default) """ config = dict(engine=engine, template_root=root, template_options=options, alias=alias) self.template_engines.append(config) 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 not enabled 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 myghty_defaults = {} # 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', 'params', 'g', 'render', 'render_fragment'] ) myghty_defaults['component_root'] = [{os.path.basename(path): path} for \ path in self.paths['templates']] 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')) 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 myghty_template_options = {} if app_conf.get('cache_dir', False): myghty_defaults['data_dir'] = app_conf['cache_dir'] else: myghty_defaults['data_dir'] = app_conf['myghty_data_dir'] # Copy Myghty defaults and options into template options for k, v in self.myghty.iteritems(): myghty_template_options['myghty.'+k] = v # Legacy copy of session and cache settings into app_conf if k.startswith('session_') or k.startswith('cache_'): self.app_conf[k] = v if not app_conf.has_key('session_data_dir'): app_conf['session_data_dir'] = os.path.join(app_conf['cache_dir'], 'sessions') if not app_conf.has_key('cache_data_dir'): app_conf['cache_data_dir'] = app_conf['cache_dir'] # Prepare our default template engine self.add_template_engine('pylonsmyghty', None, myghty_template_options) # Save our errorware values self.errorware = errorware PK4 pylons/config.pyc; Dc@s=dZdkZdkTdklZdefdYZdS(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/tZdZedZedZdZRS(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. ``environ_config`` Dict of environ keys for where in the environ to pickup various objects for registering with Pylons. If these are present then PylonsApp will use them from environ rather than using default middleware from Beaker. Valid keys are: ``session, cache`` ``template_engines`` List of template engines to configure. The first one in the list will be configured as the default template engine. Each item in the list is a dict indicating how to configure the template engine with keys: ``engine``, ``template_root``, ``template_options``, and ``alias`` cCsZ|tjo h}n||_||_||_h|_h|_g|_||_dS(N( senviron_configsNonesmyghtysselfsmapspathss global_confsapp_confstemplate_engines(sselfsmyghtysmapspathssenviron_config((s=build/bdist.darwin-7.9.0-Power_Macintosh/egg/pylons/config.pys__init__0s        c Cs5td|d|d|d|}|ii|dS(s<Add additional template engines for configuration on Pylons WSGI init ``engine`` The name of the template engine ``root`` Template root for the engine ``options`` Dict of additional options used during engine initialization ``alias`` Name engine should respond to when actually used. This allows for multiple configurations of the same engine and lets you alias the additional ones to other names. Example of Kid addition:: # In yourproj/middleware.py # ... config.init_app(global_conf, app_conf, package='yourproj') # Load additional template engines kidopts = {'kid.assume_encoding':'utf-8', 'kid.encoding':'utf-8'} config.add_template_engine('kid', 'yourproj.kidtemplates', kidopts) Example of changing the default template engine:: # In yourproj/middleware.py # ... config.init_app(global_conf, app_conf, package='yourproj') # Remove existing template engine old_default = config.template_engines.pop() # Load additional template engines kidopts = {'kid.assume_encoding':'utf-8', 'kid.encoding':'utf-8'} config.add_template_engine('kid', 'yourproj.kidtemplates', kidopts) # Add old default as additional engine config.template_engines.append(old_default) sengines template_rootstemplate_optionssaliasN( sdictsenginesrootsoptionssaliassconfigsselfstemplate_enginessappend(sselfsenginesrootsoptionssaliassconfig((s=build/bdist.darwin-7.9.0-Power_Macintosh/egg/pylons/config.pysadd_template_engine;s+!c Cs||_||_||_||d<|id}| o|id}n|o |d|i_t|i_nh}t |d<|i dg|di ddddd d d d d g gi }|idD]%} |htii| | <q~|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-7.9.0-Power_Macintosh/egg/pylons/database.pys__init__gs  cCs0|i o|in|ii||SdS(N(sselfshubsset_hubs__get__sobjstype(sselfsobjstype((s?build/bdist.darwin-7.9.0-Power_Macintosh/egg/pylons/database.pys__get__ls cCs0|i o|in|ii||SdS(N(sselfshubsset_hubs__set__sobjstype(sselfsobjstype((s?build/bdist.darwin-7.9.0-Power_Macintosh/egg/pylons/database.pys__set__qs cCs-|i o|int|i|SdS(N(sselfshubsset_hubsgetattrsname(sselfsname((s?build/bdist.darwin-7.9.0-Power_Macintosh/egg/pylons/database.pys __getattr__vs cCs|i}| obti}|id|id}|id|it}| o|idt}qsn| o t dnt i|t}| ot |}|t |>> def f(self, x=1, y=2, *args, **kw): pass >>> info = getinfo(f) >>> info["name"] 'f' >>> info["argnames"] ['self', 'x', 'y', 'args', 'kw'] >>> info["defarg"] (1, 2) >>> info["shortsign"] 'self, x, y, *args, **kw' >>> info["fullsign"] 'self, x=defarg[0], y=defarg[1], *args, **kw' >>> info["arg0"], info["arg1"], info["arg2"], info["arg3"], info["arg4"] ('self', 'x', 'y', 'args', 'kw') """ assert inspect.ismethod(func) or inspect.isfunction(func) regargs, varargs, varkwargs, defaults = inspect.getargspec(func) argnames = list(regargs) if varargs: argnames.append(varargs) if varkwargs: argnames.append(varkwargs) counter = itertools.count() fullsign = inspect.formatargspec( regargs, varargs, varkwargs, defaults, formatvalue=lambda value: "=defarg[%i]" % counter.next())[1:-1] shortsign = inspect.formatargspec( regargs, varargs, varkwargs, defaults, formatvalue=lambda value: "")[1:-1] dic = dict([("arg%s" % n, name) for n, name in enumerate(argnames)]) dic.update(name=func.__name__, argnames=argnames, shortsign=shortsign, fullsign = fullsign, defarg = func.func_defaults or ()) return dic def _contains_reserved_names(dic): # helper return "_call_" in dic or "_func_" in dic def _decorate(func, caller, infodict=None): """Takes a function and a caller and returns the function decorated with that caller. The decorated function is obtained by evaluating a function with the correct signature. """ infodict = infodict or getinfo(func) assert not _contains_reserved_names(infodict["argnames"]), \ "You cannot use _call_ or _func_ as argument names!" execdict= dict(_func_=func, _call_=caller, defarg=infodict["defarg"]) if infodict['name'] == "": lambda_src = "lambda %(fullsign)s: _call_(_func_, %(shortsign)s)" \ % infodict dec_func = eval(lambda_src, execdict) else: func_src = """def %(name)s(%(fullsign)s): return _call_(_func_, %(shortsign)s)""" % infodict # import sys; print >> sys.stderr, func_src # for debugging exec func_src in execdict dec_func = execdict[infodict['name']] dec_func.__doc__ = func.__doc__ dec_func.__dict__ = func.__dict__ dec_func.__module__ = func.__module__ return dec_func class decorator(object): """General purpose decorator factory: takes a caller function as input and returns a decorator. A caller function is any function like this:: def caller(func, *args, **kw): # do something return func(*args, **kw) Here is an example of usage: >>> @decorator ... def chatty(f, *args, **kw): ... print "Calling %r" % f.__name__ ... return f(*args, **kw) >>> @chatty ... def f(): pass ... >>> f() Calling 'f' """ def __init__(self, caller): self.caller = caller def __call__(self, func): if sys.version < '2.4': # gracefull fallback return lambda *args, **kw : self.caller(func, *args, **kw) else: return _decorate(func, self.caller) def newfunc(func, model=None): # not used internally """Creates an independent copy of a function. If model is not None, the new function copies the signature, as well the attributes __name__, __doc__, __dict__ and __module__ from the model, which must be a compatible function. Here is an example of usage: >>> def f(*args, **kw): ... return args[0]*2 >>> def double(x): ... pass >>> help(change_signature(f, double)) Help on function double in module __main__: double(x) """ if model is None: return new.function(func.func_code, func.func_globals, func.func_name, func.func_defaults, func.func_closure) else: return _decorate(func, lambda f, *a, **kw : f(*a,**kw), getinfo(model)) PK4dEpylons/decorator.pyc;  Dc@s}dZdddgZdkZdkZdkZdkZdZdZedZ de fdYZ ed Z dS( sDecorator module Author: Michele Simionato E-mail: michele.simionato@gmail.com Version: 0.7 License: Python license For more details, see: http://www.phyast.pitt.edu/~micheles/python/documentation.html s decoratorsnewfuncsgetinfoNc s]ti|p ti|ptti|\} } }}t | }| o|i | n|o|i |nt iti| | ||dddd!}ti| | ||dddd!}tgi }t|D] \} } |d| | fq~}|id|id|d |d |d |ipf|Sd S( s$Return an info dictionary containing: - name (the name of the function : str) - argnames (the names of the arguments : list) - defarg (the values of the default arguments : list) - fullsign (the full signature : str) - shortsign (the short signature : str) - arg0 ... argn (shortcuts for the names of the arguments) >>> def f(self, x=1, y=2, *args, **kw): pass >>> info = getinfo(f) >>> info["name"] 'f' >>> info["argnames"] ['self', 'x', 'y', 'args', 'kw'] >>> info["defarg"] (1, 2) >>> info["shortsign"] 'self, x, y, *args, **kw' >>> info["fullsign"] 'self, x=defarg[0], y=defarg[1], *args, **kw' >>> info["arg0"], info["arg1"], info["arg2"], info["arg3"], info["arg4"] ('self', 'x', 'y', 'args', 'kw') s formatvaluecsdiS(Ns =defarg[%i](scountersnext(svalue(scounter(s@build/bdist.darwin-7.9.0-Power_Macintosh/egg/pylons/decorator.pys6siicCsdS(Ns((svalue((s@build/bdist.darwin-7.9.0-Power_Macintosh/egg/pylons/decorator.pys9ssarg%ssnamesargnamess shortsignsfullsignsdefargN(sinspectsismethodsfuncs isfunctionsAssertionErrors getargspecsregargssvarargss varkwargssdefaultsslistsargnamessappends itertoolsscountscounters formatargspecsfullsigns shortsignsdicts_[1]s enumeratesnsnamesdicsupdates__name__s func_defaults( sfuncscountersfullsigns shortsignsargnamessdics_[1]s varkwargssdefaultssvarargssnsregargssname((scounters@build/bdist.darwin-7.9.0-Power_Macintosh/egg/pylons/decorator.pysgetinfos"'  CcCsd|jp d|jSdS(Ns_call_s_func_(sdic(sdic((s@build/bdist.darwin-7.9.0-Power_Macintosh/egg/pylons/decorator.pys_contains_reserved_names?scBs|p e|}e|d p tded|d|d|d}|ddjod|}e ||}n!d |}||U||d}|i |_ |i |_ |i|_|Sd S( sTakes a function and a caller and returns the function decorated with that caller. The decorated function is obtained by evaluating a function with the correct signature. sargnamess2You cannot use _call_ or _func_ as argument names!s_func_s_call_sdefargsnamess2lambda %(fullsign)s: _call_(_func_, %(shortsign)s)sHdef %(name)s(%(fullsign)s): return _call_(_func_, %(shortsign)s)N(sinfodictsgetinfosfuncs_contains_reserved_namessAssertionErrorsdictscallersexecdicts lambda_srcsevalsdec_funcsfunc_srcs__doc__s__dict__s __module__(sfuncscallersinfodictsexecdictsfunc_srcs lambda_srcsdec_func((s@build/bdist.darwin-7.9.0-Power_Macintosh/egg/pylons/decorator.pys _decorateBs     cBs tZdZdZdZRS(sGeneral purpose decorator factory: takes a caller function as input and returns a decorator. A caller function is any function like this:: def caller(func, *args, **kw): # do something return func(*args, **kw) Here is an example of usage: >>> @decorator ... def chatty(f, *args, **kw): ... print "Calling %r" % f.__name__ ... return f(*args, **kw) >>> @chatty ... def f(): pass ... >>> f() Calling 'f' cCs ||_dS(N(scallersself(sselfscaller((s@build/bdist.darwin-7.9.0-Power_Macintosh/egg/pylons/decorator.pys__init__oscs5tidjodSntiSdS(Ns2.4csi||S(N(sselfscallersfuncsargsskw(sargsskw(sselfsfunc(s@build/bdist.darwin-7.9.0-Power_Macintosh/egg/pylons/decorator.pysss(ssyssversions _decoratesfuncsselfscaller(sselfsfunc((sselfsfuncs@build/bdist.darwin-7.9.0-Power_Macintosh/egg/pylons/decorator.pys__call__qs(s__name__s __module__s__doc__s__init__s__call__(((s@build/bdist.darwin-7.9.0-Power_Macintosh/egg/pylons/decorator.pys decoratorZs  cCsV|tjo,ti|i|i|i|i|i Snt |dt |SdS(sCreates an independent copy of a function. If model is not None, the new function copies the signature, as well the attributes __name__, __doc__, __dict__ and __module__ from the model, which must be a compatible function. Here is an example of usage: >>> def f(*args, **kw): ... return args[0]*2 >>> def double(x): ... pass >>> help(change_signature(f, double)) Help on function double in module __main__: double(x) cOs |||S(N(sfsaskw(sfsaskw((s@build/bdist.darwin-7.9.0-Power_Macintosh/egg/pylons/decorator.pyssN( smodelsNonesnewsfunctionsfuncs func_codes func_globalss func_names func_defaultss func_closures _decoratesgetinfo(sfuncsmodel((s@build/bdist.darwin-7.9.0-Power_Macintosh/egg/pylons/decorator.pysnewfuncws   ( s__doc__s__all__sinspectsnews itertoolsssyssgetinfos_contains_reserved_namessNones _decoratesobjects decoratorsnewfunc( s__all__sgetinfosinspectssyss itertoolss _decorates_contains_reserved_namessnews decoratorsnewfunc((s@build/bdist.darwin-7.9.0-Power_Macintosh/egg/pylons/decorator.pys? s$ /  PKi4H+RRpylons/error.py"""Custom 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. """ __all__ = [] import myghty.exception, sys from paste.evalexception.middleware import * from paste.exceptions.formatter import * class Supplement(errormiddleware.Supplement): """This is a supplement used to display standard WSGI information in the traceback. """ def extraData(self): data = {} cgi_vars = data[('extra', 'CGI Variables')] = {} wsgi_vars = data[('extra', 'WSGI Variables')] = {} hide_vars = ['paste.config', 'wsgi.errors', 'wsgi.input', 'wsgi.multithread', 'wsgi.multiprocess', 'wsgi.run_once', 'wsgi.version', 'wsgi.url_scheme'] for name, value in self.environ.items(): if name.upper() == name: if value: cgi_vars[name] = value elif name not in hide_vars: wsgi_vars[name] = value if self.environ['wsgi.version'] != (1, 0): wsgi_vars['wsgi.version'] = self.environ['wsgi.version'] proc_desc = tuple([int(bool(self.environ[key])) for key in ('wsgi.multiprocess', 'wsgi.multithread', 'wsgi.run_once')]) wsgi_vars['wsgi process'] = self.process_combos[proc_desc] wsgi_vars['application'] = self.middleware.application if 'paste.config' in self.environ: data[('extra', 'Configuration')] = dict(self.environ['paste.config']) # Add any extra sections here return data class HTMLFormatter(formatter.HTMLFormatter): def format_collected_data(self, exc_data): general_data = {} if self.show_extra_data: for name, value_list in exc_data.extra_data.items(): if isinstance(name, tuple): importance, title = name else: importance, title = 'normal', name for value in value_list: general_data[(importance, name)] = self.format_extra_data( importance, title, value) lines = [] frames = self.filter_frames(exc_data.frames) for frame in frames: sup = frame.supplement if sup: if sup.object: general_data[('important', 'object')] = self.format_sup_object( sup.object) if sup.source_url: general_data[('important', 'source_url')] = self.format_sup_url( sup.source_url) if sup.line: lines.append(self.format_sup_line_pos(sup.line, sup.column)) if sup.expression: lines.append(self.format_sup_expression(sup.expression)) if sup.warnings: for warning in sup.warnings: lines.append(self.format_sup_warning(warning)) if sup.info: lines.extend(self.format_sup_info(sup.info)) if frame.supplement_exception: lines.append('Exception in supplement:') lines.append(self.quote_long(frame.supplement_exception)) if frame.traceback_info: lines.append(self.format_traceback_info(frame.traceback_info)) filename = frame.filename if filename and self.trim_source_paths: for path, repl in self.trim_source_paths: if filename.startswith(path): filename = repl + filename[len(path):] break lines.append(self.format_source_line(filename or '?', frame)) source = frame.get_source_line() long_source = frame.get_source_line(2) if source: lines.append(self.format_long_source( source, long_source)) exc_info = self.format_exception_info( exc_data.exception_type, exc_data.exception_value) data_by_importance = {'important': [], 'normal': [], 'supplemental': [], 'extra': []} for (importance, name), value in general_data.items(): data_by_importance[importance].append( (name, value)) for value in data_by_importance.itervalues(): value.sort() return self.format_combine(data_by_importance, lines, exc_info) def format_extra_data(self, importance, title, value): if isinstance(value, str): s = self.pretty_string_repr(value) if '\n' in s: return '%s:
%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: if global_conf is None: xmlhttp_key = '_' else: 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): if environ.get('paste.throw_errors'): return self.application(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) try: return_iter = list(app_iter) return return_iter finally: if hasattr(app_iter, 'close'): app_iter.close() except: exc_info = sys.exc_info() for expected in environ.get('paste.expected_exceptions', []): if isinstance(exc_info[1], 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 PK4@ XUXUpylons/error.pyc; MDc@sdZgZdkZdkZdkTdkTdeifdYZde i fdYZ e dZ dZ d 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-7.9.0-Power_Macintosh/egg/pylons/error.pysformat_extra_datans &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-7.9.0-Power_Macintosh/egg/pylons/error.pys zebra_table~s   .$ 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-7.9.0-Power_Macintosh/egg/pylons/error.pysformat_combines5  < < (s__name__s __module__sformat_collected_datasformat_extra_datas zebra_tablesformat_combine(((s<build/bdist.darwin-7.9.0-Power_Macintosh/egg/pylons/error.pys HTMLFormatter1s <  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-7.9.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-7.9.0-Power_Macintosh/egg/pylons/error.pysInvalidTemplates(s get_prefixsPylonsEvalExceptioncBs,tZeeedZdZdZRS(NcKs2||_||_h|_|tjo-|tjo d}qU|idd}n||_||_|id|id<|id=xNddddgD]:}d |d |ijot d d |d qqWyB|hdd <dd <dd <dd <d d <dd <Wnt dnXdS(Ns_s xmlhttp_keysdebugs 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-7.9.0-Power_Macintosh/egg/pylons/error.pys__init__s&          BcCs"|d7}d||||fSdS(Ns/_debugs (s base_pathscounter(sselfs base_pathscounter((s<build/bdist.darwin-7.9.0-Power_Macintosh/egg/pylons/error.pyseval_javascript3s c s|ido|i|Snti|dtdt}t |d|<d|i?d"d#i?d$d%<d&|<d|<}|gSnXdS('Nspaste.throw_errorsswith_path_infoswith_query_stringcs2y|||SWn nXitdS(N(sstart_responsesstatussheaderssexc_infosstartedsappendsTrue(sstatussheaderssexc_info(sstartedsstart_response(s<build/bdist.darwin-7.9.0-Power_Macintosh/egg/pylons/error.pysdetect_start_responseMs sclosespaste.expected_exceptionsis 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_datas 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(Asenvironsgetsselfs applicationsstart_responsesrequests construct_urlsFalses base_pathsTruesstartedsNonesdetect_start_responses Supplements__traceback_supplement__sapp_iterslists return_itershasattrsclosessyssexc_infosexpecteds isinstances debug_countersnextscounts make_view_urlsview_urisheaderssappendswrites 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_datastabs htmlformatsmtracestraceback_dataserror_templatesjoinsreplacespage(sselfsenvironsstart_responses return_itersdetect_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-7.9.0-Power_Macintosh/egg/pylons/error.pysrespondFsx              -,h(s__name__s __module__sNoneserror_templates__init__seval_javascriptsrespond(((s<build/bdist.darwin-7.9.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-7.9.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-7.9.0-Power_Macintosh/egg/pylons/error.pysformat_source_lines(s__name__s __module__s__init__sformat_source_line(((s<build/bdist.darwin-7.9.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-7.9.0-Power_Macintosh/egg/pylons/error.pysformat_eval_htmls  (s__doc__s__all__smyghty.exceptionsmyghtyssysspaste.evalexception.middlewarespaste.exceptions.formatterserrormiddlewares Supplements formatters HTMLFormattersFalses format_htmlserror_templates ExceptionsInvalidTemplates pylons.utils get_prefixs EvalExceptionsPylonsEvalExceptionsEvalHTMLFormattersformat_eval_html( s format_htmlsmyghtys__all__sPylonsEvalExceptionsEvalHTMLFormattersformat_eval_htmlssyss Supplements HTMLFormattersInvalidTemplateserror_templates get_prefix((s<build/bdist.darwin-7.9.0-Power_Macintosh/egg/pylons/error.pys? s!{ G PK4Bffpylons/helpers.py"""Myghty compatibility object, ``etag_cache``, ``redirect_to`` and Myghty Module Components Additional helper object available for use in Controllers is the etag_cache, along with the Myghty compatibility objects for Pylons 0.8 projects and new Myghty Module Components for use in Myghty templates. """ from routes import redirect_to from paste.registry import StackedObjectProxy import paste.httpexceptions as httpexceptions import pylons import pylons.helpers import pylons.templating as tmpl response = StackedObjectProxy(name="response") 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 a new response object and returned for use in your action. Suggested use is within a Controller Action like so:: import pylons class YourController(BaseController): def index(self): resp = etag_cache(key=1) resp.write(render('/splash.myt')) return resp .. Note:: This works because etag_cache will raise an HTTPNotModified exception if the ETag recieved matches the key provided. """ if_none_match = pylons.request.environ.get('HTTP_IF_NONE_MATCH', None) resp = pylons.Response() resp.headers['ETag'] = key if str(key) == if_none_match: raise httpexceptions.HTTPNotModified() else: return resp def abort(status_code=None, detail="", headers=None, comment=None): """Aborts the request immediately by returning an HTTP exception In the event that the status_code is a 300 series error, the detail attribute will be used as the Location header should one not be specified in the headers attribute. """ exc = httpexceptions.get_exception(status_code)(detail, headers, comment) raise exc __all__ = ['etag_cache', 'redirect_to', 'formfill'] PK4;h pylons/helpers.pyc; zDc@sdZdklZdklZdkiZdkZdkZdk i Z eddZ e dZe de e dZd d d gZdS( s+Myghty compatibility object, ``etag_cache``, ``redirect_to`` and Myghty Module Components Additional helper object available for use in Controllers is the etag_cache, along with the Myghty compatibility objects for Pylons 0.8 projects and new Myghty Module Components for use in Myghty templates. (s redirect_to(sStackedObjectProxyNsnamesresponsecCs\tiiidt}ti}||i dbuild/bdist.darwin-7.9.0-Power_Macintosh/egg/pylons/helpers.pys etag_caches  scCs%ti||||}|dS(sAborts the request immediately by returning an HTTP exception In the event that the status_code is a 300 series error, the detail attribute will be used as the Location header should one not be specified in the headers attribute. N(shttpexceptionss get_exceptions status_codesdetailsheadersscommentsexc(s status_codesdetailsheadersscommentsexc((s>build/bdist.darwin-7.9.0-Power_Macintosh/egg/pylons/helpers.pysabort3ss etag_caches redirect_tosformfill(s__doc__sroutess redirect_tospaste.registrysStackedObjectProxyspaste.httpexceptionsshttpexceptionsspylonsspylons.helpersspylons.templatings templatingstmplsresponsesNones etag_cachesaborts__all__( stmplspylonss__all__s redirect_tosabortsStackedObjectProxyshttpexceptionssresponses etag_cache((s>build/bdist.darwin-7.9.0-Power_Macintosh/egg/pylons/helpers.pys?s       ! PKlG4z>pylons/legacy.py"""Legacy objects for Pylons 0.8 projects""" from paste.registry import StackedObjectProxy import paste.httpexceptions as httpexceptions import pylons import pylons.helpers import pylons.templating as tmpl # Legacy objects m = StackedObjectProxy(name="m legacy object") params = StackedObjectProxy(name="params") class Myghty_Compat(object): """Myghty Compatibility Object for Pylons 0.8 Projects""" def __init__(self, environ, start_response): self.environ = environ self.start_response = start_response self.headers_out = pylons.helpers.response.headers self.headers_in = pylons.request.headers self.request_args = pylons.request.params def write(self, content): pylons.helpers.response.write(content) def out(self, content): pylons.helpers.response.write(content) def cache_self(self, *args, **kargs): return False def subexec(self, *args, **kargs): pylons.helpers.response.write(tmpl.render(*args, **kargs)) def comp(self, *args, **kargs): pylons.helpers.response.write(tmpl.render(fragment=True, *args, **kargs)) def scomp(self, *args, **kargs): return tmpl.render(fragment=True, *args, **kargs) def fetch_component(self, name): return name def get_cache(self, component): return pylons.cache.get_cache(component) def send_redirect(self, path, hard=True): raise httpexceptions.HTTPFound(path) def abort(self, status_code=None, reason=""): if status_code == 404: raise httpexceptions.HTTPNotFound() else: exc = httpexceptions.get_exception(status_code)(detail=reason) raise exc __all__ = ['m', 'params'] PK4ÿyypylons/legacy.pyc; Dc@sdZdklZdkiZdkZdkZdkiZ eddZ eddZ de fdYZ ddgZdS( s&Legacy objects for Pylons 0.8 projects(sStackedObjectProxyNsnamesm legacy objectsparamss Myghty_CompatcBsztZdZdZdZdZdZdZdZdZ dZ d Z e d Z ed d ZRS( s3Myghty Compatibility Object for Pylons 0.8 ProjectscCsF||_||_tiii|_tii|_ tii |_ dS(N( senvironsselfsstart_responsespylonsshelperssresponsesheaderss headers_outsrequests headers_insparamss request_args(sselfsenvironsstart_response((s=build/bdist.darwin-7.9.0-Power_Macintosh/egg/pylons/legacy.pys__init__s   cCstiii|dS(N(spylonsshelperssresponseswritescontent(sselfscontent((s=build/bdist.darwin-7.9.0-Power_Macintosh/egg/pylons/legacy.pyswritescCstiii|dS(N(spylonsshelperssresponseswritescontent(sselfscontent((s=build/bdist.darwin-7.9.0-Power_Macintosh/egg/pylons/legacy.pysoutscOstSdS(N(sFalse(sselfsargsskargs((s=build/bdist.darwin-7.9.0-Power_Macintosh/egg/pylons/legacy.pys cache_selfscOs#tiiiti||dS(N(spylonsshelperssresponseswritestmplsrendersargsskargs(sselfsargsskargs((s=build/bdist.darwin-7.9.0-Power_Macintosh/egg/pylons/legacy.pyssubexecscOs)tiiitidt||dS(Nsfragment( spylonsshelperssresponseswritestmplsrendersTruesargsskargs(sselfsargsskargs((s=build/bdist.darwin-7.9.0-Power_Macintosh/egg/pylons/legacy.pyscomp"scOstidt||SdS(Nsfragment(stmplsrendersTruesargsskargs(sselfsargsskargs((s=build/bdist.darwin-7.9.0-Power_Macintosh/egg/pylons/legacy.pysscomp%scCs|SdS(N(sname(sselfsname((s=build/bdist.darwin-7.9.0-Power_Macintosh/egg/pylons/legacy.pysfetch_component(scCstii|SdS(N(spylonsscaches get_caches component(sselfs component((s=build/bdist.darwin-7.9.0-Power_Macintosh/egg/pylons/legacy.pys get_cache+scCsti|dS(N(shttpexceptionss HTTPFoundspath(sselfspathshard((s=build/bdist.darwin-7.9.0-Power_Macintosh/egg/pylons/legacy.pys send_redirect.sscCs?|djotinti|d|}|dS(Nisdetail(s status_codeshttpexceptionss HTTPNotFounds get_exceptionsreasonsexc(sselfs status_codesreasonsexc((s=build/bdist.darwin-7.9.0-Power_Macintosh/egg/pylons/legacy.pysabort1s (s__name__s __module__s__doc__s__init__swritesouts cache_selfssubexecscompsscompsfetch_components get_cachesTrues send_redirectsNonesabort(((s=build/bdist.darwin-7.9.0-Power_Macintosh/egg/pylons/legacy.pys Myghty_Compat s           sm(s__doc__spaste.registrysStackedObjectProxyspaste.httpexceptionsshttpexceptionsspylonsspylons.helpersspylons.templatings templatingstmplsmsparamssobjects Myghty_Compats__all__(stmplspylonss__all__sms Myghty_CompatsStackedObjectProxysparamsshttpexceptions((s=build/bdist.darwin-7.9.0-Power_Macintosh/egg/pylons/legacy.pys?s     +PKlG47Jpylons/middleware.py"""EvalException, Error Documents, and Globals middleware""" import os.path import pylons.helpers from paste.deploy.converters import asbool from paste.urlparser import StaticURLParser from webhelpers.rails.asset_tag import javascript_path media_path = os.path.join(os.path.dirname(__file__), 'media') class Globals(object): """Legacy Globals object""" pass class StaticJavascripts(object): """ Middleware for intercepting requests for WebHelpers' included javascript files. Triggered when PATH_INFO begins with '/javascripts/'. """ def __init__(self): self.javascripts_app = StaticURLParser(os.path.dirname(javascript_path)) def __call__(self, environ, start_response): if environ.get('PATH_INFO', '').startswith('/javascripts/'): return self.javascripts_app(environ, start_response) else: return self.javascripts_app.not_found(environ, start_response) def run_wsgi(app, m, req): """Legacy WSGI call""" pylons.helpers.response.content = app(m.environ, m.start_response) pylons.helpers.response.wsgicall = True def ErrorHandler(app, global_conf, **errorware): """ErrorHandler Toggle If debug is enabled, 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')): 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 paste.recursive import RecursiveMiddleware from paste.errordocument import StatusBasedForward from urllib import urlencode from paste.deploy.converters import asbool from pylons.util import get_prefix def error_mapper(code, message, environ, global_conf=None, **kw): if global_conf is None: global_conf = {} codes = [401, 403, 404] if not asbool(global_conf.get('debug')): 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=None, 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 global_conf is None: global_conf = {} if mapper is None: mapper = error_mapper return RecursiveMiddleware(StatusBasedForward(app, global_conf=global_conf, mapper=mapper, **kw)) #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__ = ['ErrorHandler', 'ErrorDocuments', 'StaticJavascripts'] PK4C"z3"3"pylons/middleware.pyc; Dc@sdZdkZdkZdklZdklZdk l Z ei i ei i edZdefdYZdefd YZd Zd Zd klZd klZdklZdklZdklZedZeedZdZ dddgZ!dS(s6EvalException, Error Documents, and Globals middlewareN(sasbool(sStaticURLParser(sjavascript_pathsmediasGlobalscBstZdZRS(sLegacy Globals object(s__name__s __module__s__doc__(((sAbuild/bdist.darwin-7.9.0-Power_Macintosh/egg/pylons/middleware.pysGlobals s sStaticJavascriptscBs tZdZdZdZRS(s Middleware for intercepting requests for WebHelpers' included javascript files. Triggered when PATH_INFO begins with '/javascripts/'. cCsttiit|_dS(N(sStaticURLParsersosspathsdirnamesjavascript_pathsselfsjavascripts_app(sself((sAbuild/bdist.darwin-7.9.0-Power_Macintosh/egg/pylons/middleware.pys__init__scCsG|iddido|i||Sn|ii||SdS(Ns PATH_INFOss /javascripts/(senvironsgets startswithsselfsjavascripts_appsstart_responses not_found(sselfsenvironsstart_response((sAbuild/bdist.darwin-7.9.0-Power_Macintosh/egg/pylons/middleware.pys__call__s(s__name__s __module__s__doc__s__init__s__call__(((sAbuild/bdist.darwin-7.9.0-Power_Macintosh/egg/pylons/middleware.pysStaticJavascriptss  cCs1||i|itii_ttii_ dS(sLegacy WSGI callN( sappsmsenvironsstart_responsespylonsshelperssresponsescontentsTrueswsgicall(sappsmsreq((sAbuild/bdist.darwin-7.9.0-Power_Macintosh/egg/pylons/middleware.pysrun_wsgiscKs{t|ido#dkl}||||}n;dkl}|i do |d=n||||}|SdS(sKErrorHandler Toggle If debug is enabled, 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. sdebug(sPylonsEvalException(sErrorMiddlewareserror_templateN( sasbools global_confsgets pylons.errorsPylonsEvalExceptionsapps errorwares paste.exceptions.errormiddlewaresErrorMiddlewareshas_key(sapps global_confs errorwaresErrorMiddlewaresPylonsEvalException((sAbuild/bdist.darwin-7.9.0-Power_Macintosh/egg/pylons/middleware.pys ErrorHandler"s    (sRecursiveMiddleware(sStatusBasedForward(s urlencode(s get_prefixcKs|tjo h}ndddg}t|id o|idn||jo6dt|t hd|<d|<f}|SndS( Niiisdebugis%s/error/document/?%ssmessagescode( s global_confsNonescodessasboolsgetsappendscodes get_prefixsenvirons urlencodesmessagesurl(scodesmessagesenvirons global_confskwsurlscodes((sAbuild/bdist.darwin-7.9.0-Power_Macintosh/egg/pylons/middleware.pys error_mapperAs   .cKsQ|tjo h}n|tjo t}ntt|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(s global_confsNonesmappers error_mappersRecursiveMiddlewaresStatusBasedForwardsappskw(sapps global_confsmapperskw((sAbuild/bdist.darwin-7.9.0-Power_Macintosh/egg/pylons/middleware.pysErrorDocumentsKs     s Server Error %(code)s

Pylons


Error %(code)s

%(message)s

The Pylons Team | Top
s ErrorHandlersErrorDocuments("s__doc__sos.pathsosspylons.helpersspylonsspaste.deploy.converterssasboolspaste.urlparsersStaticURLParserswebhelpers.rails.asset_tagsjavascript_pathspathsjoinsdirnames__file__s media_pathsobjectsGlobalssStaticJavascriptssrun_wsgis ErrorHandlerspaste.recursivesRecursiveMiddlewarespaste.errordocumentsStatusBasedForwardsurllibs urlencodes pylons.utils get_prefixsNones error_mappersErrorDocumentsserror_document_templates __pudge_all__(s urlencodes error_mappers get_prefixspylonssasboolsRecursiveMiddlewaresStatusBasedForwardsrun_wsgisErrorDocumentss ErrorHandlersGlobalss media_pathsStaticURLParserserror_document_templates __pudge_all__sossjavascript_pathsStaticJavascripts((sAbuild/bdist.darwin-7.9.0-Power_Macintosh/egg/pylons/middleware.pys?s&     !        PK#4siT*T*pylons/templating.py"""Buffet templating plugin and render functions The Buffet object is styled after the original Buffet module that implements template language neutral rendering for CherryPy. This version of Buffet also contains caching functionality that utilizes `Beaker middleware `_ to provide template language neutral caching functionality. A customized version of `BuffetMyghty `_ is included that provides a template API hook as the ``pylonsmyghty`` engine. This version of BuffetMyghty disregards some of the TurboGears API spec so that traditional Myghty template names can be used with ``/`` and file extensions. The render functions are intended as the primary user-visible rendering commands and hook into Buffet to make rendering content easy. """ import pkg_resources import os try: from cStringIO import StringIO except ImportError: from StringIO import StringIO from myghty.interp import Interpreter import pylons 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, default_engine=None, template_root=None, default_options=None, **config): """Initialize the Buffet renderer, and optionally set a default engine/options""" if default_options is None: default_options = {} self.default_engine = default_engine self.template_root = template_root self.default_options = default_options self.engines = {} if self.default_engine: self.prepare(default_engine, template_root, **config) def prepare(self, engine_name, template_root=None, alias=None, **config): """Prepare a template engine for use This method must be run before the `render <#render>`_ method is called so that the ``template_root`` and options can be set. Template engines can also be aliased if you wish to use multiplate configurations of the same template engines, or prefer a shorter name when rendering a template with the engine of your choice. """ Engine = available_engines.get(engine_name, None) if not Engine: raise TemplateEngineMissing('Please install a plugin for ' '"%s" to use its functionality' % engine_name) engine_name = alias or engine_name defaults = config.pop('default_options', None) self.engines[engine_name] = \ dict(engine=Engine(options=config), root=template_root) def _update_names(self, ns): d = {} d.update(ns) d.update(dict( c=pylons.c, h=pylons.h, m=pylons.m, request=pylons.request, g=pylons.g, session=pylons.session, render=render, )) return d def render(self, engine_name=None, template_name=None, include_pylons_variables=True, namespace=None, cache_key=None, cache_expire=None, cache_type=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 ``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. Caching options (uses Beaker caching middleware) ``cache_key`` Key to cache this copy of the template under. ``cache_type`` Valid options are ``dbm``, ``file``, ``memory``, or ``ext:memcached``. ``cache_expire`` Time in seconds to cache this template with this ``cache_key`` for. Or use 'never' to designate that the cache should never expire. The minimum key required to trigger caching is ``cache_expire='never'`` which will cache the template forever seconds with no key. All other keyword options are passed directly to the template engine used. """ if not engine_name and self.default_engine: engine_name = self.default_engine engine_config = self.engines.get(engine_name) if not engine_config: raise Exception, "No engine with that name configured: %s" % engine_name full_path = template_name if engine_name != 'pylonsmyghty': if namespace==None: if include_pylons_variables is False: raise BuffetError('You must specify ``namespace`` if ``include_pylons_variables`` is ' 'False') else: namespace = self._update_names({}) elif isinstance(namespace, dict): if include_pylons_variables is True: for k in ['c','h','g','request','session', 'params']: if k in namespace: 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 = self._update_names(namespace) else: namespace = self._update_names(namespace) if not engine_name.startswith('pylons'): full_path = os.path.join(engine_config['root'], template_name) full_path = full_path.replace(os.path.sep, '.').lstrip('.') # If one of them is not None then the user did set something if cache_key is not None or cache_expire is not None or cache_type is not None: if not cache_type: cache_type = 'dbm' if not cache_key: cache_key = 'default' if cache_expire == 'never': cache_expire = None def content(): return engine_config['engine'].render(namespace, template=full_path, **options) tfile = full_path if options.get('fragment', False): tfile += '_frag' mycache = pylons.cache.get_cache(tfile) content = mycache.get_value(cache_key, createfunc=content, type=cache_type, expiretime=cache_expire) return content return engine_config['engine'].render(namespace, template=full_path, **options) class TemplateEngineMissing(Exception): pass class MyghtyTemplatePlugin(object): """Myghty Template Plugin This Myghty Template Plugin varies from the official BuffetMyghty in that it will properly populate all the default Myghty variables needed and render fragments. """ extension = "myt" def __init__(self, extra_vars_func=None, options=None): if options is None: options = {} myt_opts = {} for k, v in options.iteritems(): if k.startswith('myghty.'): myt_opts[k[7:]] = v myt_opts['global_args'] = dict( c=pylons.c, h=pylons.h, request=pylons.request, g=pylons.g, session=pylons.session, s=pylons.session, render=render, ) self.interpreter = Interpreter(**myt_opts) def load_template(self, template_path): pass def render(self, info, format="html", fragment=False, template=None): vars = info buf = StringIO() if fragment: self.interpreter.execute(template, request_args=vars, out_buffer=buf, disable_wrapping=True) else: self.interpreter.execute(template, request_args=vars, out_buffer=buf) return buf.getvalue() 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 render(*args, **kargs): """Render a template and return it as a string (possibly Unicode) Optionally takes 3 keyword arguments to use caching supplied by Buffet. Example:: >>> content = render('/my/template.myt') >>> print content >>> content = render('/my/template.myt', fragment=True) .. admonition:: Note Not all template languages support the concept of a fragment. In those template languages that do support the fragment option, this usually implies that the template will be rendered without extending or inheriting any site skin. """ fragment = kargs.pop('fragment', False) args = list(args) template = args.pop() cache_args = dict(cache_expire=kargs.pop('cache_expire', None), cache_type=kargs.pop('cache_type', None), cache_key=kargs.pop('cache_key', None)) if args: engine = args.pop() return pylons.buffet.render(engine, template, fragment=fragment, namespace=kargs, **cache_args) return pylons.buffet.render(template_name=template, fragment=fragment, namespace=kargs, **cache_args) def render_response(*args, **kargs): """Returns the rendered response within a Response object See ``render`` for information on rendering. Example:: def view(self): return render_response('/my/template.myt') """ return pylons.Response(render(*args, **kargs)) __pudge_all__ = ['render', 'render_response', 'Buffet', 'MyghtyTemplatePlugin'] __all__ = ['render', 'render_response', 'Buffet', 'MyghtyTemplatePlugin'] PK4n\K3K3pylons/templating.pyc; cDc@s-dZdkZdkZydklZWn ej odklZnXdklZdkZde fdYZ de fdYZ de fd YZ d e fd YZhZx0eid D]ZeiZeeei`_ to provide template language neutral caching functionality. A customized version of `BuffetMyghty `_ is included that provides a template API hook as the ``pylonsmyghty`` engine. This version of BuffetMyghty disregards some of the TurboGears API spec so that traditional Myghty template names can be used with ``/`` and file extensions. The render functions are intended as the primary user-visible rendering commands and hook into Buffet to make rendering content easy. N(sStringIO(s Interpreters BuffetErrorcBstZRS(N(s__name__s __module__(((sAbuild/bdist.darwin-7.9.0-Power_Macintosh/egg/pylons/templating.pys BuffetErrorssBuffetcBsVtZdZeeedZeedZdZeeeeeeedZRS(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. cKs`|tjo h}n||_||_||_h|_|io|i|||ndS(sSInitialize the Buffet renderer, and optionally set a default engine/optionsN(sdefault_optionssNonesdefault_enginesselfs template_rootsenginesspreparesconfig(sselfsdefault_engines template_rootsdefault_optionssconfig((sAbuild/bdist.darwin-7.9.0-Power_Macintosh/egg/pylons/templating.pys__init__)s       cKsvti|t}| otd|n|p|}|idt}t d|d|d||i |`_ method is called so that the ``template_root`` and options can be set. Template engines can also be aliased if you wish to use multiplate configurations of the same template engines, or prefer a shorter name when rendering a template with the engine of your choice. s9Please install a plugin for "%s" to use its functionalitysdefault_optionssenginesoptionssrootN(savailable_enginessgets engine_namesNonesEnginesTemplateEngineMissingsaliassconfigspopsdefaultssdicts template_rootsselfsengines(sselfs engine_names template_rootsaliassconfigsEnginesdefaults((sAbuild/bdist.darwin-7.9.0-Power_Macintosh/egg/pylons/templating.pysprepare6s  cCsgh}|i||itdtidtidtidtidti dti dt |SdS(Nscshsmsrequestsgssessionsrender( sdsupdatesnssdictspylonsscshsmsrequestsgssessionsrender(sselfsnssd((sAbuild/bdist.darwin-7.9.0-Power_Macintosh/egg/pylons/templating.pys _update_namesIs       c sk| o|io |i}n|ii| otd|n||djot jo0|t jot dq!|ihnttoh|tjoWxAdddddd gD]'} | jotd | qqW|iq!n|i|id  o>tiid |itiid id qtn|t j p|t j p |t j o| o d}n| o d}n|djo t }nd} } idt o| d7} nt i!i"| } | i$|d| d|d|} | Sndi%dSdS(sRender 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 ``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. Caching options (uses Beaker caching middleware) ``cache_key`` Key to cache this copy of the template under. ``cache_type`` Valid options are ``dbm``, ``file``, ``memory``, or ``ext:memcached``. ``cache_expire`` Time in seconds to cache this template with this ``cache_key`` for. Or use 'never' to designate that the cache should never expire. The minimum key required to trigger caching is ``cache_expire='never'`` which will cache the template forever seconds with no key. All other keyword options are passed directly to the template engine used. s'No engine with that name configured: %ss pylonsmyghtysGYou must specify ``namespace`` if ``include_pylons_variables`` is FalsescshsgsrequestssessionsparamssThe 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 templatespylonssroots.sdbmsdefaultsnevercsdidSdS(Nsenginestemplate(s engine_configsrenders namespaces full_pathsoptions((s engine_configs namespacesoptionss full_path(sAbuild/bdist.darwin-7.9.0-Power_Macintosh/egg/pylons/templating.pyscontentssfragments_frags createfuncstypes expiretimesenginestemplateN(&s engine_namesselfsdefault_enginesenginessgets engine_configs Exceptions template_names full_paths namespacesNonesinclude_pylons_variablessFalses BuffetErrors _update_namess isinstancesdictsTruesks startswithsosspathsjoinsreplacessepslstrips cache_keys cache_expires cache_typescontentstfilesoptionsspylonsscaches get_cachesmycaches get_valuesrender(sselfs engine_names template_namesinclude_pylons_variabless namespaces cache_keys cache_expires cache_typesoptionssmycachescontentstfilesks engine_configs full_path((s namespacesoptionss engine_configs full_pathsAbuild/bdist.darwin-7.9.0-Power_Macintosh/egg/pylons/templating.pysrenderWsN+      )'     ( s__name__s __module__s__doc__sNones__init__sprepares _update_namessTruesrender(((sAbuild/bdist.darwin-7.9.0-Power_Macintosh/egg/pylons/templating.pysBuffet!s   sTemplateEngineMissingcBstZRS(N(s__name__s __module__(((sAbuild/bdist.darwin-7.9.0-Power_Macintosh/egg/pylons/templating.pysTemplateEngineMissingssMyghtyTemplatePlugincBs>tZdZdZeedZdZdeedZRS(sMyghty Template Plugin This Myghty Template Plugin varies from the official BuffetMyghty in that it will properly populate all the default Myghty variables needed and render fragments. smytcCs|tjo h}nh}x<|iD].\}}|ido|||d>> content = render('/my/template.myt') >>> print content >>> content = render('/my/template.myt', fragment=True) .. admonition:: Note Not all template languages support the concept of a fragment. In those template languages that do support the fragment option, this usually implies that the template will be rendered without extending or inheriting any site skin. sfragments cache_expires cache_types cache_keys namespaces template_nameN(skargsspopsFalsesfragmentslistsargsstemplatesdictsNones cache_argssenginespylonssbuffetsrender(sargsskargssenginesfragmentstemplates cache_args((sAbuild/bdist.darwin-7.9.0-Power_Macintosh/egg/pylons/templating.pysrenders   &cOstit||SdS(sReturns the rendered response within a Response object See ``render`` for information on rendering. Example:: def view(self): return render_response('/my/template.myt') N(spylonssResponsesrendersargsskargs(sargsskargs((sAbuild/bdist.darwin-7.9.0-Power_Macintosh/egg/pylons/templating.pysrender_responses srendersrender_response(s__doc__s pkg_resourcessoss cStringIOsStringIOs ImportErrors myghty.interps Interpreterspylonss Exceptions BuffetErrorsobjectsBuffetsTemplateEngineMissingsMyghtyTemplatePluginsavailable_enginessiter_entry_pointss entry_pointsloadsEnginesnamesrendersrender_responses __pudge_all__s__all__(sEnginesavailable_enginesspylonssrendersStringIOs pkg_resourcessBuffetsrender_responses BuffetErrors entry_pointsTemplateEngineMissings Interpreters __pudge_all__sossMyghtyTemplatePlugins__all__((sAbuild/bdist.darwin-7.9.0-Power_Macintosh/egg/pylons/templating.pys?s*    '   PKS4)֘pylons/util.py"""Helpers object, RequestLocal object, and Paste Template config The util module provides the main Helper object used by Pylons. 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 from paste.script.templates import Template import pylons from routes import threadinglocal from paste.deploy.config import CONFIG def get_prefix(environ): prefix = environ['paste.config']['app_conf'].get('prefix') if not prefix: if environ.get('SCRIPT_NAME', '') != '': prefix = environ['SCRIPT_NAME'] if not prefix: prefix = '' return prefix def class_name_from_module_name(module_name): """Takes a module name and returns the name of the class it defines. If the module name contains dashes, they are replaced with underscores. Example:: >>> class_name_from_module_name('with-dashes') 'WithDashes' >>> class_name_from_module_name('with_underscores') 'WithUnderscores' >>> class_name_from_module_name('oneword') 'Oneword' """ words = module_name.replace('-', '_').split('_') return ''.join([w.title() for w in words]) 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_conf']['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_conf'].has_key('lang'): self.set_lang(CONFIG['app_conf']['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']: 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.""" 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 is 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 PylonsTemplate(Template): _template_dir = 'templates/paster_template' summary = 'Pylons application template' egg_plugins = ['Pylons', 'WebHelpers'] __all__ = ['RequestLocal', 'Helpers'] __pudge_all__ = ['RequestLocal', 'Helpers', 'PylonsTemplate'] PK4l22pylons/util.pyc; lDc@sdZdkZdkZdkZdklZdkZdkl Z dk l Z dZ dZ defdYZd efd YZd efd YZd efdYZdefdYZdd gZdd dgZdS(sHelpers object, RequestLocal object, and Paste Template config The util module provides the main Helper object used by Pylons. 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. N(sTemplate(sthreadinglocal(sCONFIGcCsd|ddid}| o+|idddjo|d}qJn| o d}n|SdS(Ns paste.configsapp_confsprefixs SCRIPT_NAMEs(senvironsgetsprefix(senvironsprefix((s;build/bdist.darwin-7.9.0-Power_Macintosh/egg/pylons/util.pys get_prefixs cCsS|iddid}digi}|D]}||iq/~SdS(sTakes a module name and returns the name of the class it defines. If the module name contains dashes, they are replaced with underscores. Example:: >>> class_name_from_module_name('with-dashes') 'WithDashes' >>> class_name_from_module_name('with_underscores') 'WithUnderscores' >>> class_name_from_module_name('oneword') 'Oneword' s-s_sN( s module_namesreplacessplitswordssjoinsappends_[1]swstitle(s module_names_[1]swswords((s;build/bdist.darwin-7.9.0-Power_Macintosh/egg/pylons/util.pysclass_name_from_module_namess RequestLocalcBsqtZdZdZdZdZdZdZdZdZ dZ d Z d Z d Z RS( sThis 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. cCsti|idException raised when a problem occurs with changing languages(s__name__s __module__s__doc__(((s;build/bdist.darwin-7.9.0-Power_Macintosh/egg/pylons/util.pys LanguageErroros s _TranslatorcBstZdZdZRS(sBAn empty gettext translator which just returns the original stringcCs|SdS(N(svalue(sselfsvalue((s;build/bdist.darwin-7.9.0-Power_Macintosh/egg/pylons/util.pysgettextus(s__name__s __module__s__doc__sgettext(((s;build/bdist.darwin-7.9.0-Power_Macintosh/egg/pylons/util.pys _Translatorss sHelperscBsYtZdZdZdZdZdZdZdZdZ d Z RS( NcKs!t|id<||id %s N(spylonssrequestsenvironswritesstrsmsg(sselfsmsg((s;build/bdist.darwin-7.9.0-Power_Macintosh/egg/pylons/util.pyslogscCstddS(sDeprecated, use _()sUse h._() insteadN(sNotImplementedError(sselfsvalue((s;build/bdist.darwin-7.9.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-7.9.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-7.9.0-Power_Macintosh/egg/pylons/util.pysset_langs  #cCs|idiSdS(Ns_local(sselfs__dict__slang(sself((s;build/bdist.darwin-7.9.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-7.9.0-Power_Macintosh/egg/pylons/util.pysHelpersxs      sPylonsTemplatecBs tZdZdZddgZRS(Nstemplates/paster_templatesPylons application templatesPylonss WebHelpers(s__name__s __module__s _template_dirssummarys egg_plugins(((s;build/bdist.darwin-7.9.0-Power_Macintosh/egg/pylons/util.pysPylonsTemplates(s__doc__ssyssos.pathsossgettextspaste.script.templatessTemplatespylonssroutessthreadinglocalspaste.deploy.configsCONFIGs get_prefixsclass_name_from_module_namesobjects RequestLocals Exceptions LanguageErrors _TranslatorsHelperssPylonsTemplates__all__s __pudge_all__(s RequestLocals get_prefixsHelpersspylonss__all__sCONFIGsgettextssyssclass_name_from_module_names _TranslatorsTemplates LanguageErrors __pudge_all__sPylonsTemplatesossthreadinglocal((s;build/bdist.darwin-7.9.0-Power_Macintosh/egg/pylons/util.pys? s      >V PKi4׀..pylons/wsgiapp.py"""WSGI App Creator This module is responsible for creating the basic Pylons WSGI application. It's generally assumed that it will be called by Paste, though any WSGI application server could create and call the WSGI app as well. """ import sys import re import inspect import urllib import paste.wsgiwrappers import paste.httpexceptions as httpexceptions from paste.registry import RegistryManager from paste.wsgiwrappers import WSGIRequest from routes import request_config import pylons import pylons.templating from pylons.util import RequestLocal, class_name_from_module_name from pylons.legacy import Myghty_Compat from pylons.controllers import Controller, WSGIController class PylonsBaseWSGIApp(object): """Basic Pylons WSGI Application This basic WSGI app is provided should a web developer want to get access to the most basic Pylons web application environment available. By itself, this Pylons web application does little more than dispatch to a controller and setup the context object, the request object, and the globals object. Additional functionality like sessions, and caching can be setup by altering the ``environ['pylons.environ_config']`` setting to indicate what key the ``session`` and ``cache`` functionality should come from. Resolving the URL and dispatching can be customized by sub-classing or "monkey-patching" this class. Subclassing is the preferred approach. """ def __init__(self, mapper, package_name, globals, default_charset='UTF-8'): self.mapper = mapper self.globals = globals self.package_name = package_name self.default_charset = default_charset self.settings = dict(charset=default_charset, content_type='text/html') self.c = RequestLocal() config = globals.pylons_config # Create the redirect function we'll use and save it def redirect_to(url): raise httpexceptions.HTTPFound(url) self.redirect_to = redirect_to # Initialize Buffet and all our template engines, default engine is the # first in the template_engines list def_eng = config.template_engines.pop(0) self.buffet = pylons.templating.Buffet(def_eng['engine'], template_root=def_eng['template_root'], **def_eng['template_options']) for e in config.template_engines: self.buffet.prepare(e['engine'], template_root=e['template_root'], alias=e['alias'], **e['template_options']) def __call__(self, environ, start_response): self.setup_app_env(environ, start_response) if environ.get('paste.testing'): self.load_test_env(environ) # Change our HTTP_METHOD if _method is present, try GET first to avoid # parsing POST unless absolutely necessary. req = pylons.request.current_obj() old_method = None if req.GET.has_key('_method'): old_method = environ['REQUEST_METHOD'] environ['REQUEST_METHOD'] = req.GET['_method'] elif req.POST.has_key('_method'): old_method = environ['REQUEST_METHOD'] environ['REQUEST_METHOD'] = req.POST['_method'] controller = self.resolve(environ, start_response) if old_method: environ['REQUEST_METHOD'] = old_method response = self.dispatch(controller, environ, start_response) if environ.get('paste.testing') and hasattr(response, 'wsgi_response'): environ['paste.testing_variables']['response'] = response # Transform HttpResponse objects into WSGI response if hasattr(response, 'wsgi_response'): status, response_headers, content = response.wsgi_response() start_response(status, response_headers) return content elif response: return response # Apparently we returned absolutely nothing, use the response # object if in legacy mode, otherwise raise an exception if environ.get('pylons.legacy'): resp = pylons.helpers.response if hasattr(pylons.helpers.response, 'wsgicall'): # Legacy app using run_wsgi return resp.content status, response_headers, content = resp.wsgi_response() start_response(status, response_headers) return content else: raise Exception, "No content returned by controller: %s" % controller.__name__ def setup_app_env(self, environ, start_response): """Setup and register all the Pylons objects with the registry""" req = WSGIRequest(environ) environ['paste.registry'].register(paste.wsgiwrappers.settings, self.settings) environ['paste.registry'].register(pylons.request, req) environ['paste.registry'].register(pylons.c, self.c) environ['paste.registry'].register(pylons.g, self.globals) environ['paste.registry'].register(pylons.buffet, self.buffet) pylons.h() self.c._clear() # Setup legacy globals if environ.get('pylons.legacy'): environ['paste.registry'].register(pylons.helpers.response, WSGIResponse()) environ['paste.registry'].register(pylons.m, Myghty_Compat(environ, start_response)) environ['paste.registry'].register(pylons.params, req.params) econf = environ['pylons.environ_config'] if econf.get('session'): environ['paste.registry'].register(pylons.session, environ[econf['session']]) if econf.get('cache'): environ['paste.registry'].register(pylons.cache, environ[econf['cache']]) def resolve(self, environ, start_response): """Implements Routes-based dispatching""" config = request_config() config.mapper = self.mapper config.environ = environ config.redirect = self.redirect_to match = config.mapper_dict if not match: return None environ['pylons.routes_dict'] = match controller = match.get('controller') if not controller: return None # Pull the controllers class name, import controller # @@ TODO: Encapsulate in try/except to raise error if controller # doesn't exist, or class in controller file doesn't exist. full_module_name = self.package_name + '.controllers.' \ + controller.lower().replace('/', '.') __import__(full_module_name) module_name = full_module_name.split('.')[-1] class_name = class_name_from_module_name(module_name) + 'Controller' return getattr(sys.modules[full_module_name], class_name) def dispatch(self, controller, environ, start_response): """Dispatches to a controller, will instantiate the controller if necessary""" if not controller: raise httpexceptions.HTTPNotFound() match = environ['pylons.routes_dict'] # Sanitize keys # @@ TODO: This should be done in a lazy fashion for k,v in match.iteritems(): if v: match[k] = urllib.unquote_plus(v) # Older subclass of Controller if inspect.isclass(controller) and not issubclass(controller, WSGIController) and \ issubclass(controller, Controller): controller = controller() controller.start_response = start_response # @@ LEGACY: Attach c to controller if environ.get('pylons.legacy'): controller.c = pylons.c return controller(**match) # If the route included a path_info attribute, we'll assume it # should be pulled, otherwise we call the controller if match.get('path_info'): self.fixup_environ(environ, match) # If it's a class, instantiate it if not hasattr(controller, '__class__') or \ getattr(controller, '__class__') == type: controller = controller() # Controller is assumed to handle a WSGI call return controller(environ, start_response) def fixup_environ(self, environ, dispatch): """Fixes the environ based on the Routes match""" oldpath = environ['PATH_INFO'] newpath = dispatch.get('path_info') or '' environ['PATH_INFO'] = newpath if not environ['PATH_INFO'].startswith('/'): environ['PATH_INFO'] = '/' + environ['PATH_INFO'] environ['SCRIPT_NAME'] += re.sub(r'^(.*?)/' + newpath + '$', r'\1', oldpath) if environ['SCRIPT_NAME'].endswith('/'): environ['SCRIPT_NAME'] = environ['SCRIPT_NAME'][:-1] def load_test_env(self, environ): """Sets up our Paste testing environment""" testenv = environ['paste.testing_variables'] testenv['req'] = pylons.request.current_obj() testenv['c'] = pylons.c.current_obj() testenv['g'] = pylons.g.current_obj() econf = environ['pylons.environ_config'] if econf.get('session'): testenv['session'] = environ[econf['session']] if econf.get('cache'): testenv['cache'] = environ[econf['cache']] class PylonsApp(object): """Setup the Pylons default environment Pylons App sets up the basic Pylons app, and initializes the global object, sessions and caching. Sessions and caching can be overridden in the config object by supplying other keys to look for in the environ where objects for the session/cache will be. If they're set to none, then no session/cache objects will be available. """ def __init__(self, config, default_charset='UTF-8'): self.config = config g = None try: package = __import__(config.package + '.lib.app_globals', globals(), locals(), ['Globals']) except ImportError: pass else: g = package.Globals(config.global_conf, config.app_conf, config=config) g.pylons_config = config # Create the base Pylons wsgi app app = PylonsBaseWSGIApp(config.map, config.package, g, default_charset) # Pull user-specified environ overrides, or just setup default # session and caching objects self.econf = econf = config.environ_config.copy() if not econf.has_key('session'): from beaker.session import SessionMiddleware econf['session'] = 'beaker.session' app = SessionMiddleware(app, config.global_conf, auto_register=True, **config.app_conf) if not econf.has_key('cache'): from beaker.cache import CacheMiddleware econf['cache'] = 'beaker.cache' app = CacheMiddleware(app, config.global_conf, **config.app_conf) self.globals = g self.app = app def __call__(self, environ, start_response): environ['pylons.environ_config'] = self.econf return self.app(environ, start_response) WSGIResponse = None class LegacyApp(object): def __init__(self, config): global WSGIResponse from paste.wsgiwrappers import WSGIResponse self.app = PylonsApp(config) self.globals = self.app.globals def __call__(self, environ, start_response): environ['pylons.legacy'] = True return self.app(environ, start_response) def make_app(config): """ Legacy WSGI app creator""" papp = LegacyApp(config) from paste.deploy.config import ConfigMiddleware app = ConfigMiddleware(papp, { 'default':config.global_conf, 'app':config.app_conf, 'app_conf':config.app_conf, 'global_conf':config.global_conf }) app = RegistryManager(app) app.globals = papp.globals return app PK4lb)3)3pylons/wsgiapp.pyc; MDc@sdZdkZdkZdkZdkZdkZdkiZdk l Z dkl Z dk l Z dkZdkZdklZlZdklZdklZlZdefd YZd efd YZead efd YZdZdS(sWSGI App Creator This module is responsible for creating the basic Pylons WSGI application. It's generally assumed that it will be called by Paste, though any WSGI application server could create and call the WSGI app as well. N(sRegistryManager(s WSGIRequest(srequest_config(s RequestLocalsclass_name_from_module_name(s Myghty_Compat(s ControllersWSGIControllersPylonsBaseWSGIAppcBsPtZdZddZdZdZdZdZdZdZ RS( sBasic Pylons WSGI Application This basic WSGI app is provided should a web developer want to get access to the most basic Pylons web application environment available. By itself, this Pylons web application does little more than dispatch to a controller and setup the context object, the request object, and the globals object. Additional functionality like sessions, and caching can be setup by altering the ``environ['pylons.environ_config']`` setting to indicate what key the ``session`` and ``cache`` functionality should come from. Resolving the URL and dispatching can be customized by sub-classing or "monkey-patching" this class. Subclassing is the preferred approach. sUTF-8c Cs||_||_||_||_td|dd|_t|_|i }d}||_ |i i d}tii|dd|d|d|_x@|i D]5}|ii|dd|dd |d |dqWdS( Nscharsets content_types text/htmlcCsti|dS(N(shttpexceptionss HTTPFoundsurl(surl((s>build/bdist.darwin-7.9.0-Power_Macintosh/egg/pylons/wsgiapp.pys redirect_to5sisengines template_rootstemplate_optionssalias(smappersselfsglobalss package_namesdefault_charsetsdictssettingss RequestLocalscs pylons_configsconfigs redirect_tostemplate_enginesspopsdef_engspylonss templatingsBuffetsbuffetsesprepare( sselfsmappers package_namesglobalssdefault_charsetsdef_engses redirect_tosconfig((s>build/bdist.darwin-7.9.0-Power_Macintosh/egg/pylons/wsgiapp.pys__init__+s          c Cs|i|||ido|i|ntii}t }|i i do|d}|i d|dbuild/bdist.darwin-7.9.0-Power_Macintosh/egg/pylons/wsgiapp.pys__call__Bs>       cCst|}|ditii|i|diti ||diti |i |diti |i |diti |i ti|i i|ido[|ditiit|ditit|||diti|in|d}|ido#|diti||dn|ido#|diti||dndS(s;Setup and register all the Pylons objects with the registryspaste.registrys pylons.legacyspylons.environ_configssessionscacheN(s WSGIRequestsenvironsreqsregisterspastes wsgiwrappersssettingssselfspylonssrequestscsgsglobalssbuffetshs_clearsgetshelperssresponses WSGIResponsesms Myghty_Compatsstart_responsesparamsseconfssessionscache(sselfsenvironsstart_responsesreqseconf((s>build/bdist.darwin-7.9.0-Power_Macintosh/egg/pylons/wsgiapp.pys setup_app_envns$     #c Cst}|i|_||_|i|_|i}| ot Sn||d<|i d}| ot Sn|i d|i idd}t||idd}t|d}tti||SdS( s#Implements Routes-based dispatchingspylons.routes_dicts controllers .controllers.s/s.is ControllerN(srequest_configsconfigsselfsmappersenvirons redirect_tosredirects mapper_dictsmatchsNonesgets controllers package_nameslowersreplacesfull_module_names __import__ssplits module_namesclass_name_from_module_names class_namesgetattrssyssmodules( sselfsenvironsstart_responsesfull_module_names controllers class_names module_namesconfigsmatch((s>build/bdist.darwin-7.9.0-Power_Macintosh/egg/pylons/wsgiapp.pysresolves"      # cCs7| otin|d}x8|iD]*\}}|oti |||build/bdist.darwin-7.9.0-Power_Macintosh/egg/pylons/wsgiapp.pysdispatchs&  1  ' cCs|d}|idpd}||d<|did od|d|dbuild/bdist.darwin-7.9.0-Power_Macintosh/egg/pylons/wsgiapp.pys fixup_environs  'cCs|d}tii|dbuild/bdist.darwin-7.9.0-Power_Macintosh/egg/pylons/wsgiapp.pys load_test_envs  ( s__name__s __module__s__doc__s__init__s__call__s setup_app_envsresolvesdispatchs fixup_environs load_test_env(((s>build/bdist.darwin-7.9.0-Power_Macintosh/egg/pylons/wsgiapp.pysPylonsBaseWSGIApps   ,   & s PylonsAppcBs#tZdZddZdZRS(sSetup the Pylons default environment Pylons App sets up the basic Pylons app, and initializes the global object, sessions and caching. Sessions and caching can be overridden in the config object by supplying other keys to look for in the environ where objects for the session/cache will be. If they're set to none, then no session/cache objects will be available. sUTF-8c CsJ||_t}y)t|idttdg}Wntj on)X|i |i |i d|}||_ t |i|i||}|ii|_}|id o9dkl}d|d<|||i dt|i }n|id o3d kl}d |d<|||i |i }n||_||_dS( Ns.lib.app_globalssGlobalssconfigssession(sSessionMiddlewaresbeaker.sessions auto_registerscache(sCacheMiddlewares beaker.cache(sconfigsselfsNonesgs __import__spackagesglobalsslocalss ImportErrorsGlobalss global_confsapp_confs pylons_configsPylonsBaseWSGIAppsmapsdefault_charsetsappsenviron_configscopyseconfshas_keysbeaker.sessionsSessionMiddlewaresTrues beaker.cachesCacheMiddleware( sselfsconfigsdefault_charsetsgspackageseconfsSessionMiddlewaresCacheMiddlewaresapp((s>build/bdist.darwin-7.9.0-Power_Macintosh/egg/pylons/wsgiapp.pys__init__s* )       cCs!|i|d<|i||SdS(Nspylons.environ_config(sselfseconfsenvironsappsstart_response(sselfsenvironsstart_response((s>build/bdist.darwin-7.9.0-Power_Macintosh/egg/pylons/wsgiapp.pys__call__s (s__name__s __module__s__doc__s__init__s__call__(((s>build/bdist.darwin-7.9.0-Power_Macintosh/egg/pylons/wsgiapp.pys PylonsApps  s LegacyAppcBstZdZdZRS(NcCs/dklat||_|ii|_dS(N(s WSGIResponse(spaste.wsgiwrapperss WSGIResponses PylonsAppsconfigsselfsappsglobals(sselfsconfig((s>build/bdist.darwin-7.9.0-Power_Macintosh/egg/pylons/wsgiapp.pys__init__ s cCst|d<|i||SdS(Ns pylons.legacy(sTruesenvironsselfsappsstart_response(sselfsenvironsstart_response((s>build/bdist.darwin-7.9.0-Power_Macintosh/egg/pylons/wsgiapp.pys__call__s (s__name__s __module__s__init__s__call__(((s>build/bdist.darwin-7.9.0-Power_Macintosh/egg/pylons/wsgiapp.pys LegacyApp s cCsxt|}dkl}||hd|i<d|i<d|i<d|i<}t|}|i |_ |SdS(s Legacy WSGI app creator(sConfigMiddlewaresdefaultsappsapp_confs global_confN( s LegacyAppsconfigspappspaste.deploy.configsConfigMiddlewares global_confsapp_confsappsRegistryManagersglobals(sconfigsappsConfigMiddlewarespapp((s>build/bdist.darwin-7.9.0-Power_Macintosh/egg/pylons/wsgiapp.pysmake_apps  ?  (s__doc__ssyssresinspectsurllibspaste.wsgiwrappersspastespaste.httpexceptionsshttpexceptionsspaste.registrysRegistryManagers WSGIRequestsroutessrequest_configspylonsspylons.templatings pylons.utils RequestLocalsclass_name_from_module_names pylons.legacys Myghty_Compatspylons.controllerss ControllersWSGIControllersobjectsPylonsBaseWSGIApps PylonsAppsNones WSGIResponses LegacyAppsmake_app(srequest_configsPylonsBaseWSGIAppsWSGIControllers PylonsAppsres Myghty_Compatsurllibsclass_name_from_module_names Controllershttpexceptionssinspectspylonssmake_apps LegacyAppssyssRegistryManagerspastes WSGIRequests RequestLocal((s>build/bdist.darwin-7.9.0-Power_Macintosh/egg/pylons/wsgiapp.pys?s&            - PK[4N) ) pylons/decorators/__init__.py"""Custom Decorators, currently ``jsonify``, ``validate``, and 2 REST decorators""" import types import simplejson as json import formencode.api as api from formencode import htmlfill import pylons from pylons.decorator import decorator import rest def jsonify(func, *args, **kw): """Action decorator that formats output for JSON Given a function that will return content, this decorator will turn the result into JSON, with a content-type of 'text/javascript' and output it. """ response = pylons.Response() response.headers['Content-Type'] = 'text/javascript' response.content.append(json.dumps(func(*args, **kw))) return response jsonify = decorator(jsonify) def validate(schema=None, validators=None, form=None): """Validate input either for a FormEncode schema, or individual validators Given a form schema or dict of validators, validate will attempt to validate the schema or validator list. If validation was succesfull, the valid result dict will be saved as ``self.form_results``. Otherwise, the action will be re-run as if it was a GET, and the output will be filled by FormEncode's htmlfill to fill in the form field errors. Example:: class SomeController(BaseController): def create(self, id): return render_response('/myform.myt') @validate(schema=model.forms.myshema(), form='create') def update(self, id): # Do something with self.form_results pass """ def validate(func, self, *args, **kwargs): defaults, errors = {}, {} if not pylons.request.method == 'POST': return func(self, *args, **kwargs) defaults.update(pylons.request.POST) if schema: try: self.form_result = schema.to_python(defaults) except api.Invalid, e: errors = e.unpack_errors() if validators: if isinstance(validators, dict): for field, validator in validators.iteritems(): try: self.form_result[field] = \ validator.to_python(defaults[field] or None) except api.Invalid, error: errors[field] = error if errors: pylons.request.environ['REQUEST_METHOD'] = 'GET' pylons.request.environ['pylons.routes_dict']['action'] = form response = self._dispatch_call() form_content = "".join(response.content) response.content = [htmlfill.render(form_content, defaults, errors)] return response return func(self, *args, **kwargs) return decorator(validate) __all__ = ['jsonify', 'validate', 'rest'] PK4dpylons/decorators/__init__.pyc; Dc@sdZdkZdkZdkiZdklZdkZdk l Z dk Z dZ e e Z e e e dZdddgZdS( sMCustom Decorators, currently ``jsonify``, ``validate``, and 2 REST decoratorsN(shtmlfill(s decoratorcOsCti}d|id<|iiti||||SdS(sAction decorator that formats output for JSON Given a function that will return content, this decorator will turn the result into JSON, with a content-type of 'text/javascript' and output it. stext/javascripts Content-TypeN( spylonssResponsesresponsesheadersscontentsappendsjsonsdumpssfuncsargsskw(sfuncsargsskwsresponse((sJbuild/bdist.darwin-7.9.0-Power_Macintosh/egg/pylons/decorators/__init__.pysjsonify s   "cs d}t|SdS(s?Validate input either for a FormEncode schema, or individual validators Given a form schema or dict of validators, validate will attempt to validate the schema or validator list. If validation was succesfull, the valid result dict will be saved as ``self.form_results``. Otherwise, the action will be re-run as if it was a GET, and the output will be filled by FormEncode's htmlfill to fill in the form field errors. Example:: class SomeController(BaseController): def create(self, id): return render_response('/myform.myt') @validate(schema=model.forms.myshema(), form='create') def update(self, id): # Do something with self.form_results pass c shhf\} }tiidj o||||Sn| i tii oAyi | |_ Wqtij o}|i}qXnottokxhiD]V\}}y%|i | |pt|i |dZdkZdklZdZdZddgZdS(sREST decoratorsN(s decoratorcsd}t|SdS(sRestricts access to the function depending on HTTP method Example:: class SomeController(BaseController): @pylons.rest.restrict('GET') def comment(self, id): csWtiijo3ti}di|id, 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) PK4&&pylons/i18n/__init__.pyc; p|Dc@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-7.9.0-Power_Macintosh/egg/pylons/i18n/__init__.pysinitialize_optionsscCsdS(N((sself((sDbuild/bdist.darwin-7.9.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-7.9.0-Power_Macintosh/egg/pylons/i18n/__init__.pysruns *   ( : (s__name__s __module__s descriptions user_optionssboolean_optionssinitialize_optionssfinalize_optionssrun(((sDbuild/bdist.darwin-7.9.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-7.9.0-Power_Macintosh/egg/pylons/i18n/__init__.pysfinalize_optionsCscCs t|_dS(N(sNonesselfslang(sself((sDbuild/bdist.darwin-7.9.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-7.9.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-7.9.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-7.9.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-7.9.0-Power_Macintosh/egg/pylons/i18n/__init__.pys?s$6PKN4`*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() PK4Npylons/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-7.9.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') PK4eJ݌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-7.9.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-7.9.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-7.9.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-7.9.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-7.9.0-Power_Macintosh/egg/pylons/i18n/pygettext.pys?sH                     '   PKV4oݯ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))) PK4_Xpylons/i18n/translation.pyc; p|Dc@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-7.9.0-Power_Macintosh/egg/pylons/i18n/translation.pysegg_translations(sossgettexts pkg_resourcessresource_streamsegg_translation(sresource_streamsossegg_translation((sGbuild/bdist.darwin-7.9.0-Power_Macintosh/egg/pylons/i18n/translation.pys?s  PKhP4 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`PKhP46HG)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%PKhP41!pylons/media/img/hatch-yellow.pngPNG  IHDRJ"+tEXtCreation TimeWed 2 Mar 2005 01:35:41 -0000Ja5tIME +_ pHYs B4gAMA aIDATxc0`b ,0H]KXIENDB`PKhP4h3pylons/media/img/header.pngPNG  IHDRM+tEXtCreation TimeMon 9 May 2005 22:40:47 -0000?tIME+ pHYs B4gAMA a.IDATxc bb`` # /$$0!@jIENDB`PKhP4?Apylons/media/img/highlight.pngPNG  IHDRJ"+tEXtCreation TimeSat 5 Feb 2005 02:45:25 -0000LCCtIME (b pHYs B4gAMA aIDATxc0`b ,0H]KXIENDB`PKhP4tQt77pylons/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`PKhP4H-%%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;PKhP4,#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`PKhP4A 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`PKhP4#>iipylons/media/img/plus.jpgJFIFC    $.' ",#(7),01444'9=82<.342C  2!!22222222222222222222222222222222222222222222222222 "#"#4Ts! ?gnIe=%iȑ>󧼎n.sU1}\p7?/Z2Y?PKhP4Cpylons/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`PKhP4ǘ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`PKhP4^Й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`PKhP4SOpylons/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-;PKhP4;,#,#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; } PKhP4pylons/templates/__init__.pyPK4=0.9dev-r742"], 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 """, )PKi4dLhhQpylons/templates/paster_template/+egg+.egg-info/paste_deploy_config.ini_tmpl_tmpl# # ${project} - Pylons configuration # # The %(here) variable will be replaced with the parent directory of this file # [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:${project} myghty_data_dir = %(here)s/data/templates cache_data_dir = %(here)s/data/cache session_data_dir = %(here)s/data/sessions session_key = ${package} session_secret = $${app_instance_secret} app_instance_uuid = $${app_instance_uuid} # Specify the database for SQLObject to use via pylons.database.PackageHub. # %(here) may include a ':' character on Windows environments; this can # invalidate the URI when specifying a SQLite db via path name. Refer to the # SQLObject documentation for a special syntax to preserve the URI. #sqlobject.dburi = sqlite:%(here)s/somedb.db # WARNING: *THE LINE BELOW MUST BE UNCOMMENTED ON A PRODUCTION ENVIRONMENT* # Debug mode will enable the interactive debugging tool, allowing ANYONE to # execute malicious code after an exception is raised. set debug = false PKhP4OZ;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 PKhP41UsD}};pylons/templates/paster_template/+package+/websetup.py_tmpldef setup_config(command, filename, section, vars): """ Place any commands to setup ${package} here. """ passPKhP4Bpylons/templates/paster_template/+package+/config/__init__.py_tmpl# PKk4R7Epylons/templates/paster_template/+package+/config/environment.py_tmplimport 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') } # 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) PKkG4Dpylons/templates/paster_template/+package+/config/middleware.py_tmplfrom paste import httpexceptions from paste.cascade import Cascade from paste.urlparser import StaticURLParser from paste.registry import RegistryManager from paste.deploy.config import ConfigMiddleware from pylons.error import error_template from pylons.middleware import ErrorHandler, ErrorDocuments, StaticJavascripts, 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.PylonsApp(config) g = app.globals app = ConfigMiddleware(app, {'app_conf':app_conf, 'global_conf':global_conf}) # 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 @@@ static_app = StaticURLParser(config.paths['static_files']) # @@@ WebHelper's static javascript files @@@ javascripts_app = StaticJavascripts() # @@@ Cascade @@@ app = Cascade([static_app, javascripts_app, app]) # @@@ Display error documents for 401, 403, 404 status codes (if debug is disabled also # intercepts 500) @@@ app = ErrorDocuments(app, global_conf, mapper=error_mapper, **app_conf) # @@@ Establish the Registry for this application @@@ app = RegistryManager(app) return app PK*U4K/ ``Apylons/templates/paster_template/+package+/config/routing.py_tmpl""" Setup your Routes options here """ import sys, os from routes 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 PKhP4Gpylons/templates/paster_template/+package+/controllers/__init__.py_tmplPKkG4|DzGttDpylons/templates/paster_template/+package+/controllers/error.py_tmplimport os.path from paste import fileapp from pylons.middleware import media_path, error_document_template from pylons.util import get_prefix from ${package}.lib.base import * 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': request.params.get('code', ''), 'message': request.params.get('message', ''), } return Response(page) def img(self, id): return self._serve_file(os.path.join(media_path, 'img', id)) def style(self, id): return self._serve_file(os.path.join(media_path, 'style', id)) def _serve_file(self, path): fapp = fileapp.FileApp(path) return fapp(request.environ, self.start_response) PKL4ؒ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): return render_response(url+'.myt') The default is just to abort the request with a 404 File not found status message. """ abort(404) PKhP4cOjAA>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``. PKhP4@pylons/templates/paster_template/+package+/i18n/__init__.py_tmplPKhP4?pylons/templates/paster_template/+package+/lib/__init__.py_tmplPKR4qv)Bpylons/templates/paster_template/+package+/lib/app_globals.py_tmplclass Globals(object): 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 PK4;pylons/templates/paster_template/+package+/lib/base.py_tmplfrom pylons import Response, c, g, h, cache, request, session from pylons.controllers import WSGIController from pylons.decorators import jsonify, rest, validate from pylons.templating import render, render_response from pylons.helpers import abort, redirect_to, etag_cache import ${package}.models as model class BaseController(WSGIController): def __call__(self, environ, start_response): # Insert any code to be run per request here. The Routes match # is under environ['pylons.routes_dict'] should you want to check # the action or route vars here return WSGIController.__call__(self, environ, start_response) PKL4C>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 * PKhP44[[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 PK4ܕApylons/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://127.0.0.1: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):
        return response('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(request.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'
        return render_response('/serverinfo.myt')
You can now view the page at: http://127.0.0.1:5000/hello/serverinfo

PKhP4`@pylons/templates/paster_template/+package+/templates/autohandler% m.call_next()PKqs4׵@Apylons/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 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'] PKhP4Dpylons/templates/paster_template/+package+/tests/test_models.py_tmplPKhP4Lpylons/templates/paster_template/+package+/tests/functional/__init__.py_tmplPKgP4tests/__init__.py# PK4z]tests/__init__.pyc; SWkDc@sdS(N((((s>build/bdist.darwin-7.9.0-Power_Macintosh/egg/tests/__init__.pys?sPKgP4?@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) PK4γ@tests/conftest.pyc; SWkDc@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-7.9.0-Power_Macintosh/egg/tests/conftest.pys?s    PKgP4tests/test_units/__init__.pyPK4tests/test_units/__init__.pyc; SWkDc@sdS(N((((sIbuild/bdist.darwin-7.9.0-Power_Macintosh/egg/tests/test_units/__init__.pys?sPK*U4`Hߝ'tests/test_webapps/test_make_project.pyimport urllib import os from paste.fixture import * import pkg_resources for spec in ['PasteScript', 'Paste', 'PasteDeploy', 'pylons']: pkg_resources.require(spec) template_path = os.path.join( os.path.dirname(__file__), 'test_files').replace('\\','/') test_environ = os.environ.copy() test_environ['PASTE_TESTING'] = 'true' testenv = TestFileEnvironment( os.path.join(os.path.dirname(__file__), 'output').replace('\\','/'), template_path=template_path, environ=test_environ) projenv = None def _get_script_name(script): if sys.platform == 'win32': script += '.exe' return script def svn_repos_setup(): res = testenv.run(_get_script_name('svnadmin'), 'create', 'REPOS', printresult=False) path = testenv.base_path.replace('\\','/').replace(' ','%20') base = 'file://' if ':' in path: base = 'file:///' testenv.svn_url = base + path + '/REPOS' assert 'REPOS' in res.files_created testenv.ignore_paths.append('REPOS') def paster_create(): global projenv sys.stderr.write(' '.join(['paster', 'create', '--verbose', '--no-interactive', '--svn-repository=' + testenv.svn_url, '--template=pylons', 'ProjectName', 'version=0.1', ])) res = testenv.run(_get_script_name('paster'), 'create', '--verbose', '--no-interactive', '--svn-repository=' + testenv.svn_url, '--template=pylons', 'ProjectName', 'version=0.1', ) expect_fn = ['projectname', 'development.ini', 'setup.cfg', 'README.txt', 'setup.py', 'ProjectName.egg-info', ] for fn in expect_fn: fn = os.path.join('ProjectName', fn) #~ if fn not in res.files_created.keys(): #~ sys.stderr.write('ERROR not creates %r'%fn) #~ if fn not in res.stdout: #~ sys.stderr.write('ERROR not in stdout %r'%fn) assert fn in res.files_created.keys() assert fn in res.stdout setup = res.files_created[os.path.join('ProjectName','setup.py')] setup.mustcontain('0.1') setup.mustcontain('projectname:make_app') setup.mustcontain('main=paste.script.appinstall:Installer') setup.mustcontain("include_package_data=True") assert '0.1' in setup testenv.run(_get_script_name('python')+' setup.py egg_info', cwd=os.path.join(testenv.cwd, 'ProjectName').replace('\\','/'), expect_stderr=True) testenv.run(_get_script_name('svn'), 'commit', '-m', 'Created project', 'ProjectName') # A new environment with a new projenv = TestFileEnvironment( os.path.join(testenv.base_path, 'ProjectName').replace('\\','/'), start_clear=False, template_path=template_path, environ=test_environ) projenv.environ['PYTHONPATH'] = ( projenv.environ.get('PYTHONPATH', '') + ':' + projenv.base_path) def make_controller(): res = projenv.run(_get_script_name('paster')+' controller sample') assert os.path.join('projectname','controllers','sample.py') in res.files_created assert os.path.join('projectname','tests','functional','test_sample.py') in res.files_created res = projenv.run(_get_script_name('svn')+' status') # Make sure all files are added to the repository: assert '?' not in res.stdout def do_pytest(): projenv.writefile('development.ini', frompath='development.ini') res = projenv.run(_get_script_name('nosetests')+' projectname/tests', expect_stderr=True, cwd=os.path.join(testenv.cwd, 'ProjectName').replace('\\','/')) def do_test_known(): projenv.writefile('projectname/controllers/sample.py', frompath='controller_sample.py') projenv.writefile('projectname/lib/app_globals.py', frompath='app_globals.py') projenv.writefile('projectname/tests/functional/test_sample.py', frompath='functional_sample_controller_sample1.py') res = projenv.run(_get_script_name('nosetests')+' projectname/tests', expect_stderr=True, cwd=os.path.join(testenv.cwd, 'ProjectName').replace('\\','/')) def do_kid_default(): projenv.writefile('projectname/kidtemplates/testkid.kid', frompath='testkid.kid') projenv.writefile('projectname/kidtemplates/__init__.py') projenv.writefile('projectname/config/middleware.py', frompath='middleware_def_engine.py') projenv.writefile('projectname/tests/functional/test_sample2.py', frompath='functional_sample_controller_sample2.py') res = projenv.run(_get_script_name('nosetests')+' projectname/tests', expect_stderr=True, cwd=os.path.join(testenv.cwd, 'ProjectName').replace('\\','/')) def do_two_engines(): projenv.writefile('projectname/config/middleware.py', frompath='middleware_two_engines.py') projenv.writefile('projectname/templates/test_myghty.myt', frompath='test_myghty.myt') projenv.writefile('projectname/tests/functional/test_sample2.py', frompath='functional_sample_controller_sample3.py') res = projenv.run(_get_script_name('nosetests')+' projectname/tests', expect_stderr=True, cwd=os.path.join(testenv.cwd, 'ProjectName').replace('\\','/')) def do_crazy_decorators(): projenv.writefile('projectname/tests/functional/test_sample3.py', frompath='functional_sample_controller_sample4.py') res = projenv.run(_get_script_name('nosetests')+' projectname/tests', expect_stderr=True, cwd=os.path.join(testenv.cwd, 'ProjectName').replace('\\','/')) def do_legacy_app(): legacyenv = TestFileEnvironment( os.path.join(testenv.base_path, 'legacyapp').replace('\\','/'), start_clear=False, template_path=template_path, environ=test_environ) res = legacyenv.run(_get_script_name('nosetests')+' legacyapp/tests', expect_stderr=True, cwd=os.path.join(testenv.cwd, 'legacyapp').replace('\\','/')) def make_tag(): global tagenv res = projenv.run(_get_script_name('svn')+' commit -m "updates"') # Space at the end needed so run() doesn't add \n causing svntag to complain res = projenv.run(_get_script_name('python')+' setup.py svntag --version=0.5 ') # XXX Still fails => setuptools problem on win32? assert 'Tagging 0.5 version' in res.stdout assert 'Auto-update of version strings' in res.stdout res = testenv.run(_get_script_name('svn')+' co %s/ProjectName/tags/0.5 Proj-05 ' % testenv.svn_url) setup = res.files_created['Proj-05/setup.py'] setup.mustcontain('0.5') assert 'Proj-05/setup.cfg' not in res.files_created tagenv = TestFileEnvironment( os.path.join(testenv.base_path, 'Proj-05').replace('\\','/'), start_clear=False, template_path=template_path) def test_project(): yield svn_repos_setup yield paster_create yield make_controller yield do_pytest yield do_test_known yield do_kid_default yield do_two_engines yield do_crazy_decorators #yield do_legacy_app #yield make_tag PK4.kM.''(tests/test_webapps/test_make_project.pyc; ADc@sGdkZdkZdkTdkZx'ddddgD]Zeieq5Weiieiie di ddZ ei i Zd ed <%init> from datetime import datetime mytime = datetime.now() PK*U4M^\\)tests/test_webapps/test_files/testkid.kid Hello from Kid

Hello from Kid

You visited the URL ${h.url_for()} at ${datetime.datetime.now()}

PK42EGG-INFO/dependency_links.txtPK4sBٕ<EGG-INFO/entry_points.txtPKQ4EGG-INFO/not-zip-safePK4+3 ;EGG-INFO/PKG-INFOPK4'J%%J EGG-INFO/requires.txtPK43nnEGG-INFO/SOURCES.txtPK4zm\ B!EGG-INFO/top_level.txtPKL4>q!pylons/__init__.pyPK4``$pylons/__init__.pycPK\4)pylons/commands.pyPK4bMH0!0!vFpylons/commands.pycPKlG4>""gpylons/config.pyPK4 pylons/config.pycPKlG4USIIëpylons/controllers.pyPK4d""?pylons/controllers.pycPK|4uzpylons/database.pyPK4 Wyypylons/database.pycPK,S4Q8lpylons/decorator.pyPK4dEI+pylons/decorator.pycPKi4H+RRGpylons/error.pyPK4@ XUXUpylons/error.pycPK4Bffpylons/helpers.pyPK4;h 6pylons/helpers.pycPKlG4z>0pylons/legacy.pyPK4ÿyyL pylons/legacy.pycPKlG47Jpylons/middleware.pyPK4C"z3"3"5pylons/middleware.pycPK#4siT*T* Xpylons/templating.pyPK4n\K3K3pylons/templating.pycPKS4)֘pylons/util.pyPK4l22pylons/util.pycPKi4׀..pylons/wsgiapp.pyPK4lb)3)3I5pylons/wsgiapp.pycPK[4N) ) hpylons/decorators/__init__.pyPK4dtpylons/decorators/__init__.pycPK*U4&pylons/decorators/rest.pyPK4@ 4pylons/decorators/rest.pycPKV4;Mpylons/i18n/__init__.pyPK4&&Npylons/i18n/__init__.pycPKN4`*pylons/i18n/msgfmt.pyPK4N]pylons/i18n/msgfmt.pycPK*U4eqZVZVupylons/i18n/pygettext.pyPK4eJ݌YY<pylons/i18n/pygettext.pycPKV4oݯȕpylons/i18n/translation.pyPK4_Xpylons/i18n/translation.pycPKhP4 opylons/media/img/bar-bg.pngPKhP46HG)G)pylons/media/img/bg.jpgPKhP41!"pylons/media/img/hatch-yellow.pngPKhP4h3%pylons/media/img/header.pngPKhP4?A4pylons/media/img/highlight.pngPKhP4tQt774pylons/media/img/icon-16.pngPKhP4H-%%pylons/media/img/logo.gifPKhP4,#pylons/media/img/main-nav-bg-on.pngPKhP4A pylons/media/img/main-nav-bg.pngPKhP4#>iiApylons/media/img/plus.jpgPKhP4Cpylons/media/img/tab-brown.pngPKhP4ǘ!pylons/media/img/tab-white.pngPKhP4XT)Bpylons/media/img/tab-yellow-highlight.pngPKhP4^Й7CCpylons/media/img/tab-yellow.pngPKhP4SO(pylons/media/img/warning.gifPKhP4;,#,#bpylons/media/style/orange.cssPKhP4pylons/templates/__init__.pyPK4?pylons/templates/paster_template/+package+/docs/index.txt_tmplPKhP4@Apylons/templates/paster_template/+package+/i18n/__init__.py_tmplPKhP4?Apylons/templates/paster_template/+package+/lib/__init__.py_tmplPKR4qv)BMBpylons/templates/paster_template/+package+/lib/app_globals.py_tmplPK4;?Gpylons/templates/paster_template/+package+/lib/base.py_tmplPKL4C>#Jpylons/templates/paster_template/+package+/lib/helpers.py_tmplPKhP44[[BKpylons/templates/paster_template/+package+/models/__init__.py_tmplPK4ܕALpylons/templates/paster_template/+package+/public/index.html_tmplPKhP4`@Upylons/templates/paster_template/+package+/templates/autohandlerPKqs4׵@AVpylons/templates/paster_template/+package+/tests/__init__.py_tmplPKhP4D@Ypylons/templates/paster_template/+package+/tests/test_models.py_tmplPKhP4LYpylons/templates/paster_template/+package+/tests/functional/__init__.py_tmplPKgP4 Ztests/__init__.pyPK4z]=Ztests/__init__.pycPKgP4?@Ztests/conftest.pyPK4γ@\tests/conftest.pycPKgP4_tests/test_units/__init__.pyPK4`tests/test_units/__init__.pycPK*U4`Hߝ'`tests/test_webapps/test_make_project.pyPK4.kM.''(~tests/test_webapps/test_make_project.pycPKR4Ln&&,tests/test_webapps/test_files/app_globals.pyPK4]-\tests/test_webapps/test_files/app_globals.pycPKL4}}2Ĭtests/test_webapps/test_files/controller_sample.pyPK4V3tests/test_webapps/test_files/controller_sample.pycPK*U4FF-tests/test_webapps/test_files/development.iniPK*U4LEtests/test_webapps/test_files/functional_sample_controller_sample1.pyPK4tm<<Ftests/test_webapps/test_files/functional_sample_controller_sample1.pycPK*U4}@Ewtests/test_webapps/test_files/functional_sample_controller_sample2.pyPK40}Fqtests/test_webapps/test_files/functional_sample_controller_sample2.pycPK[4l;GGE\tests/test_webapps/test_files/functional_sample_controller_sample3.pyPK4( SSFtests/test_webapps/test_files/functional_sample_controller_sample3.pycPK*U4"OOEtests/test_webapps/test_files/functional_sample_controller_sample4.pyPK4_s3Fotests/test_webapps/test_files/functional_sample_controller_sample4.pycPK*U4]f}}6tests/test_webapps/test_files/middleware_def_engine.pyPK4"  7Q tests/test_webapps/test_files/middleware_def_engine.pycPK*U4_^@@7tests/test_webapps/test_files/middleware_two_engines.pyPK4& 8Ttests/test_webapps/test_files/middleware_two_engines.pycPK*U4koo-(tests/test_webapps/test_files/test_myghty.mytPK*U4M^\\)S)tests/test_webapps/test_files/testkid.kidPKvv&*