Skip to content

Instantly share code, notes, and snippets.

@alexamies
Created December 20, 2019 18:07
Show Gist options
  • Save alexamies/8c2ee5d77985b42ebdb07ab8361da6d9 to your computer and use it in GitHub Desktop.
Save alexamies/8c2ee5d77985b42ebdb07ab8361da6d9 to your computer and use it in GitHub Desktop.
App Engine Python 2.7 with Background Thread joined after writing response

App Engine Python 2.7 with Threads

Demo os App Engine Python 2.7 with Background thread joined after writing response. Deploy to App Engine with the command:

gcloud app deploy

Browse to the app

gcloud app browse

Check the logs. Notice that you can write logs to Stackdriver after writing the response to the HTTP stream, even in a different thread.

runtime: python27
api_version: 1
threadsafe: true
handlers:
- url: /.*
script: main.app
# Copyright 2016 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import logging
import threading
import time
import webapp2
def backround_fn(name):
logging.info("Thread %s: starting", name)
time.sleep(1)
logging.info("Thread %s: finishing", name)
class MainPage(webapp2.RequestHandler):
def get(self):
logging.info('Message before creating thread')
t = threading.Thread(target=backround_fn, args=(1,))
t.start()
self.response.headers['Content-Type'] = 'text/plain'
self.response.write('Hello, World!')
logging.info('Message after writing response')
t.join()
logging.info('Message after joining thread')
app = webapp2.WSGIApplication([
('/', MainPage),
], debug=True)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment