|
| 1 | +# Copyright 2015 Google Inc. All Rights Reserved. |
| 2 | +# |
| 3 | +# Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | +# you may not use this file except in compliance with the License. |
| 5 | +# You may obtain a copy of the License at |
| 6 | +# |
| 7 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | +# |
| 9 | +# Unless required by applicable law or agreed to in writing, software |
| 10 | +# distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | +# See the License for the specific language governing permissions and |
| 13 | +# limitations under the License. |
| 14 | +# |
| 15 | +"""Utilities to configure the dispatcher.""" |
| 16 | + |
| 17 | +import logging |
| 18 | +import os |
| 19 | + |
| 20 | +from google.appengine.api import appinfo_includes |
| 21 | +from google.appengine.runtime import wsgi |
| 22 | + |
| 23 | + |
| 24 | +def get_module_config_filename(): |
| 25 | + """Returns the name of the module configuration file (app.yaml).""" |
| 26 | + module_yaml_path = os.environ['MODULE_YAML_PATH'] |
| 27 | + logging.info('Using module_yaml_path from env: %s', module_yaml_path) |
| 28 | + return module_yaml_path |
| 29 | + |
| 30 | + |
| 31 | +def get_module_config(filename): |
| 32 | + """Returns the parsed module config.""" |
| 33 | + with open(filename) as f: |
| 34 | + return appinfo_includes.Parse(f) |
| 35 | + |
| 36 | + |
| 37 | +def app_for_script(script): |
| 38 | + """Returns the WSGI app specified in the input string, or None on failure.""" |
| 39 | + if script: |
| 40 | + app, filename, err = wsgi.LoadObject(script) # pylint: disable=unused-variable |
| 41 | + if err: |
| 42 | + # Log the exception but do not reraise. |
| 43 | + logging.exception('Failed to import %s: %s', script, err) |
| 44 | + return None |
| 45 | + else: |
| 46 | + return app |
| 47 | + |
| 48 | + |
| 49 | +def load_user_scripts_into_handlers(handlers): |
| 50 | + """Preloads user scripts. |
| 51 | +
|
| 52 | + Args: |
| 53 | + handlers: appinfo_external.handlers data as provided by get_module_config() |
| 54 | +
|
| 55 | + Returns: |
| 56 | + A list of tuples suitable for configuring the dispatcher() app, |
| 57 | + where the tuples are (url, script, app): |
| 58 | + - url: The url pattern which matches this handler. |
| 59 | + - script: The script to serve for this handler, as a string. |
| 60 | + - app: The fully loaded app corresponding to the script. |
| 61 | + """ |
| 62 | + loaded_handlers = [ |
| 63 | + (x.url, |
| 64 | + x.script.replace('$PYTHON_LIB/', '') if x.script else x.script, |
| 65 | + app_for_script(x.script) if x.script else None) |
| 66 | + for x in handlers] |
| 67 | + logging.info('Parsed handlers: %s', |
| 68 | + [(url, script) for (url, script, _) in loaded_handlers]) |
| 69 | + return loaded_handlers |
0 commit comments