|
| 1 | +# Copyright 2016 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 | +import os |
| 16 | +from flask import Flask |
| 17 | + |
| 18 | +#to add services insert key value pair of the name of the service and |
| 19 | +#the port you want it to run on when running locally |
| 20 | +SERVICES = { |
| 21 | + 'default': 8000, |
| 22 | + 'static': 8001 |
| 23 | +} |
| 24 | + |
| 25 | +def make_app(name): |
| 26 | + app = Flask(name) |
| 27 | + environment = 'production' if os.environ.get( |
| 28 | + 'GAE_INSTANCE', os.environ.get('GAE_MODULE_INSTANCE') |
| 29 | + ) else 'development' |
| 30 | + app.config['SERVICE_MAP'] = map_services(environment) |
| 31 | + return app |
| 32 | + |
| 33 | +def map_services(environment): |
| 34 | + '''Generates a map of services to correct urls for running locally |
| 35 | + or when deployed''' |
| 36 | + url_map = {} |
| 37 | + for service, local_port in SERVICES.items(): |
| 38 | + if environment == 'production': |
| 39 | + url_map[service] = production_url(service) |
| 40 | + if environment == 'development': |
| 41 | + url_map[service] = local_url(local_port) |
| 42 | + return url_map |
| 43 | + |
| 44 | +def production_url(service_name): |
| 45 | + '''Generates url for a service when deployed to App Engine''' |
| 46 | + project_id = os.environ.get('GAE_LONG_APP_ID') |
| 47 | + project_url = '{}.appspot.com'.format(project_id) |
| 48 | + if service_name == 'default': |
| 49 | + return 'https://{}'.format(project_url) |
| 50 | + else: |
| 51 | + return 'https://{}-dot-{}'.format(service_name, project_url) |
| 52 | + |
| 53 | +def local_url(port): |
| 54 | + '''Generates url for a service when running locally''' |
| 55 | + return 'http://localhost:{}'.format(str(port)) |
0 commit comments