44# you may not use this file except in compliance with the License.
55# You may obtain a copy of the License at
66#
7- # http://www.apache.org/licenses/LICENSE-2.0
7+ # http://www.apache.org/licenses/LICENSE-2.0
88#
99# Unless required by applicable law or agreed to in writing, software
1010# distributed under the License is distributed on an "AS IS" BASIS,
@@ -59,6 +59,7 @@ def list(self, request):
5959import cgi
6060import httplib
6161import json
62+ import logging
6263import os
6364
6465import api_backend_service
@@ -67,13 +68,18 @@ def list(self, request):
6768import endpoints_dispatcher
6869import protojson
6970
71+ from google .appengine .api import app_identity
72+ from google .api .control import client as control_client
73+ from google .api .control import wsgi as control_wsgi
74+
7075from protorpc import messages
7176from protorpc import remote
7277from protorpc .wsgi import service as wsgi_service
7378
7479import util
7580
7681
82+ logger = logging .getLogger (__name__ )
7783package = 'google.appengine.endpoints'
7884
7985
@@ -444,6 +450,7 @@ def api_server(api_services, **kwargs):
444450 instance for the service handlers described by the services passed in.
445451 Additionally, it registers each API in ApiConfigRegistry for later use
446452 in the BackendService.getApiConfigs() (API config enumeration service).
453+ It also configures service control.
447454
448455 Args:
449456 api_services: List of protorpc.remote.Service classes implementing the API
@@ -462,5 +469,29 @@ def api_server(api_services, **kwargs):
462469 if 'protocols' in kwargs :
463470 raise TypeError ("__init__() got an unexpected keyword argument 'protocols'" )
464471
465- return endpoints_dispatcher .EndpointsDispatcherMiddleware (
466- _ApiServer (api_services , ** kwargs ))
472+ # Construct the api serving app
473+ apis_app = _ApiServer (api_services , ** kwargs )
474+ dispatcher = endpoints_dispatcher .EndpointsDispatcherMiddleware (apis_app )
475+
476+ # Determine the service name
477+ service_name = os .environ .get ('ENDPOINTS_SERVICE_NAME' )
478+ if not service_name :
479+ logger .warn ('Did not specify the ENDPOINTS_SERVICE_NAME environment'
480+ ' variable so service control is disabled. Please specify the'
481+ ' the name of service in ENDPOINTS_SERVICE_NAME to enable it.' )
482+ return dispatcher
483+
484+
485+ # The DEFAULT 'config' should be tuned so that it's always OK for python
486+ # App Engine workloads. The config can be adjusted, but that's probably
487+ # unnecessary on App Engine.
488+ controller = control_client .Loaders .DEFAULT .load (service_name )
489+
490+ # Start the GAE background thread that powers the control client's cache.
491+ control_client .use_gae_thread ()
492+ controller .start ()
493+
494+ return control_wsgi .add_all (
495+ dispatcher ,
496+ app_identity .get_application_id (),
497+ controller )
0 commit comments