We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
"ImportError: cannot import name 'StarletteIntegration' from 'sentry_sdk.integrations.starlette'" after sentry version update
### How do you use Sentry?

Sentry Saas (sentry.io)

### Version

1.9.7

### Steps to Reproduce

It only happens every once in a while so it is not easy to reproduce.

Here is my `sentry.py` (see exception trace below):

```
import functools
import inspect
import os
from typing import Callable

import sentry_sdk

from archimedes_data_fetcher.config import config


def initialize():
    """Initializes sentry"""
    sentry_sdk.init(
        config.get("SENTRY_DSN"),
        environment=config.get("ENVIRONMENT"),
    )
...
...
...
```

Here is the output of `pip list` on the failing container:

```
Package                 Version
----------------------- ---------
affine                  2.3.1
archimedes-data-fetcher 0.5.19
archimedes-flow-utils   1.0.2
attrs                   22.1.0
azure-core              1.25.1
azure-storage-blob      12.13.1
cachetools              5.2.0
certifi                 2022.6.15
cffi                    1.15.1
cftime                  1.6.1
charset-normalizer      2.1.1
click                   8.1.3
click-plugins           1.1.1
cligj                   0.7.2
cloudpickle             2.1.0
croniter                1.3.5
cryptography            37.0.4
dask                    2022.8.1
datadog                 0.44.0
datadog-api-client      2.3.0
distributed             2022.8.1
docker                  6.0.0
fsspec                  2022.8.2
gitdb                   4.0.9
GitPython               3.1.27
HeapDict                1.0.1
idna                    3.3
importlib-resources     5.9.0
investpy                1.0.8
isodate                 0.6.1
Jinja2                  3.1.2
locket                  1.0.0
lxml                    4.9.1
MarkupSafe              2.1.1
marshmallow             3.17.1
marshmallow-oneofschema 3.0.1
minio                   7.1.11
msgpack                 1.0.4
msrest                  0.7.1
mypy-extensions         0.4.3
netCDF4                 1.6.0
numpy                   1.23.2
oauthlib                3.2.0
packaging               21.3
pandas                  1.4.4
partd                   1.3.0
pendulum                2.1.2
pip                     22.2.2
prefect                 1.3.0
psutil                  5.9.1
psycopg                 3.1
pycparser               2.21
pyparsing               3.0.9
pyproj                  3.3.1
python-box              6.0.2
python-dateutil         2.8.2
python-dotenv           0.20.0
python-slugify          6.1.2
pytz                    2022.2.1
pytzdata                2020.1
PyYAML                  6.0
rasterio                1.3.2
requests                2.28.1
requests-oauthlib       1.3.1
rioxarray               0.10.3
sentry-sdk              1.9.7
setuptools              65.3.0
six                     1.16.0
smmap                   5.0.0
snuggs                  1.4.7
sortedcontainers        2.4.0
tabulate                0.8.10
tblib                   1.7.0
text-unidecode          1.3
toml                    0.10.2
toolz                   0.12.0
tornado                 6.1
typing_extensions       4.3.0
Unidecode               1.3.4
urllib3                 1.26.12
websocket-client        1.4.0
wheel                   0.37.1
xarray                  2022.6.0
zict                    2.2.0
zipp                    3.8.1
```

This has not happened when I pin `sentry-sdk` version to `1.9.5`, so I think it must have been introduced in either `1.9.6` or `1.9.7`.

### Expected Result

No crash on sentry initialization.

### Actual Result

```
Task 'store[1]': Exception encountered during task execution!
Traceback (most recent call last):
  File "/app/.venv/lib/python3.9/site-packages/prefect/engine/task_runner.py", line 880, in get_task_run_state
    value = prefect.utilities.executors.run_task_with_timeout(
  File "/app/.venv/lib/python3.9/site-packages/prefect/utilities/executors.py", line 468, in run_task_with_timeout
    return task.run(*args, **kwargs)  # type: ignore
  File "/home/runner/work/archimedes-data-fetcher/archimedes-data-fetcher/archimedes_data_fetcher/sentry.py", line 36, in wrapper
  File "/app/archimedes_data_fetcher/sentry.py", line 13, in initialize
    sentry_sdk.init(
  File "/app/.venv/lib/python3.9/site-packages/sentry_sdk/hub.py", line 119, in _init
    client = Client(*args, **kwargs)  # type: ignore
  File "/app/.venv/lib/python3.9/site-packages/sentry_sdk/client.py", line 89, in __init__
    self._init_impl()
  File "/app/.venv/lib/python3.9/site-packages/sentry_sdk/client.py", line 123, in _init_impl
    self.integrations = setup_integrations(
  File "/app/.venv/lib/python3.9/site-packages/sentry_sdk/integrations/__init__.py", line 109, in setup_integrations
    for integration_cls in iter_default_integrations(
  File "/app/.venv/lib/python3.9/site-packages/sentry_sdk/integrations/__init__.py", line 41, in iter_default_integrations
    yield getattr(import_module(module), cls)
  File "/usr/local/lib/python3.9/importlib/__init__.py", line 127, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
  File "<frozen importlib._bootstrap>", line 1030, in _gcd_import
  File "<frozen importlib._bootstrap>", line 1007, in _find_and_load
  File "<frozen importlib._bootstrap>", line 986, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 680, in _load_unlocked
  File "<frozen importlib._bootstrap_external>", line 850, in exec_module
  File "<frozen importlib._bootstrap>", line 228, in _call_with_frames_removed
  File "/app/.venv/lib/python3.9/site-packages/sentry_sdk/integrations/fastapi.py", line 4, in <module>
    from sentry_sdk.integrations.starlette import (
ImportError: cannot import name 'StarletteIntegration' from 'sentry_sdk.integrations.starlette' (/app/.venv/lib/python3.9/site-packages/sentry_sdk/integrations/starlette.py)
```


--- END ISSUE ---

Below are some code segments, each from a relevant file. One or more of these files may contain bugs.
--- BEGIN FILES ---
Path: `sentry_sdk/integrations/fastapi.py`
Content:
```
1 import asyncio
2 
3 from sentry_sdk._types import MYPY
4 from sentry_sdk.hub import Hub, _should_send_default_pii
5 from sentry_sdk.integrations import DidNotEnable
6 from sentry_sdk.integrations.starlette import (
7     StarletteIntegration,
8     StarletteRequestExtractor,
9 )
10 from sentry_sdk.tracing import SOURCE_FOR_STYLE, TRANSACTION_SOURCE_ROUTE
11 from sentry_sdk.utils import transaction_from_function
12 
13 if MYPY:
14     from typing import Any, Callable, Dict
15 
16     from sentry_sdk.scope import Scope
17 
18 try:
19     import fastapi  # type: ignore
20 except ImportError:
21     raise DidNotEnable("FastAPI is not installed")
22 
23 
24 _DEFAULT_TRANSACTION_NAME = "generic FastAPI request"
25 
26 
27 class FastApiIntegration(StarletteIntegration):
28     identifier = "fastapi"
29 
30     @staticmethod
31     def setup_once():
32         # type: () -> None
33         patch_get_request_handler()
34 
35 
36 def _set_transaction_name_and_source(scope, transaction_style, request):
37     # type: (Scope, str, Any) -> None
38     name = ""
39 
40     if transaction_style == "endpoint":
41         endpoint = request.scope.get("endpoint")
42         if endpoint:
43             name = transaction_from_function(endpoint) or ""
44 
45     elif transaction_style == "url":
46         route = request.scope.get("route")
47         if route:
48             path = getattr(route, "path", None)
49             if path is not None:
50                 name = path
51 
52     if not name:
53         name = _DEFAULT_TRANSACTION_NAME
54         source = TRANSACTION_SOURCE_ROUTE
55     else:
56         source = SOURCE_FOR_STYLE[transaction_style]
57 
58     scope.set_transaction_name(name, source=source)
59 
60 
61 def patch_get_request_handler():
62     # type: () -> None
63     old_get_request_handler = fastapi.routing.get_request_handler
64 
65     def _sentry_get_request_handler(*args, **kwargs):
66         # type: (*Any, **Any) -> Any
67         dependant = kwargs.get("dependant")
68         if (
69             dependant
70             and dependant.call is not None
71             and not asyncio.iscoroutinefunction(dependant.call)
72         ):
73             old_call = dependant.call
74 
75             def _sentry_call(*args, **kwargs):
76                 # type: (*Any, **Any) -> Any
77                 hub = Hub.current
78                 with hub.configure_scope() as sentry_scope:
79                     if sentry_scope.profile is not None:
80                         sentry_scope.profile.update_active_thread_id()
81                     return old_call(*args, **kwargs)
82 
83             dependant.call = _sentry_call
84 
85         old_app = old_get_request_handler(*args, **kwargs)
86 
87         async def _sentry_app(*args, **kwargs):
88             # type: (*Any, **Any) -> Any
89             hub = Hub.current
90             integration = hub.get_integration(FastApiIntegration)
91             if integration is None:
92                 return await old_app(*args, **kwargs)
93 
94             with hub.configure_scope() as sentry_scope:
95                 request = args[0]
96 
97                 _set_transaction_name_and_source(
98                     sentry_scope, integration.transaction_style, request
99                 )
100 
101                 extractor = StarletteRequestExtractor(request)
102                 info = await extractor.extract_request_info()
103 
104                 def _make_request_event_processor(req, integration):
105                     # type: (Any, Any) -> Callable[[Dict[str, Any], Dict[str, Any]], Dict[str, Any]]
106                     def event_processor(event, hint):
107                         # type: (Dict[str, Any], Dict[str, Any]) -> Dict[str, Any]
108 
109                         # Extract information from request
110                         request_info = event.get("request", {})
111                         if info:
112                             if "cookies" in info and _should_send_default_pii():
113                                 request_info["cookies"] = info["cookies"]
114                             if "data" in info:
115                                 request_info["data"] = info["data"]
116                         event["request"] = request_info
117 
118                         return event
119 
120                     return event_processor
121 
122                 sentry_scope._name = FastApiIntegration.identifier
123                 sentry_scope.add_event_processor(
124                     _make_request_event_processor(request, integration)
125                 )
126 
127             return await old_app(*args, **kwargs)
128 
129         return _sentry_app
130 
131     fastapi.routing.get_request_handler = _sentry_get_request_handler
132
```
--- END FILES ---

Please first localize the bug based on the issue statement, and then generate a patch according to the `git diff` format fenced by three backticks.

Here is an example:

```diff
diff --git a/examples/server_async.py b/examples/server_async.py
--- a/examples/server_async.py
+++ b/examples/server_async.py
@@ -313,4 +313,4 @@
 
 
 if __name__ == "__main__":
-    asyncio.run(run_async_server("."), debug=True)
+    asyncio.run(run_async_server(), debug=True)
diff --git a/examples/server_sync.py b/examples/server_sync.py
--- a/examples/server_sync.py
+++ b/examples/server_sync.py
@@ -313,5 +313,5 @@
 
 
 if __name__ == "__main__":
-    server = run_sync_server(".")
+    server = run_sync_server()
     server.shutdown()

```

diff --git a/sentry_sdk/integrations/fastapi.py b/sentry_sdk/integrations/fastapi.py
--- a/sentry_sdk/integrations/fastapi.py
+++ b/sentry_sdk/integrations/fastapi.py
@@ -3,18 +3,21 @@
 from sentry_sdk._types import MYPY
 from sentry_sdk.hub import Hub, _should_send_default_pii
 from sentry_sdk.integrations import DidNotEnable
-from sentry_sdk.integrations.starlette import (
-    StarletteIntegration,
-    StarletteRequestExtractor,
-)
 from sentry_sdk.tracing import SOURCE_FOR_STYLE, TRANSACTION_SOURCE_ROUTE
 from sentry_sdk.utils import transaction_from_function
 
 if MYPY:
     from typing import Any, Callable, Dict
-
     from sentry_sdk.scope import Scope
 
+try:
+    from sentry_sdk.integrations.starlette import (
+        StarletteIntegration,
+        StarletteRequestExtractor,
+    )
+except DidNotEnable:
+    raise DidNotEnable("Starlette is not installed")
+
 try:
     import fastapi  # type: ignore
 except ImportError:

{"golden_diff": "diff --git a/sentry_sdk/integrations/fastapi.py b/sentry_sdk/integrations/fastapi.py\n--- a/sentry_sdk/integrations/fastapi.py\n+++ b/sentry_sdk/integrations/fastapi.py\n@@ -3,18 +3,21 @@\n from sentry_sdk._types import MYPY\n from sentry_sdk.hub import Hub, _should_send_default_pii\n from sentry_sdk.integrations import DidNotEnable\n-from sentry_sdk.integrations.starlette import (\n-    StarletteIntegration,\n-    StarletteRequestExtractor,\n-)\n from sentry_sdk.tracing import SOURCE_FOR_STYLE, TRANSACTION_SOURCE_ROUTE\n from sentry_sdk.utils import transaction_from_function\n \n if MYPY:\n     from typing import Any, Callable, Dict\n-\n     from sentry_sdk.scope import Scope\n \n+try:\n+    from sentry_sdk.integrations.starlette import (\n+        StarletteIntegration,\n+        StarletteRequestExtractor,\n+    )\n+except DidNotEnable:\n+    raise DidNotEnable(\"Starlette is not installed\")\n+\n try:\n     import fastapi  # type: ignore\n except ImportError:\n", "issue": "\"ImportError: cannot import name 'StarletteIntegration' from 'sentry_sdk.integrations.starlette'\" after sentry version update\n### How do you use Sentry?\r\n\r\nSentry Saas (sentry.io)\r\n\r\n### Version\r\n\r\n1.9.7\r\n\r\n### Steps to Reproduce\r\n\r\nIt only happens every once in a while so it is not easy to reproduce.\r\n\r\nHere is my `sentry.py` (see exception trace below):\r\n\r\n```\r\nimport functools\r\nimport inspect\r\nimport os\r\nfrom typing import Callable\r\n\r\nimport sentry_sdk\r\n\r\nfrom archimedes_data_fetcher.config import config\r\n\r\n\r\ndef initialize():\r\n    \"\"\"Initializes sentry\"\"\"\r\n    sentry_sdk.init(\r\n        config.get(\"SENTRY_DSN\"),\r\n        environment=config.get(\"ENVIRONMENT\"),\r\n    )\r\n...\r\n...\r\n...\r\n```\r\n\r\nHere is the output of `pip list` on the failing container:\r\n\r\n```\r\nPackage                 Version\r\n----------------------- ---------\r\naffine                  2.3.1\r\narchimedes-data-fetcher 0.5.19\r\narchimedes-flow-utils   1.0.2\r\nattrs                   22.1.0\r\nazure-core              1.25.1\r\nazure-storage-blob      12.13.1\r\ncachetools              5.2.0\r\ncertifi                 2022.6.15\r\ncffi                    1.15.1\r\ncftime                  1.6.1\r\ncharset-normalizer      2.1.1\r\nclick                   8.1.3\r\nclick-plugins           1.1.1\r\ncligj                   0.7.2\r\ncloudpickle             2.1.0\r\ncroniter                1.3.5\r\ncryptography            37.0.4\r\ndask                    2022.8.1\r\ndatadog                 0.44.0\r\ndatadog-api-client      2.3.0\r\ndistributed             2022.8.1\r\ndocker                  6.0.0\r\nfsspec                  2022.8.2\r\ngitdb                   4.0.9\r\nGitPython               3.1.27\r\nHeapDict                1.0.1\r\nidna                    3.3\r\nimportlib-resources     5.9.0\r\ninvestpy                1.0.8\r\nisodate                 0.6.1\r\nJinja2                  3.1.2\r\nlocket                  1.0.0\r\nlxml                    4.9.1\r\nMarkupSafe              2.1.1\r\nmarshmallow             3.17.1\r\nmarshmallow-oneofschema 3.0.1\r\nminio                   7.1.11\r\nmsgpack                 1.0.4\r\nmsrest                  0.7.1\r\nmypy-extensions         0.4.3\r\nnetCDF4                 1.6.0\r\nnumpy                   1.23.2\r\noauthlib                3.2.0\r\npackaging               21.3\r\npandas                  1.4.4\r\npartd                   1.3.0\r\npendulum                2.1.2\r\npip                     22.2.2\r\nprefect                 1.3.0\r\npsutil                  5.9.1\r\npsycopg                 3.1\r\npycparser               2.21\r\npyparsing               3.0.9\r\npyproj                  3.3.1\r\npython-box              6.0.2\r\npython-dateutil         2.8.2\r\npython-dotenv           0.20.0\r\npython-slugify          6.1.2\r\npytz                    2022.2.1\r\npytzdata                2020.1\r\nPyYAML                  6.0\r\nrasterio                1.3.2\r\nrequests                2.28.1\r\nrequests-oauthlib       1.3.1\r\nrioxarray               0.10.3\r\nsentry-sdk              1.9.7\r\nsetuptools              65.3.0\r\nsix                     1.16.0\r\nsmmap                   5.0.0\r\nsnuggs                  1.4.7\r\nsortedcontainers        2.4.0\r\ntabulate                0.8.10\r\ntblib                   1.7.0\r\ntext-unidecode          1.3\r\ntoml                    0.10.2\r\ntoolz                   0.12.0\r\ntornado                 6.1\r\ntyping_extensions       4.3.0\r\nUnidecode               1.3.4\r\nurllib3                 1.26.12\r\nwebsocket-client        1.4.0\r\nwheel                   0.37.1\r\nxarray                  2022.6.0\r\nzict                    2.2.0\r\nzipp                    3.8.1\r\n```\r\n\r\nThis has not happened when I pin `sentry-sdk` version to `1.9.5`, so I think it must have been introduced in either `1.9.6` or `1.9.7`.\r\n\r\n### Expected Result\r\n\r\nNo crash on sentry initialization.\r\n\r\n### Actual Result\r\n\r\n```\r\nTask 'store[1]': Exception encountered during task execution!\r\nTraceback (most recent call last):\r\n  File \"/app/.venv/lib/python3.9/site-packages/prefect/engine/task_runner.py\", line 880, in get_task_run_state\r\n    value = prefect.utilities.executors.run_task_with_timeout(\r\n  File \"/app/.venv/lib/python3.9/site-packages/prefect/utilities/executors.py\", line 468, in run_task_with_timeout\r\n    return task.run(*args, **kwargs)  # type: ignore\r\n  File \"/home/runner/work/archimedes-data-fetcher/archimedes-data-fetcher/archimedes_data_fetcher/sentry.py\", line 36, in wrapper\r\n  File \"/app/archimedes_data_fetcher/sentry.py\", line 13, in initialize\r\n    sentry_sdk.init(\r\n  File \"/app/.venv/lib/python3.9/site-packages/sentry_sdk/hub.py\", line 119, in _init\r\n    client = Client(*args, **kwargs)  # type: ignore\r\n  File \"/app/.venv/lib/python3.9/site-packages/sentry_sdk/client.py\", line 89, in __init__\r\n    self._init_impl()\r\n  File \"/app/.venv/lib/python3.9/site-packages/sentry_sdk/client.py\", line 123, in _init_impl\r\n    self.integrations = setup_integrations(\r\n  File \"/app/.venv/lib/python3.9/site-packages/sentry_sdk/integrations/__init__.py\", line 109, in setup_integrations\r\n    for integration_cls in iter_default_integrations(\r\n  File \"/app/.venv/lib/python3.9/site-packages/sentry_sdk/integrations/__init__.py\", line 41, in iter_default_integrations\r\n    yield getattr(import_module(module), cls)\r\n  File \"/usr/local/lib/python3.9/importlib/__init__.py\", line 127, in import_module\r\n    return _bootstrap._gcd_import(name[level:], package, level)\r\n  File \"<frozen importlib._bootstrap>\", line 1030, in _gcd_import\r\n  File \"<frozen importlib._bootstrap>\", line 1007, in _find_and_load\r\n  File \"<frozen importlib._bootstrap>\", line 986, in _find_and_load_unlocked\r\n  File \"<frozen importlib._bootstrap>\", line 680, in _load_unlocked\r\n  File \"<frozen importlib._bootstrap_external>\", line 850, in exec_module\r\n  File \"<frozen importlib._bootstrap>\", line 228, in _call_with_frames_removed\r\n  File \"/app/.venv/lib/python3.9/site-packages/sentry_sdk/integrations/fastapi.py\", line 4, in <module>\r\n    from sentry_sdk.integrations.starlette import (\r\nImportError: cannot import name 'StarletteIntegration' from 'sentry_sdk.integrations.starlette' (/app/.venv/lib/python3.9/site-packages/sentry_sdk/integrations/starlette.py)\r\n```\r\n\n", "before_files": [{"content": "import asyncio\n\nfrom sentry_sdk._types import MYPY\nfrom sentry_sdk.hub import Hub, _should_send_default_pii\nfrom sentry_sdk.integrations import DidNotEnable\nfrom sentry_sdk.integrations.starlette import (\n    StarletteIntegration,\n    StarletteRequestExtractor,\n)\nfrom sentry_sdk.tracing import SOURCE_FOR_STYLE, TRANSACTION_SOURCE_ROUTE\nfrom sentry_sdk.utils import transaction_from_function\n\nif MYPY:\n    from typing import Any, Callable, Dict\n\n    from sentry_sdk.scope import Scope\n\ntry:\n    import fastapi  # type: ignore\nexcept ImportError:\n    raise DidNotEnable(\"FastAPI is not installed\")\n\n\n_DEFAULT_TRANSACTION_NAME = \"generic FastAPI request\"\n\n\nclass FastApiIntegration(StarletteIntegration):\n    identifier = \"fastapi\"\n\n    @staticmethod\n    def setup_once():\n        # type: () -> None\n        patch_get_request_handler()\n\n\ndef _set_transaction_name_and_source(scope, transaction_style, request):\n    # type: (Scope, str, Any) -> None\n    name = \"\"\n\n    if transaction_style == \"endpoint\":\n        endpoint = request.scope.get(\"endpoint\")\n        if endpoint:\n            name = transaction_from_function(endpoint) or \"\"\n\n    elif transaction_style == \"url\":\n        route = request.scope.get(\"route\")\n        if route:\n            path = getattr(route, \"path\", None)\n            if path is not None:\n                name = path\n\n    if not name:\n        name = _DEFAULT_TRANSACTION_NAME\n        source = TRANSACTION_SOURCE_ROUTE\n    else:\n        source = SOURCE_FOR_STYLE[transaction_style]\n\n    scope.set_transaction_name(name, source=source)\n\n\ndef patch_get_request_handler():\n    # type: () -> None\n    old_get_request_handler = fastapi.routing.get_request_handler\n\n    def _sentry_get_request_handler(*args, **kwargs):\n        # type: (*Any, **Any) -> Any\n        dependant = kwargs.get(\"dependant\")\n        if (\n            dependant\n            and dependant.call is not None\n            and not asyncio.iscoroutinefunction(dependant.call)\n        ):\n            old_call = dependant.call\n\n            def _sentry_call(*args, **kwargs):\n                # type: (*Any, **Any) -> Any\n                hub = Hub.current\n                with hub.configure_scope() as sentry_scope:\n                    if sentry_scope.profile is not None:\n                        sentry_scope.profile.update_active_thread_id()\n                    return old_call(*args, **kwargs)\n\n            dependant.call = _sentry_call\n\n        old_app = old_get_request_handler(*args, **kwargs)\n\n        async def _sentry_app(*args, **kwargs):\n            # type: (*Any, **Any) -> Any\n            hub = Hub.current\n            integration = hub.get_integration(FastApiIntegration)\n            if integration is None:\n                return await old_app(*args, **kwargs)\n\n            with hub.configure_scope() as sentry_scope:\n                request = args[0]\n\n                _set_transaction_name_and_source(\n                    sentry_scope, integration.transaction_style, request\n                )\n\n                extractor = StarletteRequestExtractor(request)\n                info = await extractor.extract_request_info()\n\n                def _make_request_event_processor(req, integration):\n                    # type: (Any, Any) -> Callable[[Dict[str, Any], Dict[str, Any]], Dict[str, Any]]\n                    def event_processor(event, hint):\n                        # type: (Dict[str, Any], Dict[str, Any]) -> Dict[str, Any]\n\n                        # Extract information from request\n                        request_info = event.get(\"request\", {})\n                        if info:\n                            if \"cookies\" in info and _should_send_default_pii():\n                                request_info[\"cookies\"] = info[\"cookies\"]\n                            if \"data\" in info:\n                                request_info[\"data\"] = info[\"data\"]\n                        event[\"request\"] = request_info\n\n                        return event\n\n                    return event_processor\n\n                sentry_scope._name = FastApiIntegration.identifier\n                sentry_scope.add_event_processor(\n                    _make_request_event_processor(request, integration)\n                )\n\n            return await old_app(*args, **kwargs)\n\n        return _sentry_app\n\n    fastapi.routing.get_request_handler = _sentry_get_request_handler\n", "path": "sentry_sdk/integrations/fastapi.py"}], "after_files": [{"content": "import asyncio\n\nfrom sentry_sdk._types import MYPY\nfrom sentry_sdk.hub import Hub, _should_send_default_pii\nfrom sentry_sdk.integrations import DidNotEnable\nfrom sentry_sdk.tracing import SOURCE_FOR_STYLE, TRANSACTION_SOURCE_ROUTE\nfrom sentry_sdk.utils import transaction_from_function\n\nif MYPY:\n    from typing import Any, Callable, Dict\n    from sentry_sdk.scope import Scope\n\ntry:\n    from sentry_sdk.integrations.starlette import (\n        StarletteIntegration,\n        StarletteRequestExtractor,\n    )\nexcept DidNotEnable:\n    raise DidNotEnable(\"Starlette is not installed\")\n\ntry:\n    import fastapi  # type: ignore\nexcept ImportError:\n    raise DidNotEnable(\"FastAPI is not installed\")\n\n\n_DEFAULT_TRANSACTION_NAME = \"generic FastAPI request\"\n\n\nclass FastApiIntegration(StarletteIntegration):\n    identifier = \"fastapi\"\n\n    @staticmethod\n    def setup_once():\n        # type: () -> None\n        patch_get_request_handler()\n\n\ndef _set_transaction_name_and_source(scope, transaction_style, request):\n    # type: (Scope, str, Any) -> None\n    name = \"\"\n\n    if transaction_style == \"endpoint\":\n        endpoint = request.scope.get(\"endpoint\")\n        if endpoint:\n            name = transaction_from_function(endpoint) or \"\"\n\n    elif transaction_style == \"url\":\n        route = request.scope.get(\"route\")\n        if route:\n            path = getattr(route, \"path\", None)\n            if path is not None:\n                name = path\n\n    if not name:\n        name = _DEFAULT_TRANSACTION_NAME\n        source = TRANSACTION_SOURCE_ROUTE\n    else:\n        source = SOURCE_FOR_STYLE[transaction_style]\n\n    scope.set_transaction_name(name, source=source)\n\n\ndef patch_get_request_handler():\n    # type: () -> None\n    old_get_request_handler = fastapi.routing.get_request_handler\n\n    def _sentry_get_request_handler(*args, **kwargs):\n        # type: (*Any, **Any) -> Any\n        dependant = kwargs.get(\"dependant\")\n        if (\n            dependant\n            and dependant.call is not None\n            and not asyncio.iscoroutinefunction(dependant.call)\n        ):\n            old_call = dependant.call\n\n            def _sentry_call(*args, **kwargs):\n                # type: (*Any, **Any) -> Any\n                hub = Hub.current\n                with hub.configure_scope() as sentry_scope:\n                    if sentry_scope.profile is not None:\n                        sentry_scope.profile.update_active_thread_id()\n                    return old_call(*args, **kwargs)\n\n            dependant.call = _sentry_call\n\n        old_app = old_get_request_handler(*args, **kwargs)\n\n        async def _sentry_app(*args, **kwargs):\n            # type: (*Any, **Any) -> Any\n            hub = Hub.current\n            integration = hub.get_integration(FastApiIntegration)\n            if integration is None:\n                return await old_app(*args, **kwargs)\n\n            with hub.configure_scope() as sentry_scope:\n                request = args[0]\n\n                _set_transaction_name_and_source(\n                    sentry_scope, integration.transaction_style, request\n                )\n\n                extractor = StarletteRequestExtractor(request)\n                info = await extractor.extract_request_info()\n\n                def _make_request_event_processor(req, integration):\n                    # type: (Any, Any) -> Callable[[Dict[str, Any], Dict[str, Any]], Dict[str, Any]]\n                    def event_processor(event, hint):\n                        # type: (Dict[str, Any], Dict[str, Any]) -> Dict[str, Any]\n\n                        # Extract information from request\n                        request_info = event.get(\"request\", {})\n                        if info:\n                            if \"cookies\" in info and _should_send_default_pii():\n                                request_info[\"cookies\"] = info[\"cookies\"]\n                            if \"data\" in info:\n                                request_info[\"data\"] = info[\"data\"]\n                        event[\"request\"] = request_info\n\n                        return event\n\n                    return event_processor\n\n                sentry_scope._name = FastApiIntegration.identifier\n                sentry_scope.add_event_processor(\n                    _make_request_event_processor(request, integration)\n                )\n\n            return await old_app(*args, **kwargs)\n\n        return _sentry_app\n\n    fastapi.routing.get_request_handler = _sentry_get_request_handler\n", "path": "sentry_sdk/integrations/fastapi.py"}]}