HTTPConnection request socket.gaierror in python - python

I encountered an error today while trying to retrieve an XML by sending a 'GET' HTTP request.
from httplib import HTTPConnection
import urllib
params = urllib.urlencode({'sK': 'test', 'sXML': 1})
httpCon = HTTPConnection("http://www.podnapisi.net",80)
httpCon.request('GET', '/en/ppodnapisi/search',params)
r1 = httpCon.getresponse()
and here is the error i got:
.....
File "C:\Python27\lib\socket.py", line 553, in create_connection
for res in getaddrinfo(host, port, 0, SOCK_STREAM):
socket.gaierror: [Errno 11004] getaddrinfo failed
The XML that I am trying to retrieve HERE
How can I fix this error ?
Thanks in Advance ...

No scheme (http://) in the HTTPConnection constructor:
httpCon = HTTPConnection("www.podnapisi.net",80)
It already knows it's HTTP, it's an HTTPConnection object :)

You accidentally included the protocol prefix in the domain argument to HTTPConnection. You want:
httpCon = HTTPConnection("www.podnapisi.net", 80)
Generally, This error indicates there was a problem resolving the domain name to an IP address. In It might be just intermittent. If the problem persists, check the DNS configuration on your system.
For example, you can set it to use Google's public DNS server. For more information about how to configure your DNS server on Microsoft Windows, refer to Microsoft's knowledge database.

Related

TIme out error in python while sending email [duplicate]

I have tried to attached a file to the mail using python.
Code:
import smtplib
from email.MIMEMultipart import MIMEMultipart
from email.MIMEText import MIMEText
from smtplib import SMTPException
def send_Email():
file1="abc.txt"
message = "Test mail"
msg = MIMEMultipart()
msg.attach(MIMEText(file(file1).read()))
try:
smtpObj = smtplib.SMTP('smtp server name',port)
smtpObj.sendmail(sender, EmailId, message, msg.as_string() )
print "Successfully sent email"
except SMTPException:
print "Error: unable to send email"
Bt I have get the error: socket.gaierror: [Errno 11001] getaddrinfo failed
full error message:
File "C:\Python27\lib\smtplib.py", line 249, in __init__
(code, msg) = self.connect(host, port)
File "C:\Python27\lib\smtplib.py", line 309, in connect
self.sock = self._get_socket(host, port, self.timeout)
File "C:\Python27\lib\smtplib.py", line 284, in _get_socket
return socket.create_connection((port, host), timeout)
File "C:\Python27\lib\socket.py", line 553, in create_connection
for res in getaddrinfo(host, port, 0, SOCK_STREAM):
socket.gaierror: [Errno 11001] getaddrinfo failed
I know for sure that gaierror comes up when you are working from behind proxy.
The problem is that the DNS lookup for 'smtp server name' is failing - if this is your exact code then you can see why - if not and you have the valid qualified name for the SMTP server then you may have issues with the firewall/internet connection, etc., also port has to be set to a valid value to match your servers SMTP configuration, (usually port 25 but not absolutely always).
The below answer may be quite irrelevant to the question. But,some users may have a different scenario.
If a server can be reached only through VPN and if we try to reach it with VPN disconnected, this error : "gaierror: [Errno 11001] getaddrinfo failed" crops up.
Connect to VPN and then executing the code should work good.
In my case was a host problem. Using debug mode, I spotted that in (host, port, 0, SOCK_STREAM) I got host=local and it should be host=localhost.
In the run.py I defined localhost and the file hosts (c:\windows\system32\drivers\etc\hosts) was defined local.
They have to be equal, otherwise you get the socket.gaieeror.
There seems to be a bug in urllib3 version 1.25.9 package. This produced "socket.gaierror: [Errno 11001] getaddrinfo failed" error for me (working from behind an authenticated proxy server).
Downgrading to urllib3 version 1.25.8 solved the problem.
you might did a little mistake in settings.py file..
check your code one more time in your settings file
settings.py:
EMAIL_BACKEND='django.core.mail.backends.smtp.EmailBackend'
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_HOST_USER = 'your_email'
EMAIL_HOST_PASSWORD = 'your_password'
EMAIL_PORT = 587
EMAIL_USE_TLS=True
I got this error when I tried using flask-mail
I just had to resend the message and it worked perfectly well.
I don't know why I got the error the first time perhaps it might be a bug in the library...
You need to login using your credential. Try:
smtpObj = smtplib.SMTP('smtp server name',port)
smtpObj .starttls()
smtpObj .login(email, password)
smtpObj.sendmail(sender, EmailId, message, msg.as_string() )
print "Successfully sent email"
I prefer u guys to run the file as administrator for eg
open cmd as administrator then
type
cd C:\into ur .py file path
and then type
python filename.py
it worked for me.
good luck
You need to activate IMAP/SMTP service active for your host mail.

Access FTP URL with ftplib [duplicate]

This question already has an answer here:
Accessing FTP server with Python fails with "getaddrinfo" error
(1 answer)
Closed 2 years ago.
I am using python in Windows with ftplib to access a folder at ftp5.xyz.eu.
The folder is 'baz' in ftp5.xyz.eu in the folder 'foo bar'. So : ftp5.xyz.eu/foo bar/baz
I connect successfully at ftp5.xyz.eu but when i write the whole path to the folder it gives me an error:
from ftplib import FTP
#domain name or server ip:
ftp = FTP('ftp5.xyz.eu/foo%20bar')
...
ftp.dir()
error gived below:
File "C:\Users\mirel.voicu\AppData\Local\Programs\Python\Python37\lib\ftplib.py", line 117, in __init__
self.connect(host)
File "C:\Users\mirel.voicu\AppData\Local\Programs\Python\Python37\lib\ftplib.py", line 152, in connect
source_address=self.source_address)
File "C:\Users\mirel.voicu\AppData\Local\Programs\Python\Python37\lib\socket.py", line 707, in create_connection
for res in getaddrinfo(host, port, 0, SOCK_STREAM):
File "C:\Users\mirel.voicu\AppData\Local\Programs\Python\Python37\lib\socket.py", line 748, in getaddrinfo
for res in _socket.getaddrinfo(host, port, family, type, proto, flags):
socket.gaierror: [Errno 11001] getaddrinfo failed
This has nothing to do with the space. The first argument of FTP constructor is host – a hostname or an IP address – not an URL.
So it should be:
ftp = FTP('ftp5.xyz.eu')
If you want to list files in foo bar subfolder, either do:
ftp.cwd('foo bar')
ftp.dir()
or
ftp.dir('foo bar')
The error message is Python's slightly obtuse way of saying "there is no server with that name"; and indeed, the server name here is not valid. You are passing 'ftp5.xyz.eu/foo%20bar' where you should be passing in just 'ftp5.xyz.eu'.
FTP traditionally does not use URL addresses, and Python's ftplib has no support for parsing them. You will need to pick apart the URL using, oh, I guess urllib, and take it from there.
from ftplib import FTP
from urllib.parse import urlparse
parsed = urlparse('ftp://ftp5.xyz.eu/foo%20bar')
ftp = FTP(parsed.netloc)
ftp.login()
ftp.cwd(parsed.path)
ftp.dir()
The parsed parsed.path still uses %20 where probably the FTP server expects a literal space; maybe also do URL decoding (urllib.parse.unquote or maybe urlllib.parse.unquote_plus).

InstagramApi using Python: How to set up proxy server?

I am newbie to Instagram Api. I am trying to figure out how to set proxy for InstagramApi using Python. Below is the basic code which I got from github. When I executed this code I got an error. I think I need to include proxy server.
How can I include a proxy server in this?
from instagram.client import InstagramAPI
access_token="*******************************"
client_secret="******************************"
api = InstagramAPI(access_token=access_token, client_secret=client_secret)
recent_media, next_ = api.user_recent_media(user_id="jey07", count=4)
for media in recent_media:
print(media.caption.text)
I am getting below error:
File "C:\Users\Gabriel\AppData\Local\Programs\Python\Python36\lib\socket.py", line 713, in create_connection
sock.connect(sa)
ConnectionRefusedError: [WinError 10061] No connection could be made because the target machine actively refused it
It's not possible with the current version of python-instagram lib. But to deal with http requests, python-instagram uses httplib2 that allows you to set a Proxy Server : http://httplib2.readthedocs.io/en/latest/libhttplib2.html?highlight=proxyinfo#httplib2.ProxyInfo
You can fork the project, implement the feature and make a pull request.
Alternatively, you can try to use Instagram-API-python library. Proxy seems to be supported : https://github.com/LevPasha/Instagram-API-python/blob/master/InstagramAPI.py#L64

Error connecting to WCF service with Python suds

I am trying to connect to a WCF web service with Python suds. The link type is:
from suds import Client
url = "http://ipadress/Webservices/WCF/Service.svc?singleWsdl"
client = Client(url)
response = client.services.GetData(username, password)
The error I get comes from the urllib2 library, which is a dependency of suds:
urllib2.URLError: <urlopen error [Errno 11004] getaddrinfo failed>
When I put the url in the browser I get the xml tree of the web service, therefore the link appears to be good. Is it a problem with suds not supporting these types of web services?

troubleshooting python code

I am in my first steps in learning python so excuse my questions please. I want to run the code below (taken from: http://docs.python.org/library/ssl.html) :
import socket, ssl, pprint
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# require a certificate from the server
ssl_sock = ssl.wrap_socket(s,
ca_certs="F:/cert",
cert_reqs=ssl.CERT_REQUIRED)
ssl_sock.connect(('www.versign.com', 443))
print repr(ssl_sock.getpeername())
print ssl_sock.cipher()
print pprint.pformat(ssl_sock.getpeercert())
# Set a simple HTTP request -- use httplib in actual code.
ssl_sock.write("""GET / HTTP/1.0\r
Host: www.verisign.com\r\n\r\n""")
# Read a chunk of data. Will not necessarily
# read all the data returned by the server.
data = ssl_sock.read()
# note that closing the SSLSocket will also close the underlying socket
ssl_sock.close()
I got the following errors:
Traceback (most recent call last):
File "C:\Users\e\workspace\PythonTesting\source\HelloWorld.py", line 38, in
ssl_sock.connect(('www.versign.com', 443))
File "C:\Python27\lib\ssl.py", line 331, in connect
self._real_connect(addr, False)
File "C:\Python27\lib\ssl.py", line 314, in _real_connect
self.ca_certs, self.ciphers)
ssl.SSLError: [Errno 185090050] _ssl.c:340: error:0B084002:x509 certificate routines:X509_load_cert_crl_file:system lib
The error reporting in python does not look guiding to find the source of the problem. i might be mistaken. Can anybody help in telling me what is the problem in the code ?
This is one area where the Python standard library is known to be difficult to use. Instead you may want to use the requests library. Documentation on sending certificates is available at: http://docs.python-requests.org/en/latest/user/advanced/#ssl-cert-verification
Your code is referring to a certificate file on drive 'F:' (using the ca_certs parameter), which is not found during execution -- is there one?
See the relevant documentation:
The ca_certs file contains a set of concatenated “certification
authority” certificates, which are used to validate certificates
passed from the other end of the connection.
Does the certificate referenced exist on your filesystem? I think that error is in response to invalid cert from this code:
ssl_sock = ssl.wrap_socket(s,ca_certs="F:/cert",cert_reqs=ssl.CERT_REQUIRED)

Categories

Resources