errno 10054 on Status check request - python-2.7

Ok, I've tried to resolve this with a couple of different libraries. I'm working on a script to look at thousands of sites and kick out specific items on the pages. I need to be able to reset the connection so that the script will continue without losing any data. I've tried catching the error and waiting but that doesn't seem to fix it as it eventually causes the script to error completely out. I get the error on the below snippet of code in my status check module.
def status(url): #checks the response code
try:
req=urllib2.urlopen(url)
response=req.getcode()
return response
except urllib2.HTTPError, e:
return e.code
print e.code
except urllib2.URLError, e:
print e.args
return e.args
But before trying this I used the below as instead of urrlib2
parsedurl = urlparse(url)
conn = httplib.HTTPConnection(parsedurl.netloc)
conn.request('HEAD',parsedurl.path)
response = conn.getresponse()
return response.status

Related

Trying again after a urllib2.URLError: <urlopen error [Errno 111] Connection refused>

Is this code correct? I ended up getting an Errno 111 and the program still quit rather than trying again and again.
When i get a connection error, i want to wait 10 seconds and then retry to get the URL again.
I'm using Python 2.7.
import errno
for attempt in range(20):
try:
browser.get(url)
except EnvironmentError as exc:
if exc.errno == errno.ECONNREFUSED:
anow = datetime.datetime.now()
print("got a 111 connection error",anow)
time.sleep(10)
elif exc.errno == errno.ECONNRESET:
anow = datetime.datetime.now()
print("got a RESET connection error",anow)
time.sleep(10)
else:
continue
else:
break
else:
print("tried 20 times - kept getting Error")
So this is what I ended up doing, and it seems to work:
What I wanted was something that would re-try again after any error, but also tell me what the error was. This code is running on PythonANywhere so i am not worried about keyboard interrupts, etc... Besides, the attempt in range() ensures that the code doesn't run forever as it would in a While-True loop.
for attempt in range(1,3):
try:
browser.get(url)
print("browser success",i)
break
except Exception as e:
print(e," Attempt:" + str(attempt))
time.sleep(4)
pass

Why does the Python script to send data to Slack web hook not work when variable is pulled from a line?

Language: Python 2.7
Hello all. I found a really helpful script here: Python to Slack Web Hook
that shows how to send messages to a Slack web hook.
import json
import requests
# Set the webhook_url to the one provided by Slack when you create the webhook at https://my.slack.com/services/new/incoming-webhook/
webhook_url = 'https://hooks.slack.com/services/T00000000/B00000000/XXXXXXXXXXXXXXXXXXXXXXXX'
slack_data = {"text": "<https://alert-system.com/alerts/1234|Click here> for details!"}
response = requests.post(
webhook_url, data=json.dumps(slack_data),
headers={'Content-Type': 'application/json'}
)
if response.status_code != 200:
raise ValueError(
'Request to slack returned an error %s, the response is:\n%s'
% (response.status_code, response.text)
)
It works flawlessly when I run .py file.
Now, I have a file that has many lines of messages that I want to send to Slack. I have it formatted correctly already in the file, no spaces etc.. It's just a matter of grabbing it and passing it so slack_data = line1 etc..
So, I modify the file with something like this:
with open('export.txt', 'r') as e:
for line in e:
slack_data = line
Now if I do a print slack_data right after that, the information returns on the screen exactly as it should be, so I'm thinking it's good. I haven't began to get it working for each line yet, because it's not even working on the first line.
I get an invalid payload 400 when I run it.
EDIT: Slack support said the what they were receiving has escape characters inserted into for some reason.
"{\"text\": \"<https://alert-system.com/alerts/1234|Click here> for details!"}\n"
Any direction or assistance is appreciated.
Thanks!!
Just posting as it might help somebody. For me the below snippet worked:
data = json.dumps(slack_data)
response = requests.post(
URL, json={"text": data},
headers={'Content-Type': 'application/json'}
)
As #Geo pointed out the final payload that we are going to send should have keyword "text", else it will fail.
Moreover, in post method I have to replace data= with json= else it kept throwing error for invalid payload with 400
Since I already had the data preformatted in the file as JSON already, it was just a matter of removing json.dumps out of the code.
OLD:
#response = requests.post(webhook_url, data=json.dumps(slack_data), headers={'Content-Type': 'application/json'})
NEW:
response = requests.post(webhook_url, data=slack_data, headers={'Content-Type': 'application/json'})
Once I did that, everything worked like a charm.
If you change the code to this:
with open('export.txt', 'r') as e:
slack_data = e.read()
do you still get the 400?

PyUSB ask for device Status

I'm trying to write a script for barcode printers.
Here is my Code:
def printLabel(barcode, qty, articlenr=''):
dev = findPrinter()
dev.write("")
return True
if __name__ =="__main__":
for i in range(2):
try:
# Everything works fine, the for loop breaks
printLabel('01234567890123','1', 'Hello World')
break
except usb.core.USBError as error:
if "Resource busy" in unicode(error):
# Printer is doing something, wait 3 seconds, try again
time.sleep(3)
print 'Retrying after error:"Resource busy"\n' + str(error)
printLabel('01234567890123','1', 'Hello World')
elif "Operation Timeout" in unicode(error):
# Printer is not responding
print 'ERROR! Check Paper!\n' + str(error)
else:
print 'Unknown error' + str(error)
I have to ask for the status of the printer before he tries to printLabel, because if I can't ask for it he maybe gets in the "Resource busy" if clause inside the exception, prints the label, starts all over again and prints it again.
But if I could ask for the status I can say him something like:
def waitForPrinter(dev):
dev = findPrinter()
if dev.status() is True: ## True if he is ready and False if he is Busy or something
printLabel(arguments and stuff)
else:
time.sleep(3)
waitForPrinter()
I couldn't find a function in the documentation for asking the device status and don't know how to solve the problem right now.
At the moment i can only fetch the device status with the USBError.

Python telnet connection refuse exception

I'm using following function to make telnet connection verification
telnetlib.Telnet("172.28.5.240", "8080")
When the connection refused it shows exception message. Is it possible to hide the message and detect as success or failed through if condition?
You can use try-except-finally blocks
try:
#
#
response = 'Success'
except:
response = 'Failed'
finally:
print response
Based on Suku's answer I develop my code. that is a working answer. And following is my script for reference.
try:
conn = telnetlib.Telnet("172.28.5.240", "80")
response = 'Success'
except:
response = 'Failed'
finally:
print response
None of the options helped me.
Maybe someone will come in handy.
100% working version:
Used to check the availability of the RDP server in ZABBIX:
import telnetlib
response = ''
HOST = '192.168.1.201'
PORT = 3389
tn = telnetlib.Telnet()
try:
tn.open(HOST, PORT, 3)
response = '2'
except Exception:
response = '0'
finally:
tn.close()
print(response)

How to get the contents of the error page in Python's mechanize?

So assume I get an error back when using mechanize.Browser.retrieve and I catch it like this:
try:
br.retrieve(url, fname)
except mechanize.HTTPError as e:
if e.code in [403, 404]:
# how can I get to the contents of the server-sent error page?
else:
raise
How can I access the error page which was sent by the server at this point?
I've tried using br.response().get_data(), but that doesn't seem to get populated when using retrieve().
Since HTTP errors are wrapped by mechanize and contain additional info about the response, you can use e.read():
try:
br.retrieve(url, fname)
except mechanize.HTTPError as e:
if e.code in [403, 404]:
print e.read()
else:
raise