raspberry pi can't make any url requests, connection timed out - python

I need to update my sensor data to thingspeak , so I was doing it with the python thingspeak library. Two days ago it was working fine but now it doesn't work, the connection times out , I also tried to update it with urllib2 ,that too doesnt' work.
My net connection is fine, I am able to open webpages on Pi and I can update the channel from my laptop using thingspeak library as well as urllib2.
could someone kindly help me.
my code with thingspeak library:
node = False
channel_id = ""
write = ""
if data['MAC'] in ':ab:35':
channel_id = "XXXXX"
write = "XXXXXXXXXXX"
node = True
if node:
channel = thingspeak.Channel(id=channel_id,write_key=write)
try :
response=channel.update({1:data['TEMP'],2:data['VOLT'],3:data['PRES'],4:data['HUM']})
print response
print 'Thingspeak updated!!!'
except :
print "connection failed"
when i try urllib2 :
f = urllib2.urlopen(url)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib/python2.7/urllib2.py", line 154, in urlopen
return opener.open(url, data, timeout)
File "/usr/lib/python2.7/urllib2.py", line 431, in open
response = self._open(req, data)
File "/usr/lib/python2.7/urllib2.py", line 449, in _open
'_open', req)
File "/usr/lib/python2.7/urllib2.py", line 409, in _call_chain
result = func(*args)
File "/usr/lib/python2.7/urllib2.py", line 1240, in https_open
context=self._context)
File "/usr/lib/python2.7/urllib2.py", line 1197, in do_open
raise URLError(err)
urllib2.URLError: <urlopen error [Errno 110] Connection timed out>
when I try thingspeak library :
>>> channel = thingspeak.Channel(id=c,write_key=w)
>>> res = channel.update({1:50,2:30,3:70,4:20})
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "build/bdist.linux-armv7l/egg/thingspeak/thingspeak.py", line 116, in update
File "/usr/lib/python2.7/dist-packages/requests/api.py", line 94, in post
return request('post', url, data=data, json=json, **kwargs)
File "/usr/lib/python2.7/dist-packages/requests/api.py", line 49, in request
return session.request(method=method, url=url, **kwargs)
File "/usr/lib/python2.7/dist-packages/requests/sessions.py", line 457, in request
resp = self.send(prep, **send_kwargs)
File "/usr/lib/python2.7/dist-packages/requests/sessions.py", line 569, in send
r = adapter.send(request, **kwargs)
File "/usr/lib/python2.7/dist-packages/requests/adapters.py", line 407, in send
raise ConnectionError(err, request=request)
requests.exceptions.ConnectionError: ('Connection aborted.', error(110, 'Connection timed out'))

I am using the raspberry-pi to send data to thingspeak.
What I do is something like this:
import httplib
import urllib
#Preparing to send the information to the cloud
params=urllib.urlencode({'field1':liters,'key':key})
headers={"Content-typZZe": "application/x-www-form-urlencoded","Accept":"text/plain"}
conn=httplib.HTTPConnection("api.thingspeak.com:80")
#Sending the data to the thingspeak platform
try:
conn.request("POST", "/update", params, headers)
response=conn.getresponse()
print response.status, response.reason
data=response.read()
conn.close()
except:
print "connection failed"
And it works just fine.
The key is the string of your channel key.
Hope it helps.

If I use SSH and try to run the script, it works .

Add a new User-Agent, by creating Request objects & using them as arguments for urlopen:
import urllib2
request = urllib2.Request('http://www.example.com/')
request.add_header('User-agent', 'Mozilla/5.0 (Linux i686)')
response = urllib2.urlopen(request)

Related

ReadTimeoutError - Why is this occurring?

I encounter the following ReadTimeoutError, the request not responding and not giving out any output (in the state of runnning non-stop):
Traceback (most recent call last):
File "C:\Users\user\AppData\Local\Programs\Python\Python310\lib\site-packages\urllib3\connectionpool.py", line 449, in _make_request
six.raise_from(e, None)
File "<string>", line 3, in raise_from
File "C:\Users\user\AppData\Local\Programs\Python\Python310\lib\site-packages\urllib3\connectionpool.py", line 444, in _make_request
httplib_response = conn.getresponse()
File "C:\Users\user\AppData\Local\Programs\Python\Python310\lib\http\client.py", line 1374, in getresponse
response.begin()
File "C:\Users\user\AppData\Local\Programs\Python\Python310\lib\http\client.py", line 318, in begin
version, status, reason = self._read_status()
File "C:\Users\user\AppData\Local\Programs\Python\Python310\lib\http\client.py", line 279, in _read_status
line = str(self.fp.readline(_MAXLINE + 1), "iso-8859-1")
File "C:\Users\user\AppData\Local\Programs\Python\Python310\lib\socket.py", line 705, in readinto
return self._sock.recv_into(b)
TimeoutError: timed out
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "C:\Users\user\AppData\Local\Programs\Python\Python310\lib\site-packages\requests\adapters.py", line 440, in send
resp = conn.urlopen(
File "C:\Users\user\AppData\Local\Programs\Python\Python310\lib\site-packages\urllib3\connectionpool.py", line 785, in urlopen
retries = retries.increment(
File "C:\Users\user\AppData\Local\Programs\Python\Python310\lib\site-packages\urllib3\util\retry.py", line 550, in increment
raise six.reraise(type(error), error, _stacktrace)
File "C:\Users\user\AppData\Local\Programs\Python\Python310\lib\site-packages\urllib3\packages\six.py", line 770, in reraise
raise value
File "C:\Users\user\AppData\Local\Programs\Python\Python310\lib\site-packages\urllib3\connectionpool.py", line 703, in urlopen
httplib_response = self._make_request(
File "C:\Users\user\AppData\Local\Programs\Python\Python310\lib\site-packages\urllib3\connectionpool.py", line 451, in _make_request
self._raise_timeout(err=e, url=url, timeout_value=read_timeout)
File "C:\Users\user\AppData\Local\Programs\Python\Python310\lib\site-packages\urllib3\connectionpool.py", line 340, in _raise_timeout
raise ReadTimeoutError(
urllib3.exceptions.ReadTimeoutError: HTTPConnectionPool(host='127.0.0.1', port=4990): Read timed out. (read timeout=10)
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "C:\Users\user\Downloads\getSupplierName-api\test.py", line 35, in <module>
response = requests.request("PUT", url, headers=headers, data=payload, timeout=10)
File "C:\Users\user\AppData\Local\Programs\Python\Python310\lib\site-packages\requests\api.py", line 61, in request
return session.request(method=method, url=url, **kwargs)
File "C:\Users\user\AppData\Local\Programs\Python\Python310\lib\site-packages\requests\sessions.py", line 529, in request
resp = self.send(prep, **send_kwargs)
File "C:\Users\user\AppData\Local\Programs\Python\Python310\lib\site-packages\requests\sessions.py", line 645, in send
r = adapter.send(request, **kwargs)
File "C:\Users\user\AppData\Local\Programs\Python\Python310\lib\site-packages\requests\adapters.py", line 532, in send
raise ReadTimeout(e, request=request)
requests.exceptions.ReadTimeout: HTTPConnectionPool(host='127.0.0.1', port=4990): Read timed out. (read timeout=10)
The request code is as follows:
import requests
import json
import glob
url = "..."
headers = {
'Content-Type': 'application/json'
}
path = "..../*.pdf"
list_of_path = glob.glob(path)
print("Number of files:", len(list_of_path))
for i in list_of_path:
print(i)
payload = json.dumps({
"file_path": i,
"company_id": "abcde",
})
response = requests.request("PUT", url, headers=headers, data=payload, timeout=10)
print(response.json()['payload'])
Not sure why this is happening. The same issue happens with or without running in virtualenv. It was running fine when I ran it (many times) without any virtualenv, then I created the virtualenv on my machine and ran it again, it's working fine. But on the next day, the error occurs when I try to run it.
Appreciate any help, many thanks!
Looks to me that the service that was listening for at port 4990 is not listening anymore. I suppose you know what service this is, so I recommend to check if it's running.
After you start the service that listen at port 4990, there are two ways to confirm you the port is really open and listening:
If you are using linux, you can check what ports are listening in your machine with the following command:
sudo lsof -i -P -n | grep LISTEN
You can try to connect to the port 4990 using telnet:
telnet 127.0.0.1 4990
If the telnet works, the output should be something like this:
Trying 127.0.0.1...
Connected to 127.0.0.1.
Escape character is '^]'.

Sending a JSON Post using requests in python 3.7.2

So im trying to use python to send a post to a url, i have basically copied everything from my network console in firefox yet i can't get it to work.
import requests
import json
url = 'https://www.example.com/example?handle'
cookie = {'UID':'b56f14d8-02b1-4ae8-ad5e-3485cf0abdbe'}
data ={'example':'example'}
headers = {'Accept':'*/*',
'Accept-Encoding':'gzip, deflate, br',
'Accept-Language':'en-US,en;q=0.5',
'Connection':'keep-alive',
'Content-Length':'78',
'Content-Type':'text/plain;charset=UTF-8',
'Cookie':'UID=b56f14d8-02b1-4ae8-ad5e-3485cf0abdbe',
'Host':'www.example.com',
'Referer':'https:/example.com/example',
'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:65.0) Gecko/20100101 Firefox/65.0'}
req = requests.post(url, cookies=cookie, params=json.dumps(data), headers=headers)
print(req)
I have replaced the actual data and url with example.
After running this, i get a big long error:
Traceback (most recent call last):
File "C:\Users\Kaiser\AppData\Local\Programs\Python\Python37-32 \lib\site-packages\urllib3\connectionpool.py", line 600, in urlopen
chunked=chunked)
File "C:\Users\Kaiser\AppData\Local\Programs\Python\Python37-32\lib\site-packages\urllib3\connectionpool.py", line 384, in _make_request
six.raise_from(e, None)
File "<string>", line 2, in raise_from
File "C:\Users\Kaiser\AppData\Local\Programs\Python\Python37-32\lib\site-packages\urllib3\connectionpool.py", line 380, in _make_request
httplib_response = conn.getresponse()
File "C:\Users\Kaiser\AppData\Local\Programs\Python\Python37-32\lib\http\client.py", line 1321, in getresponse
response.begin()
File "C:\Users\Kaiser\AppData\Local\Programs\Python\Python37-32\lib\http\client.py", line 296, in begin
version, status, reason = self._read_status()
File "C:\Users\Kaiser\AppData\Local\Programs\Python\Python37-32\lib\http\client.py", line 257, in _read_status
line = str(self.fp.readline(_MAXLINE + 1), "iso-8859-1")
File "C:\Users\Kaiser\AppData\Local\Programs\Python\Python37-32\lib\socket.py", line 589, in readinto
return self._sock.recv_into(b)
File "C:\Users\Kaiser\AppData\Local\Programs\Python\Python37-32\lib\ssl.py", line 1052, in recv_into
return self.read(nbytes, buffer)
File "C:\Users\Kaiser\AppData\Local\Programs\Python\Python37-32\lib\ssl.py", line 911, in read
return self._sslobj.read(len, buffer)
ConnectionResetError: [WinError 10054] An existing connection was forcibly closed by the remote host
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "C:\Users\Kaiser\AppData\Local\Programs\Python\Python37-32\lib\site-packages\requests\adapters.py", line 449, in send
timeout=timeout
File "C:\Users\Kaiser\AppData\Local\Programs\Python\Python37-32\lib\site-packages\urllib3\connectionpool.py", line 638, in urlopen
_stacktrace=sys.exc_info()[2])
File "C:\Users\Kaiser\AppData\Local\Programs\Python\Python37-32\lib\site-packages\urllib3\util\retry.py", line 367, in increment
raise six.reraise(type(error), error, _stacktrace)
File "C:\Users\Kaiser\AppData\Local\Programs\Python\Python37-32\lib\site-packages\urllib3\packages\six.py", line 685, in reraise
raise value.with_traceback(tb)
File "C:\Users\Kaiser\AppData\Local\Programs\Python\Python37-32\lib\site-packages\urllib3\connectionpool.py", line 600, in urlopen
chunked=chunked)
File "C:\Users\Kaiser\AppData\Local\Programs\Python\Python37-32\lib\site-packages\urllib3\connectionpool.py", line 384, in _make_request
six.raise_from(e, None)
File "<string>", line 2, in raise_from
File "C:\Users\Kaiser\AppData\Local\Programs\Python\Python37-32\lib\site-packages\urllib3\connectionpool.py", line 380, in _make_request
httplib_response = conn.getresponse()
File "C:\Users\Kaiser\AppData\Local\Programs\Python\Python37-32\lib\http\client.py", line 1321, in getresponse
response.begin()
File "C:\Users\Kaiser\AppData\Local\Programs\Python\Python37-32\lib\http\client.py", line 296, in begin
version, status, reason = self._read_status()
File "C:\Users\Kaiser\AppData\Local\Programs\Python\Python37-32\lib\http\client.py", line 257, in _read_status
line = str(self.fp.readline(_MAXLINE + 1), "iso-8859-1")
File "C:\Users\Kaiser\AppData\Local\Programs\Python\Python37-32\lib\socket.py", line 589, in readinto
return self._sock.recv_into(b)
File "C:\Users\Kaiser\AppData\Local\Programs\Python\Python37-32\lib\ssl.py", line 1052, in recv_into
return self.read(nbytes, buffer)
File "C:\Users\Kaiser\AppData\Local\Programs\Python\Python37-32\lib\ssl.py", line 911, in read
return self._sslobj.read(len, buffer)
urllib3.exceptions.ProtocolError: ('Connection aborted.', ConnectionResetError(10054, 'An existing connection was forcibly closed by the remote host', None, 10054, None))
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "C:/Users/Kaiser/Documents/python ddoser.py", line 19, in <module>
req = requests.post(url, cookies=cookie, params=json.dumps(data).encode('UTF-8'), headers=headers)
File "C:\Users\Kaiser\AppData\Local\Programs\Python\Python37-32\lib\site-packages\requests\api.py", line 116, in post
return request('post', url, data=data, json=json, **kwargs)
File "C:\Users\Kaiser\AppData\Local\Programs\Python\Python37-32\lib\site-packages\requests\api.py", line 60, in request
return session.request(method=method, url=url, **kwargs)
File "C:\Users\Kaiser\AppData\Local\Programs\Python\Python37-32\lib\site-packages\requests\sessions.py", line 533, in request
resp = self.send(prep, **send_kwargs)
File "C:\Users\Kaiser\AppData\Local\Programs\Python\Python37-32\lib\site-packages\requests\sessions.py", line 646, in send
r = adapter.send(request, **kwargs)
File "C:\Users\Kaiser\AppData\Local\Programs\Python\Python37-32\lib\site-packages\requests\adapters.py", line 498, in send
raise ConnectionError(err, request=request)
requests.exceptions.ConnectionError: ('Connection aborted.', ConnectionResetError(10054, 'An existing connection was forcibly closed by the remote host', None, 10054, None))
Does anyone know about what i could be doing wrong. Sorry if its a rookie mistake.
This error occurs when the web server rejects your connection. A web server can reject your connection for various reasons. Most likely, you did not properly mimic the HTTP request the web server was expecting.
You do not have to manually fill in all of the HTTP parameters such content length. The library automatically fills in these fields for you. If you plan to make subsequent HTTP requests using the same cookies, consider creating a session object, which stores and handles the cookies for you:
session = requests.Session()
session.post(url, data=payload)
Also, realize the difference between the data parameter and the params parameter. Since you are sending a POST request, chances are that the web server is expecting the data to be passed via the data parameter (which places the data in the request body rather than the query string in the URL). Another reason a web server may reject your connection is because you sent a HTTP request rather than a HTTPS request, so always ensure everything is correct on your end.
Below the code that i use to send post information and read the response,
import urllib2
from urllib2 import URLError, HTTPError
import urllib
import ssl
mydata=[('funcion',funcion),('codigo',codigo)] #The first is the var name the second is the value
headers = {"Content-type", "application/x-www-form-urlencoded","User-Agent", "Mozilla/5.0",}
handler=urllib2.HTTPHandler(debuglevel=1)
opener = urllib2.build_opener(handler)
urllib2.install_opener(opener)
mydata=urllib.urlencode(mydata)
path=url #the url you want to POST to
ctx = ssl.create_default_context()
ctx.check_hostname = False
ctx.verify_mode = ssl.CERT_NONE #In my case i need accept certificates
req=urllib2.Request(path, mydata)
req.add_header("Content-type", "application/x-www-form-urlencoded")
req.add_header("User-Agent", "Mozilla/5.0")
page=urllib2.urlopen(req).read()

how to translate this code in curl using bash to request in python

I'm trying to translate a bash script that works with curl to send a code remotely to a mega Arduino, using an ESP01 as a programmer with the ESP-link firmware, the bash script that does that work, summarized in a few lines, is this:
#! /bin/bash
# first make a post to reset the arduino
curl -m 10 -s -w '%{http_code}' -XPOST
http://192.168.4.1/pgmmega/sync
sleep 0.5
# make a GET to Sync with it and wait for the sync
curl -s http://192.168.4.1/pgmmega/sync
sleep 0.1
#send the .hex file
curl -m 20 -s -g -d #/tmp/arduino_build_274266/SMI_6_0_1.ino.hex
http://192.168.4.1/pgmmega/upload
And my code in python3 is:
#! /bin/python3
import requests
import time
urlsync = 'http://192.168.4.1/pgmmega/sync'
urlupload = 'http://192.168.4.1/pgmmega/upload'
file = {'upload_file':
open('/home/wander/app_llamadores/SMI_6_0_1.ino.hex', 'rb')}
rsync = requests.post(urlsync, stream=True, timeout = 5)
time.sleep(0.4)
print(rsync1.status_code) #204
rsync1 = requests.get(urlsync)
print(rsync1.status_code) #200
rupload = requests.post(urlupload, files=file, timeout=20)
print(rupload.status_code)
I tried with that code, and although the synchronization part seems to work fine, when I send the .hex file, I get this ..
Traceback (most recent call last):
File "/usr/lib/python3/dist-packages/urllib3/connectionpool.py",
line 387, in _make_request
six.raise_from(e, None)
File "<string>", line 3, in raise_from
File "/usr/lib/python3/dist-packages/urllib3/connectionpool.py",
line 383, in _make_request
httplib_response = conn.getresponse()
File "/usr/lib/python3.6/http/client.py", line 1331, in
getresponse
response.begin()
File "/usr/lib/python3.6/http/client.py", line 297, in begin
version, status, reason = self._read_status()
File "/usr/lib/python3.6/http/client.py", line 258, in
_read_status
line = str(self.fp.readline(_MAXLINE + 1), "iso-8859-1")
File "/usr/lib/python3.6/socket.py", line 586, in readinto
return self._sock.recv_into(b)
socket.timeout: timed out
During handling of the above exception, another exception
occurred:
Traceback (most recent call last):
File "/usr/lib/python3/dist-packages/requests/adapters.py", line
440, in send
timeout=timeout
File "/usr/lib/python3/dist-packages/urllib3/connectionpool.py",
line 639, in urlopen
_stacktrace=sys.exc_info()[2])
File "/usr/lib/python3/dist-packages/urllib3/util/retry.py",
line 357, in increment
raise six.reraise(type(error), error, _stacktrace)
File "/usr/lib/python3/dist-packages/six.py", line 693, in
reraise
raise value
File "/usr/lib/python3/dist-packages/urllib3/connectionpool.py",
line 601, in urlopen
chunked=chunked)
File "/usr/lib/python3/dist-packages/urllib3/connectionpool.py",
line 389, in _make_request
self._raise_timeout(err=e, url=url, timeout_value=read_timeout)
File "/usr/lib/python3/dist-packages/urllib3/connectionpool.py",
line 309, in _raise_timeout
raise ReadTimeoutError(self, url, "Read timed out. (read
timeout=%s)" % timeout_value)
urllib3.exceptions.ReadTimeoutError:
HTTPConnectionPool(host='192.168.4.1', port=80): Read timed
out. (read timeout=20)
During handling of the above exception, another exception
occurred:
Traceback (most recent call last):
File "./CargaFirmware.py", line 17, in <module>
rupload = requests.post(urlupload, files=file, stream=True,
timeout=20)
File "/usr/lib/python3/dist-packages/requests/api.py", line 112,
in post
return request('post', url, data=data, json=json, **kwargs)
File "/usr/lib/python3/dist-packages/requests/api.py", line 58,
in request
return session.request(method=method, url=url, **kwargs)
File "/usr/lib/python3/dist-packages/requests/sessions.py", line
520, in request
resp = self.send(prep, **send_kwargs)
File "/usr/lib/python3/dist-packages/requests/sessions.py", line
630, in send
r = adapter.send(request, **kwargs)
File "/usr/lib/python3/dist-packages/requests/adapters.py", line
521, in send
raise ReadTimeout(e, request=request)
requests.exceptions.ReadTimeout:
HTTPConnectionPool(host='192.168.4.1', port=80): Read timed
out. (read timeout=20)
Your curl and requests commands are not equivalent.
With curl you are HTTP POSTing data directly in the request body. With requests you are (implicitly) creating MultiPart Encoded form data, with upload_file field set to the contents of the SMI_6_0_1.ino.hex file.
Simple way to see what is happening under the hood is to prepare request, is to prepare and inspect request without sending:
from requests import Request
url = "http://192.168.4.1/pgmmega/sync"
filename = "SMI_6_0_1.ino.hex"
req = Request("POST", url, files={"upload_file": open(filename, "rb")}).prepare()
print(vars(req)["body"])
# b'--052baa09bbc2f6ab52a2c9f8f2b99b3a\r\nContent-Disposition: form-data; name="upload_file"; filename="SMI_6_0_1.ino.hex"\r\n\r\n\r\n--052baa09bbc2f6ab52a2c9f8f2b99b3a--\r\n'
print(vars(req)["headers"]["Content-Type"])
# multipart/form-data; boundary=052baa09bbc2f6ab52a2c9f8f2b99b3a
and
req = Request("POST", url, data=open(filename, "rb")).prepare()
print(vars(req)["body"])
# <_io.BufferedReader name='SMI_6_0_1.ino.hex'>
print(vars(req)["headers"]["Content-Type"])
# KeyError: 'content-type'
So most probably requests are sending a file in format that cannot be read by target server. In this case, switch to requests.post(url, data=...) should fix the problem.
This is not that uncommon problem. There is a web page, where you can convert curl to requests on your own - https://curl.trillworks.com/

Python script on Ubuntu VM can't connect to twitter API

I am using Ubuntu 12 with VitualBox on top of a Windows XP PC. I am using a proxy to access the internet.
I can browse those websites with Firefox, and for script below:
import urllib2
import json
proxy = urllib2.ProxyHandler({'http': 'http://my-proxy-server:80'})
auth = urllib2.HTTPBasicAuthHandler()
opener = urllib2.build_opener(proxy, auth, urllib2.HTTPHandler)
urllib2.install_opener(opener)
#conn = urllib2.urlopen('http://python.org')
return_str = conn.read()
print return_str
Everything goes well for code above, but for similar code as below is not working.
import urllib2
import json
proxy = urllib2.ProxyHandler({'http': 'http://my-proxy-server:80'})
auth = urllib2.HTTPBasicAuthHandler()
opener = urllib2.build_opener(proxy, auth, urllib2.HTTPHandler)
urllib2.install_opener(opener)
response = urllib.urlopen('https://api.twitter.com/1.1/search/tweets.json?q=microsoft')
print json.load(response)
The error log is as below.
Traceback (most recent call last):
File "print.py", line 12, in <module>
conn = urllib2.urlopen('https://api.twitter.com/1.1/search/tweets.json?q=microsoft')
File "/usr/lib/python2.7/urllib2.py", line 126, in urlopen
return _opener.open(url, data, timeout)
File "/usr/lib/python2.7/urllib2.py", line 400, in open
response = self._open(req, data)
File "/usr/lib/python2.7/urllib2.py", line 418, in _open
'_open', req)
File "/usr/lib/python2.7/urllib2.py", line 378, in _call_chain
result = func(*args)
File "/usr/lib/python2.7/urllib2.py", line 1215, in https_open
return self.do_open(httplib.HTTPSConnection, req)
File "/usr/lib/python2.7/urllib2.py", line 1177, in do_open
raise URLError(err)
urllib2.URLError: <urlopen error [Errno 113] No route to host>
Please help me out. Thanks.
Try creating a https handler and see if that fixes the problem.
Change this line:
proxy = urllib2.ProxyHandler({'http': 'http://my-proxy-server:80'})
to
proxy = urllib2.ProxyHandler({'https': 'http://my-proxy-server:80'})
and see if that works, since the Twitter API you are trying to access is over HTTPS.

Program abruptly stops and throws URLERROR

from poster.encode import multipart_encode
from poster.streaminghttp import register_openers
def picscrazy(str,int):
register_openers()
datagen, headers = multipart_encode({"imagefile[]": open(str, "rb")})
request = urllib2.Request("http://www.picscrazy.com/process.php", datagen, headers)
Str is the filename and the int is just another flag.
The code is to upload a file to a image hosting website .I am using poster Poster for the post requests. The program stops after the request statement and gives an error .I cant understand the error whether its a problem in my network or in the program.
Below is the traceback of the error:
Traceback (most recent call last):
File "C:\Documents and Settings\Administrator\Desktop\for exbii\res.py", line 42, in <module>
picscrazy(fname,1)
File "C:\Documents and Settings\Administrator\Desktop\for exbii\res.py", line 14, in picscrazy
print(urllib2.urlopen(request).read())
File "C:\Python25\Lib\urllib2.py", line 121, in urlopen
return _opener.open(url, data)
File "C:\Python25\Lib\urllib2.py", line 374, in open
response = self._open(req, data)
File "C:\Python25\Lib\urllib2.py", line 392, in _open
'_open', req)
File "C:\Python25\Lib\urllib2.py", line 353, in _call_chain
result = func(*args)
File "C:\Python25\lib\poster\streaminghttp.py", line 142, in http_open
return self.do_open(StreamingHTTPConnection, req)
File "C:\Python25\Lib\urllib2.py", line 1076, in do_open
raise URLError(err)
URLError: <urlopen error (10054, 'Connection reset by peer')>
If you can't display the header coming back from the server, then, your server has simply cut you off.
It may be your request is bad -- but that's unlikely.
It may be that you've exceeded bandwidth restrictions.
It may be that your requests appear to be a DDOS attack because they're happening too frequently.

Categories