We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
FORWARDED_ALLOW_IPS cannot be loaded from ENV
The following two lines together makes impossible to read `FORWARDED_ALLOW_IPS` from env variable.

https://github.com/encode/uvicorn/blob/4da64be4335ba50e43d7ac8c3b5535460a9c1594/uvicorn/config.py#L160
https://github.com/encode/uvicorn/blob/4da64be4335ba50e43d7ac8c3b5535460a9c1594/uvicorn/config.py#L193

--- END ISSUE ---

Below are some code segments, each from a relevant file. One or more of these files may contain bugs.
--- BEGIN FILES ---
Path: `uvicorn/config.py`
Content:
```
1 import asyncio
2 import inspect
3 import logging
4 import logging.config
5 import os
6 import socket
7 import ssl
8 import sys
9 from typing import List, Tuple
10 
11 import click
12 
13 from uvicorn.importer import ImportFromStringError, import_from_string
14 from uvicorn.middleware.asgi2 import ASGI2Middleware
15 from uvicorn.middleware.debug import DebugMiddleware
16 from uvicorn.middleware.message_logger import MessageLoggerMiddleware
17 from uvicorn.middleware.proxy_headers import ProxyHeadersMiddleware
18 from uvicorn.middleware.wsgi import WSGIMiddleware
19 
20 TRACE_LOG_LEVEL = 5
21 
22 LOG_LEVELS = {
23     "critical": logging.CRITICAL,
24     "error": logging.ERROR,
25     "warning": logging.WARNING,
26     "info": logging.INFO,
27     "debug": logging.DEBUG,
28     "trace": TRACE_LOG_LEVEL,
29 }
30 HTTP_PROTOCOLS = {
31     "auto": "uvicorn.protocols.http.auto:AutoHTTPProtocol",
32     "h11": "uvicorn.protocols.http.h11_impl:H11Protocol",
33     "httptools": "uvicorn.protocols.http.httptools_impl:HttpToolsProtocol",
34 }
35 WS_PROTOCOLS = {
36     "auto": "uvicorn.protocols.websockets.auto:AutoWebSocketsProtocol",
37     "none": None,
38     "websockets": "uvicorn.protocols.websockets.websockets_impl:WebSocketProtocol",
39     "wsproto": "uvicorn.protocols.websockets.wsproto_impl:WSProtocol",
40 }
41 LIFESPAN = {
42     "auto": "uvicorn.lifespan.on:LifespanOn",
43     "on": "uvicorn.lifespan.on:LifespanOn",
44     "off": "uvicorn.lifespan.off:LifespanOff",
45 }
46 LOOP_SETUPS = {
47     "none": None,
48     "auto": "uvicorn.loops.auto:auto_loop_setup",
49     "asyncio": "uvicorn.loops.asyncio:asyncio_setup",
50     "uvloop": "uvicorn.loops.uvloop:uvloop_setup",
51     "iocp": "uvicorn.loops.iocp:iocp_setup",
52 }
53 INTERFACES = ["auto", "asgi3", "asgi2", "wsgi"]
54 
55 
56 # Fallback to 'ssl.PROTOCOL_SSLv23' in order to support Python < 3.5.3.
57 SSL_PROTOCOL_VERSION = getattr(ssl, "PROTOCOL_TLS", ssl.PROTOCOL_SSLv23)
58 
59 
60 LOGGING_CONFIG = {
61     "version": 1,
62     "disable_existing_loggers": False,
63     "formatters": {
64         "default": {
65             "()": "uvicorn.logging.DefaultFormatter",
66             "fmt": "%(levelprefix)s %(message)s",
67         },
68         "access": {
69             "()": "uvicorn.logging.AccessFormatter",
70             "fmt": '%(levelprefix)s %(client_addr)s - "%(request_line)s" %(status_code)s',
71         },
72     },
73     "handlers": {
74         "default": {
75             "formatter": "default",
76             "class": "logging.StreamHandler",
77             "stream": "ext://sys.stderr",
78         },
79         "access": {
80             "formatter": "access",
81             "class": "logging.StreamHandler",
82             "stream": "ext://sys.stdout",
83         },
84     },
85     "loggers": {
86         "": {"handlers": ["default"], "level": "INFO"},
87         "uvicorn.error": {"level": "INFO"},
88         "uvicorn.access": {"handlers": ["access"], "level": "INFO", "propagate": False},
89     },
90 }
91 
92 logger = logging.getLogger("uvicorn.error")
93 
94 
95 def create_ssl_context(certfile, keyfile, ssl_version, cert_reqs, ca_certs, ciphers):
96     ctx = ssl.SSLContext(ssl_version)
97     ctx.load_cert_chain(certfile, keyfile)
98     ctx.verify_mode = cert_reqs
99     if ca_certs:
100         ctx.load_verify_locations(ca_certs)
101     if ciphers:
102         ctx.set_ciphers(ciphers)
103     return ctx
104 
105 
106 class Config:
107     def __init__(
108         self,
109         app,
110         host="127.0.0.1",
111         port=8000,
112         uds=None,
113         fd=None,
114         loop="auto",
115         http="auto",
116         ws="auto",
117         lifespan="auto",
118         env_file=None,
119         log_config=LOGGING_CONFIG,
120         log_level=None,
121         access_log=True,
122         interface="auto",
123         debug=False,
124         reload=False,
125         reload_dirs=None,
126         workers=None,
127         proxy_headers=True,
128         forwarded_allow_ips=None,
129         root_path="",
130         limit_concurrency=None,
131         limit_max_requests=None,
132         timeout_keep_alive=5,
133         timeout_notify=30,
134         callback_notify=None,
135         ssl_keyfile=None,
136         ssl_certfile=None,
137         ssl_version=SSL_PROTOCOL_VERSION,
138         ssl_cert_reqs=ssl.CERT_NONE,
139         ssl_ca_certs=None,
140         ssl_ciphers="TLSv1",
141         headers=None,
142     ):
143         self.app = app
144         self.host = host
145         self.port = port
146         self.uds = uds
147         self.fd = fd
148         self.loop = loop
149         self.http = http
150         self.ws = ws
151         self.lifespan = lifespan
152         self.log_config = log_config
153         self.log_level = log_level
154         self.access_log = access_log
155         self.interface = interface
156         self.debug = debug
157         self.reload = reload
158         self.workers = workers or 1
159         self.proxy_headers = proxy_headers
160         self.forwarded_allow_ips = forwarded_allow_ips or "127.0.0.1"
161         self.root_path = root_path
162         self.limit_concurrency = limit_concurrency
163         self.limit_max_requests = limit_max_requests
164         self.timeout_keep_alive = timeout_keep_alive
165         self.timeout_notify = timeout_notify
166         self.callback_notify = callback_notify
167         self.ssl_keyfile = ssl_keyfile
168         self.ssl_certfile = ssl_certfile
169         self.ssl_version = ssl_version
170         self.ssl_cert_reqs = ssl_cert_reqs
171         self.ssl_ca_certs = ssl_ca_certs
172         self.ssl_ciphers = ssl_ciphers
173         self.headers = headers if headers else []  # type: List[str]
174         self.encoded_headers = None  # type: List[Tuple[bytes, bytes]]
175 
176         self.loaded = False
177         self.configure_logging()
178 
179         if reload_dirs is None:
180             self.reload_dirs = [os.getcwd()]
181         else:
182             self.reload_dirs = reload_dirs
183 
184         if env_file is not None:
185             from dotenv import load_dotenv
186 
187             logger.info("Loading environment from '%s'", env_file)
188             load_dotenv(dotenv_path=env_file)
189 
190         if workers is None and "WEB_CONCURRENCY" in os.environ:
191             self.workers = int(os.environ["WEB_CONCURRENCY"])
192 
193         if forwarded_allow_ips is None and "FORWARDED_ALLOW_IPS" in os.environ:
194             self.forwarded_allow_ips = os.environ["FORWARDED_ALLOW_IPS"]
195 
196     @property
197     def is_ssl(self) -> bool:
198         return bool(self.ssl_keyfile or self.ssl_certfile)
199 
200     def configure_logging(self):
201         logging.addLevelName(TRACE_LOG_LEVEL, "TRACE")
202 
203         if sys.version_info < (3, 7):
204             # https://bugs.python.org/issue30520
205             import pickle
206 
207             def __reduce__(self):
208                 if isinstance(self, logging.RootLogger):
209                     return logging.getLogger, ()
210 
211                 if logging.getLogger(self.name) is not self:
212                     raise pickle.PicklingError("logger cannot be pickled")
213                 return logging.getLogger, (self.name,)
214 
215             logging.Logger.__reduce__ = __reduce__
216 
217         if self.log_config is not None:
218             if isinstance(self.log_config, dict):
219                 logging.config.dictConfig(self.log_config)
220             else:
221                 logging.config.fileConfig(self.log_config)
222 
223         if self.log_level is not None:
224             if isinstance(self.log_level, str):
225                 log_level = LOG_LEVELS[self.log_level]
226             else:
227                 log_level = self.log_level
228             logging.getLogger("").setLevel(log_level)
229             logging.getLogger("uvicorn.error").setLevel(log_level)
230             logging.getLogger("uvicorn.access").setLevel(log_level)
231             logging.getLogger("uvicorn.asgi").setLevel(log_level)
232         if self.access_log is False:
233             logging.getLogger("uvicorn.access").handlers = []
234             logging.getLogger("uvicorn.access").propagate = False
235 
236     def load(self):
237         assert not self.loaded
238 
239         if self.is_ssl:
240             self.ssl = create_ssl_context(
241                 keyfile=self.ssl_keyfile,
242                 certfile=self.ssl_certfile,
243                 ssl_version=self.ssl_version,
244                 cert_reqs=self.ssl_cert_reqs,
245                 ca_certs=self.ssl_ca_certs,
246                 ciphers=self.ssl_ciphers,
247             )
248         else:
249             self.ssl = None
250 
251         encoded_headers = [
252             (key.lower().encode("latin1"), value.encode("latin1"))
253             for key, value in self.headers
254         ]
255         self.encoded_headers = (
256             encoded_headers
257             if b"server" in dict(encoded_headers)
258             else [(b"server", b"uvicorn")] + encoded_headers
259         )  # type: List[Tuple[bytes, bytes]]
260 
261         if isinstance(self.http, str):
262             self.http_protocol_class = import_from_string(HTTP_PROTOCOLS[self.http])
263         else:
264             self.http_protocol_class = self.http
265 
266         if isinstance(self.ws, str):
267             self.ws_protocol_class = import_from_string(WS_PROTOCOLS[self.ws])
268         else:
269             self.ws_protocol_class = self.ws
270 
271         self.lifespan_class = import_from_string(LIFESPAN[self.lifespan])
272 
273         try:
274             self.loaded_app = import_from_string(self.app)
275         except ImportFromStringError as exc:
276             logger.error("Error loading ASGI app. %s" % exc)
277             sys.exit(1)
278 
279         if self.interface == "auto":
280             if inspect.isclass(self.loaded_app):
281                 use_asgi_3 = hasattr(self.loaded_app, "__await__")
282             elif inspect.isfunction(self.loaded_app):
283                 use_asgi_3 = asyncio.iscoroutinefunction(self.loaded_app)
284             else:
285                 call = getattr(self.loaded_app, "__call__", None)
286                 use_asgi_3 = asyncio.iscoroutinefunction(call)
287             self.interface = "asgi3" if use_asgi_3 else "asgi2"
288 
289         if self.interface == "wsgi":
290             self.loaded_app = WSGIMiddleware(self.loaded_app)
291             self.ws_protocol_class = None
292         elif self.interface == "asgi2":
293             self.loaded_app = ASGI2Middleware(self.loaded_app)
294 
295         if self.debug:
296             self.loaded_app = DebugMiddleware(self.loaded_app)
297         if logger.level <= TRACE_LOG_LEVEL:
298             self.loaded_app = MessageLoggerMiddleware(self.loaded_app)
299         if self.proxy_headers:
300             self.loaded_app = ProxyHeadersMiddleware(
301                 self.loaded_app, trusted_hosts=self.forwarded_allow_ips
302             )
303 
304         self.loaded = True
305 
306     def setup_event_loop(self):
307         loop_setup = import_from_string(LOOP_SETUPS[self.loop])
308         if loop_setup is not None:
309             loop_setup()
310 
311     def bind_socket(self):
312         sock = socket.socket()
313         sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
314         try:
315             sock.bind((self.host, self.port))
316         except OSError as exc:
317             logger.error(exc)
318             sys.exit(1)
319         sock.set_inheritable(True)
320 
321         message = "Uvicorn running on %s://%s:%d (Press CTRL+C to quit)"
322         color_message = (
323             "Uvicorn running on "
324             + click.style("%s://%s:%d", bold=True)
325             + " (Press CTRL+C to quit)"
326         )
327         protocol_name = "https" if self.is_ssl else "http"
328         logger.info(
329             message,
330             protocol_name,
331             self.host,
332             self.port,
333             extra={"color_message": color_message},
334         )
335         return sock
336 
337     @property
338     def should_reload(self):
339         return isinstance(self.app, str) and (self.debug or self.reload)
340
```
--- 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/uvicorn/config.py b/uvicorn/config.py
--- a/uvicorn/config.py
+++ b/uvicorn/config.py
@@ -157,7 +157,6 @@
         self.reload = reload
         self.workers = workers or 1
         self.proxy_headers = proxy_headers
-        self.forwarded_allow_ips = forwarded_allow_ips or "127.0.0.1"
         self.root_path = root_path
         self.limit_concurrency = limit_concurrency
         self.limit_max_requests = limit_max_requests
@@ -190,8 +189,12 @@
         if workers is None and "WEB_CONCURRENCY" in os.environ:
             self.workers = int(os.environ["WEB_CONCURRENCY"])
 
-        if forwarded_allow_ips is None and "FORWARDED_ALLOW_IPS" in os.environ:
-            self.forwarded_allow_ips = os.environ["FORWARDED_ALLOW_IPS"]
+        if forwarded_allow_ips is None:
+            self.forwarded_allow_ips = os.environ.get(
+                "FORWARDED_ALLOW_IPS", "127.0.0.1"
+            )
+        else:
+            self.forwarded_allow_ips = forwarded_allow_ips
 
     @property
     def is_ssl(self) -> bool:

{"golden_diff": "diff --git a/uvicorn/config.py b/uvicorn/config.py\n--- a/uvicorn/config.py\n+++ b/uvicorn/config.py\n@@ -157,7 +157,6 @@\n         self.reload = reload\n         self.workers = workers or 1\n         self.proxy_headers = proxy_headers\n-        self.forwarded_allow_ips = forwarded_allow_ips or \"127.0.0.1\"\n         self.root_path = root_path\n         self.limit_concurrency = limit_concurrency\n         self.limit_max_requests = limit_max_requests\n@@ -190,8 +189,12 @@\n         if workers is None and \"WEB_CONCURRENCY\" in os.environ:\n             self.workers = int(os.environ[\"WEB_CONCURRENCY\"])\n \n-        if forwarded_allow_ips is None and \"FORWARDED_ALLOW_IPS\" in os.environ:\n-            self.forwarded_allow_ips = os.environ[\"FORWARDED_ALLOW_IPS\"]\n+        if forwarded_allow_ips is None:\n+            self.forwarded_allow_ips = os.environ.get(\n+                \"FORWARDED_ALLOW_IPS\", \"127.0.0.1\"\n+            )\n+        else:\n+            self.forwarded_allow_ips = forwarded_allow_ips\n \n     @property\n     def is_ssl(self) -> bool:\n", "issue": "FORWARDED_ALLOW_IPS cannot be loaded from ENV\nThe following two lines together makes impossible to read `FORWARDED_ALLOW_IPS` from env variable.\r\n\r\nhttps://github.com/encode/uvicorn/blob/4da64be4335ba50e43d7ac8c3b5535460a9c1594/uvicorn/config.py#L160\r\nhttps://github.com/encode/uvicorn/blob/4da64be4335ba50e43d7ac8c3b5535460a9c1594/uvicorn/config.py#L193\n", "before_files": [{"content": "import asyncio\nimport inspect\nimport logging\nimport logging.config\nimport os\nimport socket\nimport ssl\nimport sys\nfrom typing import List, Tuple\n\nimport click\n\nfrom uvicorn.importer import ImportFromStringError, import_from_string\nfrom uvicorn.middleware.asgi2 import ASGI2Middleware\nfrom uvicorn.middleware.debug import DebugMiddleware\nfrom uvicorn.middleware.message_logger import MessageLoggerMiddleware\nfrom uvicorn.middleware.proxy_headers import ProxyHeadersMiddleware\nfrom uvicorn.middleware.wsgi import WSGIMiddleware\n\nTRACE_LOG_LEVEL = 5\n\nLOG_LEVELS = {\n    \"critical\": logging.CRITICAL,\n    \"error\": logging.ERROR,\n    \"warning\": logging.WARNING,\n    \"info\": logging.INFO,\n    \"debug\": logging.DEBUG,\n    \"trace\": TRACE_LOG_LEVEL,\n}\nHTTP_PROTOCOLS = {\n    \"auto\": \"uvicorn.protocols.http.auto:AutoHTTPProtocol\",\n    \"h11\": \"uvicorn.protocols.http.h11_impl:H11Protocol\",\n    \"httptools\": \"uvicorn.protocols.http.httptools_impl:HttpToolsProtocol\",\n}\nWS_PROTOCOLS = {\n    \"auto\": \"uvicorn.protocols.websockets.auto:AutoWebSocketsProtocol\",\n    \"none\": None,\n    \"websockets\": \"uvicorn.protocols.websockets.websockets_impl:WebSocketProtocol\",\n    \"wsproto\": \"uvicorn.protocols.websockets.wsproto_impl:WSProtocol\",\n}\nLIFESPAN = {\n    \"auto\": \"uvicorn.lifespan.on:LifespanOn\",\n    \"on\": \"uvicorn.lifespan.on:LifespanOn\",\n    \"off\": \"uvicorn.lifespan.off:LifespanOff\",\n}\nLOOP_SETUPS = {\n    \"none\": None,\n    \"auto\": \"uvicorn.loops.auto:auto_loop_setup\",\n    \"asyncio\": \"uvicorn.loops.asyncio:asyncio_setup\",\n    \"uvloop\": \"uvicorn.loops.uvloop:uvloop_setup\",\n    \"iocp\": \"uvicorn.loops.iocp:iocp_setup\",\n}\nINTERFACES = [\"auto\", \"asgi3\", \"asgi2\", \"wsgi\"]\n\n\n# Fallback to 'ssl.PROTOCOL_SSLv23' in order to support Python < 3.5.3.\nSSL_PROTOCOL_VERSION = getattr(ssl, \"PROTOCOL_TLS\", ssl.PROTOCOL_SSLv23)\n\n\nLOGGING_CONFIG = {\n    \"version\": 1,\n    \"disable_existing_loggers\": False,\n    \"formatters\": {\n        \"default\": {\n            \"()\": \"uvicorn.logging.DefaultFormatter\",\n            \"fmt\": \"%(levelprefix)s %(message)s\",\n        },\n        \"access\": {\n            \"()\": \"uvicorn.logging.AccessFormatter\",\n            \"fmt\": '%(levelprefix)s %(client_addr)s - \"%(request_line)s\" %(status_code)s',\n        },\n    },\n    \"handlers\": {\n        \"default\": {\n            \"formatter\": \"default\",\n            \"class\": \"logging.StreamHandler\",\n            \"stream\": \"ext://sys.stderr\",\n        },\n        \"access\": {\n            \"formatter\": \"access\",\n            \"class\": \"logging.StreamHandler\",\n            \"stream\": \"ext://sys.stdout\",\n        },\n    },\n    \"loggers\": {\n        \"\": {\"handlers\": [\"default\"], \"level\": \"INFO\"},\n        \"uvicorn.error\": {\"level\": \"INFO\"},\n        \"uvicorn.access\": {\"handlers\": [\"access\"], \"level\": \"INFO\", \"propagate\": False},\n    },\n}\n\nlogger = logging.getLogger(\"uvicorn.error\")\n\n\ndef create_ssl_context(certfile, keyfile, ssl_version, cert_reqs, ca_certs, ciphers):\n    ctx = ssl.SSLContext(ssl_version)\n    ctx.load_cert_chain(certfile, keyfile)\n    ctx.verify_mode = cert_reqs\n    if ca_certs:\n        ctx.load_verify_locations(ca_certs)\n    if ciphers:\n        ctx.set_ciphers(ciphers)\n    return ctx\n\n\nclass Config:\n    def __init__(\n        self,\n        app,\n        host=\"127.0.0.1\",\n        port=8000,\n        uds=None,\n        fd=None,\n        loop=\"auto\",\n        http=\"auto\",\n        ws=\"auto\",\n        lifespan=\"auto\",\n        env_file=None,\n        log_config=LOGGING_CONFIG,\n        log_level=None,\n        access_log=True,\n        interface=\"auto\",\n        debug=False,\n        reload=False,\n        reload_dirs=None,\n        workers=None,\n        proxy_headers=True,\n        forwarded_allow_ips=None,\n        root_path=\"\",\n        limit_concurrency=None,\n        limit_max_requests=None,\n        timeout_keep_alive=5,\n        timeout_notify=30,\n        callback_notify=None,\n        ssl_keyfile=None,\n        ssl_certfile=None,\n        ssl_version=SSL_PROTOCOL_VERSION,\n        ssl_cert_reqs=ssl.CERT_NONE,\n        ssl_ca_certs=None,\n        ssl_ciphers=\"TLSv1\",\n        headers=None,\n    ):\n        self.app = app\n        self.host = host\n        self.port = port\n        self.uds = uds\n        self.fd = fd\n        self.loop = loop\n        self.http = http\n        self.ws = ws\n        self.lifespan = lifespan\n        self.log_config = log_config\n        self.log_level = log_level\n        self.access_log = access_log\n        self.interface = interface\n        self.debug = debug\n        self.reload = reload\n        self.workers = workers or 1\n        self.proxy_headers = proxy_headers\n        self.forwarded_allow_ips = forwarded_allow_ips or \"127.0.0.1\"\n        self.root_path = root_path\n        self.limit_concurrency = limit_concurrency\n        self.limit_max_requests = limit_max_requests\n        self.timeout_keep_alive = timeout_keep_alive\n        self.timeout_notify = timeout_notify\n        self.callback_notify = callback_notify\n        self.ssl_keyfile = ssl_keyfile\n        self.ssl_certfile = ssl_certfile\n        self.ssl_version = ssl_version\n        self.ssl_cert_reqs = ssl_cert_reqs\n        self.ssl_ca_certs = ssl_ca_certs\n        self.ssl_ciphers = ssl_ciphers\n        self.headers = headers if headers else []  # type: List[str]\n        self.encoded_headers = None  # type: List[Tuple[bytes, bytes]]\n\n        self.loaded = False\n        self.configure_logging()\n\n        if reload_dirs is None:\n            self.reload_dirs = [os.getcwd()]\n        else:\n            self.reload_dirs = reload_dirs\n\n        if env_file is not None:\n            from dotenv import load_dotenv\n\n            logger.info(\"Loading environment from '%s'\", env_file)\n            load_dotenv(dotenv_path=env_file)\n\n        if workers is None and \"WEB_CONCURRENCY\" in os.environ:\n            self.workers = int(os.environ[\"WEB_CONCURRENCY\"])\n\n        if forwarded_allow_ips is None and \"FORWARDED_ALLOW_IPS\" in os.environ:\n            self.forwarded_allow_ips = os.environ[\"FORWARDED_ALLOW_IPS\"]\n\n    @property\n    def is_ssl(self) -> bool:\n        return bool(self.ssl_keyfile or self.ssl_certfile)\n\n    def configure_logging(self):\n        logging.addLevelName(TRACE_LOG_LEVEL, \"TRACE\")\n\n        if sys.version_info < (3, 7):\n            # https://bugs.python.org/issue30520\n            import pickle\n\n            def __reduce__(self):\n                if isinstance(self, logging.RootLogger):\n                    return logging.getLogger, ()\n\n                if logging.getLogger(self.name) is not self:\n                    raise pickle.PicklingError(\"logger cannot be pickled\")\n                return logging.getLogger, (self.name,)\n\n            logging.Logger.__reduce__ = __reduce__\n\n        if self.log_config is not None:\n            if isinstance(self.log_config, dict):\n                logging.config.dictConfig(self.log_config)\n            else:\n                logging.config.fileConfig(self.log_config)\n\n        if self.log_level is not None:\n            if isinstance(self.log_level, str):\n                log_level = LOG_LEVELS[self.log_level]\n            else:\n                log_level = self.log_level\n            logging.getLogger(\"\").setLevel(log_level)\n            logging.getLogger(\"uvicorn.error\").setLevel(log_level)\n            logging.getLogger(\"uvicorn.access\").setLevel(log_level)\n            logging.getLogger(\"uvicorn.asgi\").setLevel(log_level)\n        if self.access_log is False:\n            logging.getLogger(\"uvicorn.access\").handlers = []\n            logging.getLogger(\"uvicorn.access\").propagate = False\n\n    def load(self):\n        assert not self.loaded\n\n        if self.is_ssl:\n            self.ssl = create_ssl_context(\n                keyfile=self.ssl_keyfile,\n                certfile=self.ssl_certfile,\n                ssl_version=self.ssl_version,\n                cert_reqs=self.ssl_cert_reqs,\n                ca_certs=self.ssl_ca_certs,\n                ciphers=self.ssl_ciphers,\n            )\n        else:\n            self.ssl = None\n\n        encoded_headers = [\n            (key.lower().encode(\"latin1\"), value.encode(\"latin1\"))\n            for key, value in self.headers\n        ]\n        self.encoded_headers = (\n            encoded_headers\n            if b\"server\" in dict(encoded_headers)\n            else [(b\"server\", b\"uvicorn\")] + encoded_headers\n        )  # type: List[Tuple[bytes, bytes]]\n\n        if isinstance(self.http, str):\n            self.http_protocol_class = import_from_string(HTTP_PROTOCOLS[self.http])\n        else:\n            self.http_protocol_class = self.http\n\n        if isinstance(self.ws, str):\n            self.ws_protocol_class = import_from_string(WS_PROTOCOLS[self.ws])\n        else:\n            self.ws_protocol_class = self.ws\n\n        self.lifespan_class = import_from_string(LIFESPAN[self.lifespan])\n\n        try:\n            self.loaded_app = import_from_string(self.app)\n        except ImportFromStringError as exc:\n            logger.error(\"Error loading ASGI app. %s\" % exc)\n            sys.exit(1)\n\n        if self.interface == \"auto\":\n            if inspect.isclass(self.loaded_app):\n                use_asgi_3 = hasattr(self.loaded_app, \"__await__\")\n            elif inspect.isfunction(self.loaded_app):\n                use_asgi_3 = asyncio.iscoroutinefunction(self.loaded_app)\n            else:\n                call = getattr(self.loaded_app, \"__call__\", None)\n                use_asgi_3 = asyncio.iscoroutinefunction(call)\n            self.interface = \"asgi3\" if use_asgi_3 else \"asgi2\"\n\n        if self.interface == \"wsgi\":\n            self.loaded_app = WSGIMiddleware(self.loaded_app)\n            self.ws_protocol_class = None\n        elif self.interface == \"asgi2\":\n            self.loaded_app = ASGI2Middleware(self.loaded_app)\n\n        if self.debug:\n            self.loaded_app = DebugMiddleware(self.loaded_app)\n        if logger.level <= TRACE_LOG_LEVEL:\n            self.loaded_app = MessageLoggerMiddleware(self.loaded_app)\n        if self.proxy_headers:\n            self.loaded_app = ProxyHeadersMiddleware(\n                self.loaded_app, trusted_hosts=self.forwarded_allow_ips\n            )\n\n        self.loaded = True\n\n    def setup_event_loop(self):\n        loop_setup = import_from_string(LOOP_SETUPS[self.loop])\n        if loop_setup is not None:\n            loop_setup()\n\n    def bind_socket(self):\n        sock = socket.socket()\n        sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)\n        try:\n            sock.bind((self.host, self.port))\n        except OSError as exc:\n            logger.error(exc)\n            sys.exit(1)\n        sock.set_inheritable(True)\n\n        message = \"Uvicorn running on %s://%s:%d (Press CTRL+C to quit)\"\n        color_message = (\n            \"Uvicorn running on \"\n            + click.style(\"%s://%s:%d\", bold=True)\n            + \" (Press CTRL+C to quit)\"\n        )\n        protocol_name = \"https\" if self.is_ssl else \"http\"\n        logger.info(\n            message,\n            protocol_name,\n            self.host,\n            self.port,\n            extra={\"color_message\": color_message},\n        )\n        return sock\n\n    @property\n    def should_reload(self):\n        return isinstance(self.app, str) and (self.debug or self.reload)\n", "path": "uvicorn/config.py"}], "after_files": [{"content": "import asyncio\nimport inspect\nimport logging\nimport logging.config\nimport os\nimport socket\nimport ssl\nimport sys\nfrom typing import List, Tuple\n\nimport click\n\nfrom uvicorn.importer import ImportFromStringError, import_from_string\nfrom uvicorn.middleware.asgi2 import ASGI2Middleware\nfrom uvicorn.middleware.debug import DebugMiddleware\nfrom uvicorn.middleware.message_logger import MessageLoggerMiddleware\nfrom uvicorn.middleware.proxy_headers import ProxyHeadersMiddleware\nfrom uvicorn.middleware.wsgi import WSGIMiddleware\n\nTRACE_LOG_LEVEL = 5\n\nLOG_LEVELS = {\n    \"critical\": logging.CRITICAL,\n    \"error\": logging.ERROR,\n    \"warning\": logging.WARNING,\n    \"info\": logging.INFO,\n    \"debug\": logging.DEBUG,\n    \"trace\": TRACE_LOG_LEVEL,\n}\nHTTP_PROTOCOLS = {\n    \"auto\": \"uvicorn.protocols.http.auto:AutoHTTPProtocol\",\n    \"h11\": \"uvicorn.protocols.http.h11_impl:H11Protocol\",\n    \"httptools\": \"uvicorn.protocols.http.httptools_impl:HttpToolsProtocol\",\n}\nWS_PROTOCOLS = {\n    \"auto\": \"uvicorn.protocols.websockets.auto:AutoWebSocketsProtocol\",\n    \"none\": None,\n    \"websockets\": \"uvicorn.protocols.websockets.websockets_impl:WebSocketProtocol\",\n    \"wsproto\": \"uvicorn.protocols.websockets.wsproto_impl:WSProtocol\",\n}\nLIFESPAN = {\n    \"auto\": \"uvicorn.lifespan.on:LifespanOn\",\n    \"on\": \"uvicorn.lifespan.on:LifespanOn\",\n    \"off\": \"uvicorn.lifespan.off:LifespanOff\",\n}\nLOOP_SETUPS = {\n    \"none\": None,\n    \"auto\": \"uvicorn.loops.auto:auto_loop_setup\",\n    \"asyncio\": \"uvicorn.loops.asyncio:asyncio_setup\",\n    \"uvloop\": \"uvicorn.loops.uvloop:uvloop_setup\",\n    \"iocp\": \"uvicorn.loops.iocp:iocp_setup\",\n}\nINTERFACES = [\"auto\", \"asgi3\", \"asgi2\", \"wsgi\"]\n\n\n# Fallback to 'ssl.PROTOCOL_SSLv23' in order to support Python < 3.5.3.\nSSL_PROTOCOL_VERSION = getattr(ssl, \"PROTOCOL_TLS\", ssl.PROTOCOL_SSLv23)\n\n\nLOGGING_CONFIG = {\n    \"version\": 1,\n    \"disable_existing_loggers\": False,\n    \"formatters\": {\n        \"default\": {\n            \"()\": \"uvicorn.logging.DefaultFormatter\",\n            \"fmt\": \"%(levelprefix)s %(message)s\",\n        },\n        \"access\": {\n            \"()\": \"uvicorn.logging.AccessFormatter\",\n            \"fmt\": '%(levelprefix)s %(client_addr)s - \"%(request_line)s\" %(status_code)s',\n        },\n    },\n    \"handlers\": {\n        \"default\": {\n            \"formatter\": \"default\",\n            \"class\": \"logging.StreamHandler\",\n            \"stream\": \"ext://sys.stderr\",\n        },\n        \"access\": {\n            \"formatter\": \"access\",\n            \"class\": \"logging.StreamHandler\",\n            \"stream\": \"ext://sys.stdout\",\n        },\n    },\n    \"loggers\": {\n        \"\": {\"handlers\": [\"default\"], \"level\": \"INFO\"},\n        \"uvicorn.error\": {\"level\": \"INFO\"},\n        \"uvicorn.access\": {\"handlers\": [\"access\"], \"level\": \"INFO\", \"propagate\": False},\n    },\n}\n\nlogger = logging.getLogger(\"uvicorn.error\")\n\n\ndef create_ssl_context(certfile, keyfile, ssl_version, cert_reqs, ca_certs, ciphers):\n    ctx = ssl.SSLContext(ssl_version)\n    ctx.load_cert_chain(certfile, keyfile)\n    ctx.verify_mode = cert_reqs\n    if ca_certs:\n        ctx.load_verify_locations(ca_certs)\n    if ciphers:\n        ctx.set_ciphers(ciphers)\n    return ctx\n\n\nclass Config:\n    def __init__(\n        self,\n        app,\n        host=\"127.0.0.1\",\n        port=8000,\n        uds=None,\n        fd=None,\n        loop=\"auto\",\n        http=\"auto\",\n        ws=\"auto\",\n        lifespan=\"auto\",\n        env_file=None,\n        log_config=LOGGING_CONFIG,\n        log_level=None,\n        access_log=True,\n        interface=\"auto\",\n        debug=False,\n        reload=False,\n        reload_dirs=None,\n        workers=None,\n        proxy_headers=True,\n        forwarded_allow_ips=None,\n        root_path=\"\",\n        limit_concurrency=None,\n        limit_max_requests=None,\n        timeout_keep_alive=5,\n        timeout_notify=30,\n        callback_notify=None,\n        ssl_keyfile=None,\n        ssl_certfile=None,\n        ssl_version=SSL_PROTOCOL_VERSION,\n        ssl_cert_reqs=ssl.CERT_NONE,\n        ssl_ca_certs=None,\n        ssl_ciphers=\"TLSv1\",\n        headers=None,\n    ):\n        self.app = app\n        self.host = host\n        self.port = port\n        self.uds = uds\n        self.fd = fd\n        self.loop = loop\n        self.http = http\n        self.ws = ws\n        self.lifespan = lifespan\n        self.log_config = log_config\n        self.log_level = log_level\n        self.access_log = access_log\n        self.interface = interface\n        self.debug = debug\n        self.reload = reload\n        self.workers = workers or 1\n        self.proxy_headers = proxy_headers\n        self.root_path = root_path\n        self.limit_concurrency = limit_concurrency\n        self.limit_max_requests = limit_max_requests\n        self.timeout_keep_alive = timeout_keep_alive\n        self.timeout_notify = timeout_notify\n        self.callback_notify = callback_notify\n        self.ssl_keyfile = ssl_keyfile\n        self.ssl_certfile = ssl_certfile\n        self.ssl_version = ssl_version\n        self.ssl_cert_reqs = ssl_cert_reqs\n        self.ssl_ca_certs = ssl_ca_certs\n        self.ssl_ciphers = ssl_ciphers\n        self.headers = headers if headers else []  # type: List[str]\n        self.encoded_headers = None  # type: List[Tuple[bytes, bytes]]\n\n        self.loaded = False\n        self.configure_logging()\n\n        if reload_dirs is None:\n            self.reload_dirs = [os.getcwd()]\n        else:\n            self.reload_dirs = reload_dirs\n\n        if env_file is not None:\n            from dotenv import load_dotenv\n\n            logger.info(\"Loading environment from '%s'\", env_file)\n            load_dotenv(dotenv_path=env_file)\n\n        if workers is None and \"WEB_CONCURRENCY\" in os.environ:\n            self.workers = int(os.environ[\"WEB_CONCURRENCY\"])\n\n        if forwarded_allow_ips is None:\n            self.forwarded_allow_ips = os.environ.get(\n                \"FORWARDED_ALLOW_IPS\", \"127.0.0.1\"\n            )\n        else:\n            self.forwarded_allow_ips = forwarded_allow_ips\n\n    @property\n    def is_ssl(self) -> bool:\n        return bool(self.ssl_keyfile or self.ssl_certfile)\n\n    def configure_logging(self):\n        logging.addLevelName(TRACE_LOG_LEVEL, \"TRACE\")\n\n        if sys.version_info < (3, 7):\n            # https://bugs.python.org/issue30520\n            import pickle\n\n            def __reduce__(self):\n                if isinstance(self, logging.RootLogger):\n                    return logging.getLogger, ()\n\n                if logging.getLogger(self.name) is not self:\n                    raise pickle.PicklingError(\"logger cannot be pickled\")\n                return logging.getLogger, (self.name,)\n\n            logging.Logger.__reduce__ = __reduce__\n\n        if self.log_config is not None:\n            if isinstance(self.log_config, dict):\n                logging.config.dictConfig(self.log_config)\n            else:\n                logging.config.fileConfig(self.log_config)\n\n        if self.log_level is not None:\n            if isinstance(self.log_level, str):\n                log_level = LOG_LEVELS[self.log_level]\n            else:\n                log_level = self.log_level\n            logging.getLogger(\"\").setLevel(log_level)\n            logging.getLogger(\"uvicorn.error\").setLevel(log_level)\n            logging.getLogger(\"uvicorn.access\").setLevel(log_level)\n            logging.getLogger(\"uvicorn.asgi\").setLevel(log_level)\n        if self.access_log is False:\n            logging.getLogger(\"uvicorn.access\").handlers = []\n            logging.getLogger(\"uvicorn.access\").propagate = False\n\n    def load(self):\n        assert not self.loaded\n\n        if self.is_ssl:\n            self.ssl = create_ssl_context(\n                keyfile=self.ssl_keyfile,\n                certfile=self.ssl_certfile,\n                ssl_version=self.ssl_version,\n                cert_reqs=self.ssl_cert_reqs,\n                ca_certs=self.ssl_ca_certs,\n                ciphers=self.ssl_ciphers,\n            )\n        else:\n            self.ssl = None\n\n        encoded_headers = [\n            (key.lower().encode(\"latin1\"), value.encode(\"latin1\"))\n            for key, value in self.headers\n        ]\n        self.encoded_headers = (\n            encoded_headers\n            if b\"server\" in dict(encoded_headers)\n            else [(b\"server\", b\"uvicorn\")] + encoded_headers\n        )  # type: List[Tuple[bytes, bytes]]\n\n        if isinstance(self.http, str):\n            self.http_protocol_class = import_from_string(HTTP_PROTOCOLS[self.http])\n        else:\n            self.http_protocol_class = self.http\n\n        if isinstance(self.ws, str):\n            self.ws_protocol_class = import_from_string(WS_PROTOCOLS[self.ws])\n        else:\n            self.ws_protocol_class = self.ws\n\n        self.lifespan_class = import_from_string(LIFESPAN[self.lifespan])\n\n        try:\n            self.loaded_app = import_from_string(self.app)\n        except ImportFromStringError as exc:\n            logger.error(\"Error loading ASGI app. %s\" % exc)\n            sys.exit(1)\n\n        if self.interface == \"auto\":\n            if inspect.isclass(self.loaded_app):\n                use_asgi_3 = hasattr(self.loaded_app, \"__await__\")\n            elif inspect.isfunction(self.loaded_app):\n                use_asgi_3 = asyncio.iscoroutinefunction(self.loaded_app)\n            else:\n                call = getattr(self.loaded_app, \"__call__\", None)\n                use_asgi_3 = asyncio.iscoroutinefunction(call)\n            self.interface = \"asgi3\" if use_asgi_3 else \"asgi2\"\n\n        if self.interface == \"wsgi\":\n            self.loaded_app = WSGIMiddleware(self.loaded_app)\n            self.ws_protocol_class = None\n        elif self.interface == \"asgi2\":\n            self.loaded_app = ASGI2Middleware(self.loaded_app)\n\n        if self.debug:\n            self.loaded_app = DebugMiddleware(self.loaded_app)\n        if logger.level <= TRACE_LOG_LEVEL:\n            self.loaded_app = MessageLoggerMiddleware(self.loaded_app)\n        if self.proxy_headers:\n            self.loaded_app = ProxyHeadersMiddleware(\n                self.loaded_app, trusted_hosts=self.forwarded_allow_ips\n            )\n\n        self.loaded = True\n\n    def setup_event_loop(self):\n        loop_setup = import_from_string(LOOP_SETUPS[self.loop])\n        if loop_setup is not None:\n            loop_setup()\n\n    def bind_socket(self):\n        sock = socket.socket()\n        sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)\n        try:\n            sock.bind((self.host, self.port))\n        except OSError as exc:\n            logger.error(exc)\n            sys.exit(1)\n        sock.set_inheritable(True)\n\n        message = \"Uvicorn running on %s://%s:%d (Press CTRL+C to quit)\"\n        color_message = (\n            \"Uvicorn running on \"\n            + click.style(\"%s://%s:%d\", bold=True)\n            + \" (Press CTRL+C to quit)\"\n        )\n        protocol_name = \"https\" if self.is_ssl else \"http\"\n        logger.info(\n            message,\n            protocol_name,\n            self.host,\n            self.port,\n            extra={\"color_message\": color_message},\n        )\n        return sock\n\n    @property\n    def should_reload(self):\n        return isinstance(self.app, str) and (self.debug or self.reload)\n", "path": "uvicorn/config.py"}]}