- Получение ошибки socket.gaierror: [Errno 11003] getaddrinfo failed when using Django Channels
- Getaddrinfo failed python django
- # Table of Contents
- # socket.gaierror: [Errno 11001] getaddrinfo failed [Solved]
- # The error commonly occurs when you try to connect from behind a proxy
- # Trying to use pip install from behind a proxy
- # Make sure you don’t have internet connectivity issues
- # Additional Resources
- Saved searches
- Use saved searches to filter your results more quickly
- «Error: [Errno 11001] getaddrinfo failed» on Windows #1669
- «Error: [Errno 11001] getaddrinfo failed» on Windows #1669
- Comments
Получение ошибки socket.gaierror: [Errno 11003] getaddrinfo failed when using Django Channels
Я настраиваю Websockets с помощью Django Channels , отправляя тестовое сообщение при срабатывании соответствующей конечной точки API. Однако когда я пытаюсь использовать Postman для тестирования моего websocket-соединения, я успешно подключаюсь, получаю JSON, который я отправляю, и сразу же отключаюсь. Вот полный отслеживание:
redis.exceptions.ConnectionError: Error 10061 connecting to localhost:49155. No connection could be made because the target machine actively refused it. HTTP GET /media/profile/2022/06/10/photo-1615672968435-95ade28e0b38.jpg 500 [4.47, 127.0.0.1:51105] HTTP GET /users/1/ 500 [4.46, 127.0.0.1:51106] WebSocket HANDSHAKING /stories/notification_testing/ [127.0.0.1:50570] , 'cookies': <>, 'session': , 'user': , 'path_remaining': '', 'url_route': >> WebSocket CONNECT /stories/notification_testing/ [127.0.0.1:50570] Exception inside application: [Errno 11003] getaddrinfo failed Traceback (most recent call last): . File "C:\Users\15512\Desktop\django-project\peerplatform\signup\consumers.py", line 31, in websocket_connect await self.channel_layer.group_add(self.room_group_name, self.channel_name) . for res in _socket.getaddrinfo(host, port, family, type, proto, flags): socket.gaierror: [Errno 11003] getaddrinfo failed WebSocket DISCONNECT /stories/notification_testing/ [127.0.0.1:50570]
Я запускаю Redis через образ Django, я уже использую кэш Redis для различных целей. Вот как я настраиваю свой слой Channels в Settings.py :
Это расположение моего экземпляра Redis из Docker
"LOCATION": "redis://default:redispw@localhost:49153",
Я настроил маршрутизатор для моих вебсокетах в asgi.py :
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'signup.settings') application = ProtocolTypeRouter(< "http": get_asgi_application(), "websocket": AuthMiddlewareStack( URLRouter( [path('stories/notification_testing/', NotificationConsumer.as_asgi())] )) >)
Я заметил в трекбеке, что одна из ошибок, похоже, относится к строке 31 в моем файле consumers.py, вот конкретная функция из consumers.py:
class NotificationConsumer(AsyncWebsocketConsumer): async def websocket_connect(self, event): print(self.scope) await self.accept() await self.send(json.dumps(< "type": "websocket.send", "text": "hello world" >)) self.room_name='test_consumer' self.room_group_name='test_consumer_group' await self.channel_layer.group_add(self.room_group_name, self.channel_name) self.send(< "type": "websocket.send", "text": "room made" >)
На всякий случай, если это тоже актуально, вот мой models.py:
class Notifications(models.Model): sender = models.ForeignKey(User, null=True, blank=True, related_name='sender', on_delete=models.CASCADE) receiver = models.ForeignKey(User, null=True, blank=True, related_name='receiver', on_delete=models.CASCADE) status = models.CharField(max_length=264, null=True, blank=True, default="unread") type_of_notification = models.CharField(max_length=264, null=True, blank=True)
- После небольшого исследования я попробовал изменить хост на: redis://default:redispw@localhost, 49153 и получил ту же ошибку .
- Переустановил все django-channels & redis-channels
- Временно отключил брандмауэр, чтобы проверить, не в этом ли проблема .
- Я знаю, что раскрываю свой порт и хост, потому что, как я уже говорил, я уже использую экземпляр redis в качестве кэша для хранения и получения данных .
У меня была такая же проблема. URL Redis был неправильным. После того как я изменил его, все заработало.
Getaddrinfo failed python django
Last updated: Jul 8, 2023
Reading time · 4 min
# Table of Contents
# socket.gaierror: [Errno 11001] getaddrinfo failed [Solved]
The article addresses the following 2 related errors:
- socket.gaierror: [Errno 11001] getaddrinfo failed
- socket.gaierror: [Errno -2] Name or service not known
The Python «socket.gaierror: [Errno 11001] getaddrinfo failed» occurs for 2 main reasons:
- Trying to resolve a hostname incorrectly. Your Python application cannot resolve the IP address of the host.
- Incorrectly setting the http_proxy environment variable.
- Having internet connectivity issues.
If you got the error when using the socket.getaddrinfo method, make sure you haven’t passed it incorrect arguments.
For example, if you’re trying to connect to a server running on a localhost port, your getaddrinfo() call would look something like this:
Copied!import socket # [(, , 6, '', ('127.0.0.1', 8000)), (, , 17, '', ('127.0.0.1', 8000)), (, , 0, '', ('127.0.0.1', 8000))] print(socket.getaddrinfo('localhost', 8000))
The first argument we passed to the method is the host and the second is the port.
If that doesn’t work, you can also try to replace localhost with the string ‘127.0.0.1’ .
Copied!import socket # [(, , 6, '', ('127.0.0.1', 8000)), (, , 17, '', ('127.0.0.1', 8000)), (, , 0, '', ('127.0.0.1', 8000))] print(socket.getaddrinfo('127.0.0.1', 8000))
The string 127.0.0.1 is equivalent to localhost but resolves more often.
You can also call the socket.getaddrinfo() method with a fully qualified domain name.
Copied!import socket print(socket.getaddrinfo('google.com', 443))
However, make sure the protocol scheme is not included because that causes an error.
Copied!import socket # ⛔️ socket.gaierror: [Errno -2] Name or service not known print(socket.getaddrinfo('https://google.com', 443))
Including the protocol scheme ( https:// or http:// ) causes an error.
If you need to handle the potential error, use a try/except block.
Copied!import socket try: print(socket.getaddrinfo('google.com', 443)) except socket.gaierror as e: print('An error occurred: ', e)
We try to call the socket.getaddrinfo() method in the try block.
If a socket.gaierror exception occurs, it gets handled in the except block.
# The error commonly occurs when you try to connect from behind a proxy
The error also commonly occurs when you try to connect to a network from behind a proxy.
You might have set the http_proxy or https_proxy environment variables by mistake.
You can print the values of the variables by using the following commands on Windows.
Copied!# Windows CMD echo %http_proxy% echo %https_proxy%
If you are on macOS or Linux, issue the following commands instead.
Copied!# macOS and Linux echo $http_proxy echo $https_proxy
To clear the http_proxy and https_proxy environment variables on Windows, issue the following commands in CMD (Command Prompt).
Copied!# for Windows CMD (Command Prompt) set http_proxy=null set https_proxy=null set HTTP_PROXY=null set HTTPS_PROXY=null
If you use PowerShell on Windows, issue the following commands instead.
Copied!# for Windows CMD (PowerShell) [Environment]::SetEnvironmentVariable('http_proxy', '', 'User') [Environment]::SetEnvironmentVariable('http_proxy', '', 'Machine') [Environment]::SetEnvironmentVariable('https_proxy', '', 'User') [Environment]::SetEnvironmentVariable('https_proxy', '', 'Machine')
If you are on macOS or Linux, issue the following commands in bash or zsh .
Copied!# for macOS, Linux or Windows Git Bash unset http_proxy unset https_proxy unset HTTP_PROXY unset HTTPS_PROXY
Check if the error is resolved after removing the http_proxy and https_proxy environment variables.
If you need to use a proxy, try setting the environment variables to the correct value.
For example, if you are on Windows, the commands would look something like this:
Copied!# for Windows # without a username and a password set HTTP_PROXY=http://proxy.company:8080 # or with a username and a password set HTTPS_PROXY=http://USERNAME:PASSWORD@proxy.company:8080
If you are on macOS or Linux, the commands would look something like this:
Copied!# For macOS or Linux # without a username and a password export http_proxy=http://proxy.company:8080 export HTTP_PROXY=http://proxy.company:8080 # or with a username and a password export https_proxy=http://USERNAME:PASSWORD@proxy.company:8080 export HTTPS_PROXY=http://USERNAME:PASSWORD@proxy.company:8080
Make sure to replace the placeholders with the actual values.
# Trying to use pip install from behind a proxy
If you’re trying to use pip install from behind a proxy, set the —proxy parameter.
Copied!pip install --proxy http://user:password@proxy_server:port requests
If you don’t have to specify the username and password, your command might look something like this:
Copied!pip install --proxy http://proxy_server:port
If you set the http_proxy or https_proxy environment variables, you don’t have to set the —proxy parameter when running pip install .
# Make sure you don’t have internet connectivity issues
Make sure your connection to the internet is not flake, as that also causes the error.
If the server you’re trying to connect to requires the use of a VPN, make sure your VPN is turned on.
You can also try to restart your VPN or try to disable it.
# Additional Resources
You can learn more about the related topics by checking out the following tutorials:
I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
Saved searches
Use saved searches to filter your results more quickly
You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session. You switched accounts on another tab or window. Reload to refresh your session.
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
«Error: [Errno 11001] getaddrinfo failed» on Windows #1669
«Error: [Errno 11001] getaddrinfo failed» on Windows #1669
Comments
Issue Discription
(myvenv) C:\Users\rkfql\djangogirls>python manage.py runserver 0:8000
Performing system checks.
System check identified no issues (0 silenced).
July 14, 2020 — 23:15:38
Django version 2.0.13, using settings ‘mysite.settings’
Starting development server at http://0:8000/
Quit the server with CTRL-BREAK.
Error: [Errno 11001] getaddrinfo failed
Operating system : WIndows 10
how to solve this error?
The text was updated successfully, but these errors were encountered:
The only place, where I found 0:8000 in our tutorial is here: https://github.com/DjangoGirls/tutorial/blame/master/en/django_start_project/README.md#L184 and it looks, that it was proposed back in 2015: 6e428a4 as a resolution for some unicode problem.
Original commit message doesn’t clearly say why we cannot use 0.0.0.0 or even 127.0.0.1 .
Did you try 0.0.0.0:8000 or 127.0.0.0:8000 @horeoryang ?
Thank you for your reply. i try your solution that is both of you, but it can’t work. i will attach the codes.
(myvenv) C:\Users\이시형\djangogirls>python manage.py runserver 0.0.0.0:8000 Performing system checks. System check identified no issues (0 silenced). July 18, 2020 - 13:14:28 Django version 2.0.13, using settings 'mysite.settings' Starting development server at http://0.0.0.0:8000/ Quit the server with CTRL-BREAK. Exception ignored in thread started by: .wrapper at 0x000001B2C490BEE0> Traceback (most recent call last): File "C:\Users\이시형\djangogirls\myvenv\lib\site-packages\django\utils\autoreload.py", line 225, in wrapper fn(*args, **kwargs) File "C:\Users\이시형\djangogirls\myvenv\lib\site-packages\django\core\management\commands\runserver.py", line 141, in inner_run run(self.addr, int(self.port), handler, File "C:\Users\이시형\djangogirls\myvenv\lib\site-packages\django\core\servers\basehttp.py", line 163, in run httpd = httpd_cls(server_address, WSGIRequestHandler, ipv6=ipv6) File "C:\Users\이시형\djangogirls\myvenv\lib\site-packages\django\core\servers\basehttp.py", line 66, in __init__ super().__init__(*args, **kwargs) File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.8_3.8.1264.0_x64__qbz5n2kfra8p0\lib\socketserver.py", line 452, in __init__ self.server_bind() File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.8_3.8.1264.0_x64__qbz5n2kfra8p0\lib\wsgiref\simple_server.py", line 50, in server_bind HTTPServer.server_bind(self) File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.8_3.8.1264.0_x64__qbz5n2kfra8p0\lib\http\server.py", line 140, in server_bind self.server_name = socket.getfqdn(host) File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.8_3.8.1264.0_x64__qbz5n2kfra8p0\lib\socket.py", line 756, in getfqdn hostname, aliases, ipaddrs = gethostbyaddr(name) UnicodeDecodeError: 'utf-8' codec can't decode byte 0xc0 in position 4: invalid start byte (myvenv) C:\Users\이시형\djangogirls>python manage.py runserver 127.0.0.0:8000 Performing system checks. System check identified no issues (0 silenced). July 18, 2020 - 13:09:04 Django version 2.0.13, using settings 'mysite.settings' Starting development server at http://127.0.0.0:8000/ Quit the server with CTRL-BREAK. Error: That IP address can't be assigned to.