|
1
|
|
|
# Licensed to the StackStorm, Inc ('StackStorm') under one or more |
|
2
|
|
|
# contributor license agreements. See the NOTICE file distributed with |
|
3
|
|
|
# this work for additional information regarding copyright ownership. |
|
4
|
|
|
# The ASF licenses this file to You under the Apache License, Version 2.0 |
|
5
|
|
|
# (the "License"); you may not use this file except in compliance with |
|
6
|
|
|
# the License. You may obtain a copy of the License at |
|
7
|
|
|
# |
|
8
|
|
|
# http://www.apache.org/licenses/LICENSE-2.0 |
|
9
|
|
|
# |
|
10
|
|
|
# Unless required by applicable law or agreed to in writing, software |
|
11
|
|
|
# distributed under the License is distributed on an "AS IS" BASIS, |
|
12
|
|
|
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
|
13
|
|
|
# See the License for the specific language governing permissions and |
|
14
|
|
|
# limitations under the License. |
|
15
|
|
|
|
|
16
|
|
|
import uuid |
|
17
|
|
|
|
|
18
|
|
|
from webob.headers import ResponseHeaders |
|
19
|
|
|
|
|
20
|
|
|
from st2common.constants.api import REQUEST_ID_HEADER |
|
21
|
|
|
from st2common.router import Request |
|
22
|
|
|
|
|
23
|
|
|
|
|
24
|
|
|
class RequestIDMiddleware(object): |
|
25
|
|
|
def __init__(self, app): |
|
26
|
|
|
self.app = app |
|
27
|
|
|
|
|
28
|
|
|
def __call__(self, environ, start_response): |
|
29
|
|
|
request = Request(environ) |
|
30
|
|
|
|
|
31
|
|
|
if not request.headers.get(REQUEST_ID_HEADER, None): |
|
32
|
|
|
req_id = str(uuid.uuid4()) |
|
33
|
|
|
request.headers[REQUEST_ID_HEADER] = req_id |
|
34
|
|
|
|
|
35
|
|
|
def custom_start_response(status, headers, exc_info=None): |
|
36
|
|
|
headers = ResponseHeaders(headers) |
|
37
|
|
|
|
|
38
|
|
|
req_id_header = request.headers.get(REQUEST_ID_HEADER, None) |
|
39
|
|
|
if req_id_header: |
|
40
|
|
|
headers[REQUEST_ID_HEADER] = req_id_header |
|
41
|
|
|
|
|
42
|
|
|
return start_response(status, headers._items, exc_info) |
|
|
|
|
|
|
43
|
|
|
|
|
44
|
|
|
return self.app(environ, custom_start_response) |
|
45
|
|
|
|
Prefixing a member variable
_is usually regarded as the equivalent of declaring it with protected visibility that exists in other languages. Consequentially, such a member should only be accessed from the same class or a child class: