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 | from __future__ import absolute_import |
||
17 | import uuid |
||
18 | |||
19 | from webob.headers import ResponseHeaders |
||
20 | |||
21 | from st2common.constants.api import REQUEST_ID_HEADER |
||
22 | from st2common.router import Request |
||
23 | |||
24 | |||
25 | class RequestIDMiddleware(object): |
||
26 | def __init__(self, app): |
||
27 | self.app = app |
||
28 | |||
29 | def __call__(self, environ, start_response): |
||
30 | # The middleware adds unique `X-Request-ID` header on the requests that don't have it and |
||
31 | # modifies the responses to have the same exact header as their request. The middleware |
||
32 | # helps us better track relation between request and response in places where it might not |
||
33 | # be immediately obvious (like logs for example). In general, you want to place this header |
||
34 | # as soon as possible to ensure it's present by the time it's needed. Certainly before |
||
35 | # LoggingMiddleware which relies on this header. |
||
36 | request = Request(environ) |
||
37 | |||
38 | if not request.headers.get(REQUEST_ID_HEADER, None): |
||
39 | req_id = str(uuid.uuid4()) |
||
40 | request.headers[REQUEST_ID_HEADER] = req_id |
||
41 | |||
42 | def custom_start_response(status, headers, exc_info=None): |
||
43 | headers = ResponseHeaders(headers) |
||
44 | |||
45 | req_id_header = request.headers.get(REQUEST_ID_HEADER, None) |
||
46 | if req_id_header: |
||
47 | headers[REQUEST_ID_HEADER] = req_id_header |
||
48 | |||
49 | return start_response(status, headers._items, exc_info) |
||
0 ignored issues
–
show
|
|||
50 | |||
51 | return self.app(environ, custom_start_response) |
||
52 |
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: