import json, requests
def tick():
r = requests.get('https://stocks.exchange/api2/ticker')
return r.json()
print tick()
This code outputs,
Traceback (most recent call last):
File "C:\Users\Steven\Desktop\Auto\tradeogre\stocksexchange.py", line 6, in
<module>
print tick()
File "C:\Users\Steven\Desktop\Auto\tradeogre\stocksexchange.py", line 4, in
tick
r = requests.get('https://stocks.exchange/api2/ticker')
File "C:\Python27\lib\site-packages\requests\api.py", line 72, in get
return request('get', url, params=params, **kwargs)
File "C:\Python27\lib\site-packages\requests\api.py", line 58, in request
return session.request(method=method, url=url, **kwargs)
File "C:\Python27\lib\site-packages\requests\sessions.py", line 508, in
request
resp = self.send(prep, **send_kwargs)
File "C:\Python27\lib\site-packages\requests\sessions.py", line 618, in send
r = adapter.send(request, **kwargs)
File "C:\Python27\lib\site-packages\requests\adapters.py", line 506, in send
raise SSLError(e, request=request)
SSLError: HTTPSConnectionPool(host='stocks.exchange', port=443): Max retries
exceeded with url: /api2/ticker (Caused by SSLError(SSLEOFError(8, u'EOF
occurred in violation of protocol (_ssl.c:661)'),))
How would I do this without violating the protocol? I have used urllib, urllib2, and get similer responses. If I enter the url in the browser, it displays the data I need. Any help would be greatly appreciated.
Related
I'm trying to deploy Telegram bot on pythonanywhere. Here is my code. All was working until I updated repository. Nothing was change in this piece of code. But it happed not working now. The get_message function not even calls. May be it is some problems with JSON or so, i don't understand exactly. How to get rid of this error?
URL = 'name.pythonanywhere.com'
app = Flask(__name__)
sslify = SSLify(app)
bot.remove_webhook()
bot.set_webhook(url=URL)
bot.send_message(userID, 'helo')
#app.route('/', methods=['POST', 'GET'])
def get_message():
update = types.Update.de_json(request.stream.read().decode('utf-8'))
bot.process_new_updates([update])
return 'ok', 200
2023-01-15 22:15:05,776: Exception on / [GET]
Traceback (most recent call last):
File "/home/kentus/.local/lib/python3.9/site-packages/flask/app.py", line 2077, in wsgi_app
response = self.full_dispatch_request()
File "/home/kentus/.local/lib/python3.9/site-packages/flask/app.py", line 1526, in full_dispatch_request
return self.finalize_request(rv)
File "/home/kentus/.local/lib/python3.9/site-packages/flask/app.py", line 1545, in finalize_request
response = self.make_response(rv)
File "/home/kentus/.local/lib/python3.9/site-packages/flask/app.py", line 1701, in make_response
raise TypeError(
TypeError: The view function for 'get_message' did not return a valid response. The function either returned None or ended without a return statement.
2023-01-15 22:52:17,579: Exception on / [GET]
Traceback (most recent call last):
File "/home/kentus/.local/lib/python3.9/site-packages/flask/app.py", line 2077, in wsgi_app
response = self.full_dispatch_request()
File "/home/kentus/.local/lib/python3.9/site-packages/flask/app.py", line 1525, in full_dispatch_request
rv = self.handle_user_exception(e)
File "/home/kentus/.local/lib/python3.9/site-packages/flask/app.py", line 1523, in full_dispatch_request
rv = self.dispatch_request()
File "/home/kentus/.local/lib/python3.9/site-packages/flask/app.py", line 1509, in dispatch_request
return self.ensure_sync(self.view_functions[rule.endpoint])(**req.view_args)
File "/home/kentus/english_bot/app/main.py", line 177, in get_message
update = types.Update.de_json(request.stream.read().decode('utf-8'))
File "/home/kentus/.local/lib/python3.9/site-packages/telebot/types.py", line 96, in de_json
obj = cls.check_json(json_string, dict_copy=False)
File "/home/kentus/.local/lib/python3.9/site-packages/telebot/types.py", line 80, in check_json
return json.loads(json_type)
File "/usr/local/lib/python3.9/json/__init__.py", line 346, in loads
return _default_decoder.decode(s)
File "/usr/local/lib/python3.9/json/decoder.py", line 337, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "/usr/local/lib/python3.9/json/decoder.py", line 355, in raw_decode
raise JSONDecodeError("Expecting value", s, err.value) from None
json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)
I tried to manipulate the webhook but it ok with it. I guess. getWebhookInfo method shows correct url.
i tried to run locally flask app with public URL using ngrok to debug it locally, but i had errors with setting webhook on ngrok URL.
I even asked ChatGPT and he didn't help.
I bought a Sonoff Basic R3 to use use in DIY mode with a Raspberry Pi. The firmware I've confirmed is 3.6.0 so DIY v2.0. The DIY connection process works fine using 10.10.7.1 and it connects to the router and I have assigned it a static IP address. I can ping it no problem.
Ping statistics for 10.0.0.35:
Packets: Sent = 4, Received = 4, Lost = 0 (0% loss),
Approximate round trip times in milli-seconds:
Minimum = 3ms, Maximum = 97ms, Average = 53ms
But when I run the Raspberry Pi (connected to the same router with the same subnet etc) http post json code
import requests
import json
#API details
url = "https://10.0.0.35:8081/zeroconf/switch"
body = {"deviceid": "", "data": {"switch": "on"} }
headers = {'Content-Type': 'application/json'}
#Making http post request
response = requests.post(url, headers=headers, data=body, verify=False)
print(response)
It just hangs up until I keyboard interrupt (Ctrl-C). I'm pretty sure it is some sort of connection/port issue as the outcome of the code is the same whether or not the device is powered up (I've also tried a number of variations of the json post code using info, switch: off etc all with the same outcome).
^CTraceback (most recent call last):
File "/home/pi/Programmes/sonoff3.py", line 10, in <module>
response = requests.post(url, headers=headers, data=body, verify=False)
File "/usr/lib/python3/dist-packages/requests/api.py", line 119, in post
return request('post', url, data=data, json=json, **kwargs)
File "/usr/lib/python3/dist-packages/requests/api.py", line 61, in request
return session.request(method=method, url=url, **kwargs)
File "/usr/lib/python3/dist-packages/requests/sessions.py", line 542, in request
resp = self.send(prep, **send_kwargs)
File "/usr/lib/python3/dist-packages/requests/sessions.py", line 655, in send
r = adapter.send(request, **kwargs)
File "/usr/lib/python3/dist-packages/requests/adapters.py", line 439, in send
resp = conn.urlopen(
File "/usr/lib/python3/dist-packages/urllib3/connectionpool.py", line 699, in urlopen
httplib_response = self._make_request(
File "/usr/lib/python3/dist-packages/urllib3/connectionpool.py", line 445, 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 440, in _make_request
httplib_response = conn.getresponse()
File "/usr/lib/python3.9/http/client.py", line 1347, in getresponse
response.begin()
File "/usr/lib/python3.9/http/client.py", line 307, in begin
version, status, reason = self._read_status()
File "/usr/lib/python3.9/http/client.py", line 268, in _read_status
line = str(self.fp.readline(_MAXLINE + 1), "iso-8859-1")
File "/usr/lib/python3.9/socket.py", line 704, in readinto
return self._sock.recv_into(b)
KeyboardInterrupt
So after 8 hours of trying yesterday and another few today I'm at a loss so any pointers as to what else to try would be great. Thanks.
I stumbled across an issue which causes the below script to throw an error every so often, like every other day on average.
The script is being run 24/7 and dozens of instances similar to it are being run simultaneously. That seems to be relevant because as can be seen from the error, it appears to throw it on another instance (different asset than the one being retrieved).
OS: W10
Programming Language version: 3.9
CCXT version: 1.54.87
import ccxt
import pandas_ta as ta
import config
import schedule
import pandas as pd
from datetime import datetime
import time
import socket
pd.set_option('display.max_rows', None)
pd.set_option('display.max_columns', None)
pd.set_option('display.width', 250)
exchange = ccxt.binance({
'apiKey': config.BINANCE_API_KEY,
'secret': config.BINANCE_API_SECRET,
'enableRateLimit': True,
'options': {
'defaultType': 'future'
},
})
in_position = False
free_balance = exchange.fetch_free_balance()
used_balance = exchange.fetch_used_balance()
free_usd = (free_balance['USDT'])
used_usd = (used_balance['USDT'])
amount = free_usd + used_usd
quantity = 0
new_quantity = 0
def trigger(df):
// strategy
def algo():
print(f"Loading data as of {datetime.now().isoformat()}")
bars = exchange.fetch_ohlcv('BNB/USDT', timeframe='30m', limit=50)
df = pd.DataFrame(bars, columns=['time', 'open', 'high', 'low', 'close', 'volume'])
df['time'] = pd.to_datetime(df['time'], unit='ms')
df.set_index(pd.DatetimeIndex(df['time']), inplace=True)
trigger(df)
try:
schedule.every(2).seconds.do(algo)
while True:
schedule.run_pending()
time.sleep(1)
except ConnectionResetError:
schedule.every(3).seconds.do(algo)
while True:
schedule.run_pending()
time.sleep(1)
except socket.timeout:
schedule.every(3).seconds.do(algo)
while True:
schedule.run_pending()
time.sleep(1)
Traceback (most recent call last):
File "C:\Users\", line 699, in urlopen
httplib_response = self._make_request(
File "C:\Users\", line 445, in _make_request
six.raise_from(e, None)
File "<string>", line 3, in raise_from
File "C:\Users\", line 440, in _make_request
httplib_response = conn.getresponse()
File "C:\Users\", line 1349, in getresponse
response.begin()
File "C:\Users\", line 316, in begin
version, status, reason = self._read_status()
File "C:\Users\", line 277, in _read_status
line = str(self.fp.readline(_MAXLINE + 1), "iso-8859-1")
File "C:\Users\", line 704, in readinto
return self._sock.recv_into(b)
File "C:\Users\", line 1241, in recv_into
return self.read(nbytes, buffer)
File "C:\Users\", line 1099, 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\", line 439, in send
resp = conn.urlopen(
File "C:\Users\", line 755, in urlopen
retries = retries.increment(
File "C:\Users\", line 532, in increment
raise six.reraise(type(error), error, _stacktrace)
File "C:\Users\", line 769, in reraise
raise value.with_traceback(tb)
File "C:\Users\", line 699, in urlopen
httplib_response = self._make_request(
File "C:\Users\", line 445, in _make_request
six.raise_from(e, None)
File "<string>", line 3, in raise_from
File "C:\Users\", line 440, in _make_request
httplib_response = conn.getresponse()
File "C:\Users\", line 1349, in getresponse
response.begin()
File "C:\Users\", line 316, in begin
version, status, reason = self._read_status()
File "C:\Users\", line 277, in _read_status
line = str(self.fp.readline(_MAXLINE + 1), "iso-8859-1")
File "C:\Users\", line 704, in readinto
return self._sock.recv_into(b)
File "C:\Users\", line 1241, in recv_into
return self.read(nbytes, buffer)
File "C:\Users\", line 1099, 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\", line 571, in fetch
response = self.session.request(
File "C:\Users\", line 542, in request
resp = self.send(prep, **send_kwargs)
File "C:\Users\", line 655, in send
r = adapter.send(request, **kwargs)
File "C:\Users\", 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))
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\", line 79, in <module>
schedule.run_pending()
File "C:\Users\", line 780, in run_pending
default_scheduler.run_pending()
File "C:\Users\", line 100, in run_pending
self._run_job(job)
File "C:\Users\", line 172, in _run_job
ret = job.run()
File "C:\Users\", line 661, in run
ret = self.job_func()
File "C:\Users\", line 67, in algo
bars = exchange.fetch_ohlcv('ADA/USDT', timeframe='15m', limit=300)
File "C:\Users\", line 1724, in fetch_ohlcv
response = getattr(self, method)(self.extend(request, params))
File "C:\Users\", line 463, in inner
return entry(_self, **inner_kwargs)
File "C:\Users\", line 4119, in request
response = self.fetch2(path, api, method, params, headers, body)
File "C:\Users\", line 486, in fetch2
return self.fetch(request['url'], request['method'], request['headers'], request['body'])
File "C:\Users\", line 623, in fetch
raise NetworkError(details) from e
ccxt.base.errors.NetworkError: binance GET https://fapi.binance.com/fapi/v1/klines?symbol=ADAUSDT&interval=15m&limit=300
I got the same problem, my browser was able to access the url fine, but pycharm ran with a network error, i m using proxy to access binance.com , and my pycharm proxy setting is manual and Connection detection is normal
I have a CSV file, which contains a list of Google extension IDs.
I'm writing a code that will read the extension IDs, add the webstore url, then perform a basic get request:
import csv
import requests
with open('small.csv', 'rb') as f:
reader = csv.reader(f)
for row in reader:
urls = "https://chrome.google.com/webstore/detail/" + row[0]
print urls
r = requests.get([urls])
Running this code results in the following Traceback:
Traceback (most recent call last):
File "C:\Users\tom\Dropbox\Python\panya\test.py", line 9, in <module>
r = requests.get([urls])
File "C:\Python27\lib\site-packages\requests\api.py", line 69, in get
return request('get', url, params=params, **kwargs)
File "C:\Python27\lib\site-packages\requests\api.py", line 50, in request
response = session.request(method=method, url=url, **kwargs)
File "C:\Python27\lib\site-packages\requests\sessions.py", line 465, in request
resp = self.send(prep, **send_kwargs)
File "C:\Python27\lib\site-packages\requests\sessions.py", line 567, in send
adapter = self.get_adapter(url=request.url)
File "C:\Python27\lib\site-packages\requests\sessions.py", line 641, in get_adapter
raise InvalidSchema("No connection adapters were found for '%s'" % url)
InvalidSchema: No connection adapters were found for '['https://chrome.google.com/webstore/detail/blpcfgokakmgnkcojhhkbfbldkacnbeo']'
How can revise the code, so that it would accept the urls in the list, and make the GET request?
requests.get expects a string, but you're creating and passing a list [urls]
r = requests.get([urls])
Change it to just
r = requests.get(urls)
and it should work.
I can't for the life of me figure out why I can't catch this exception.
Looking here at this guide.
def get_team_names(get_team_id_url, team_id):
print(get_team_id_url + team_id)
try:
response = urllib.request.urlopen(get_team_id_url + team_id)
except urllib.error.HTTPError as e:
print(e.code)
print(e.read())
except urllib.error.URLError as e:
print(e.code)
print(e.read())
exception:
Traceback (most recent call last):
File "queue_cleaner_main.py", line 60, in <module>
sys.exit(main())
File "queue_cleaner_main.py", line 57, in main
team_names_to_contact = queue_cleaner_functions.get_team_names(SERVICE_NOW_TEAM_NAME_URL, team[2])
File "D:\oppssup\old_job\queue_cleaner_functions.py", line 132, in get_team_names
response = urllib.request.urlopen(get_team_id_url + team_id)
File "C:\Python34\lib\urllib\request.py", line 153, in urlopen
return opener.open(url, data, timeout)
File "C:\Python34\lib\urllib\request.py", line 455, in open
response = self._open(req, data)
File "C:\Python34\lib\urllib\request.py", line 473, in _open
'_open', req)
File "C:\Python34\lib\urllib\request.py", line 433, in _call_chain
result = func(*args)
File "C:\Python34\lib\urllib\request.py", line 1202, in http_open
return self.do_open(http.client.HTTPConnection, req)
File "C:\Python34\lib\urllib\request.py", line 1177, in do_open
r = h.getresponse()
File "C:\Python34\lib\http\client.py", line 1172, in getresponse
response.begin()
File "C:\Python34\lib\http\client.py", line 351, in begin
version, status, reason = self._read_status()
File "C:\Python34\lib\http\client.py", line 321, in _read_status
raise BadStatusLine(line)
http.client.BadStatusLine: ''
In addition, my entire method seems to be very clunky. I cannot figure out an elegant way to handle exceptions, including a case where no result is returned.
def get_team_names(get_team_id_url, team_id):
print(get_team_id_url + team_id)
try:
response = urllib.request.urlopen(get_team_id_url + team_id)
except Exception as e:
#print(e.code)
#print(e.read())
print('shit')
#print(response.read().decode('utf8'))
r_json = json.loads(response.read().decode('utf8'))
print(r_json['result'])
for i in r_json['result']:
print(i['group'])
Exception:
Traceback (most recent call last):
File "queue_cleaner_main.py", line 60, in <module>
sys.exit(main())
File "queue_cleaner_main.py", line 57, in main
team_names_to_contact = queue_cleaner_functions.get_team_names(SERVICE_NOW_TEAM_NAME_URL, team[2])
File "D:\oppssup\old_job\queue_cleaner_functions.py", line 141, in get_team_names
r_json = json.loads(response.read().decode('utf8'))
UnboundLocalError: local variable 'response' referenced before assignment
This http.client.BadStatusLine is a subclass of http.client.HTTPException. I think if you do:
try:
response = urllib.request.urlopen(get_team_id_url + team_id)
except http.client.HTTPException as e:
print(e)
then you shouldn't have problem catching it. However, what caused it is perhaps what you should concern.