in main.py [0:0]
def on_post(self, req, res):
try:
import falcon
res.content_type = falcon.MEDIA_TEXT
# Check if this is an API call
context = None
event = None
using_webserver = False
if req.url[-4:] != '/api':
try:
envelope = req.media
except falcon.MediaNotFoundError:
raise NoMessageReceivedException(
'No Pub/Sub message received')
except falcon.MediaMalformedError:
raise InvalidMessageFormatException('Invalid Pub/Sub JSON')
if not isinstance(envelope, dict) or 'message' not in envelope:
raise InvalidMessageFormatException(
'Invalid Pub/Sub message format')
event = {
'data':
envelope['message']['data'],
'attributes':
envelope['message']['attributes']
if 'attributes' in envelope['message'] else {}
}
context = Context(eventId=envelope['message']['messageId'],
timestamp=envelope['message']['publishTime'])
else:
try:
envelope = req.media
except falcon.MediaNotFoundError:
raise NoMessageReceivedException('No request received')
except falcon.MediaMalformedError:
raise InvalidMessageFormatException('Invalid Pub/Sub JSON')
request_headers = req.headers
if 'authorization' in request_headers:
del request_headers['authorization']
event = {
'data':
base64.b64encode(json.dumps(envelope).encode('utf-8')),
'attributes': {
'headers': request_headers
}
}
context = Context(
timestamp=datetime.now().strftime('%Y-%m-%dT%H:%M:%SZ'))
using_webserver = True
process_pubsub(event,
context,
message_too_old_exception=True,
using_webserver=using_webserver)
if context.http_response:
res.status = context.http_response[0]
res.set_headers(context.http_response[1])
res.text = context.http_response[2]
else:
res.status = falcon.HTTP_200
res.text = 'Message processed.'
except (NoMessageReceivedException,
InvalidMessageFormatException) as me:
# Do not attempt to retry malformed messages
logger.error('%s' % (me),
extra={'exception': traceback.format_exc()})
res.status = falcon.HTTP_204
res.text = 'Bad Request: %s' % (str(me))
except MessageTooOldException as mtoe:
res.status = falcon.HTTP_202
res.text = 'Message ignored: %s' % (mtoe)
except ImportError:
logger.error(
'Falcon is required for web server mode, run: pip install falcon'
)
except Exception as e:
traceback.print_exc()
res.status = falcon.HTTP_500
res.text = 'Internal Server Error: %s' % (e)