Catching multiple exceptions - Python - api

I have a program that occasionally throws a badStatusLine exception, after catching it we are now getting another error and I can't seem to catch it so the program doesn't stop. Here is what I have, any help would be appreciated.
The error:
Exception in thread Thread-1:
Traceback (most recent call last):
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/threading.py", line 810, in __bootstrap_inner
self.run()
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/threading.py", line 763, in run
self.__target(*self.__args, **self.__kwargs)
File "/Users/mattduhon/trading4.py", line 30, in trade
execution.execute_order(event)
File "/Users/mattduhon/execution.py", line 33, in execute_order
params, headers
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/httplib.py", line 1001, in request
self._send_request(method, url, body, headers)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/httplib.py", line 1029, in _send_request
self.putrequest(method, url, **skips)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/httplib.py", line 892, in putrequest
raise CannotSendRequest()
CannotSendRequest
The file responsible for catching the error:
import httplib
import urllib
from httplib import BadStatusLine
from httplib import CannotSendRequest
class Execution(object):
def __init__(self, domain, access_token, account_id):
self.domain = domain
self.access_token = access_token
self.account_id = account_id
self.conn = self.obtain_connection()
def obtain_connection(self):
return httplib.HTTPSConnection(self.domain)
def execute_order(self, event):
headers = {
"Content-Type": "application/x-www-form-urlencoded",
"Authorization": "Bearer " + self.access_token}
params = urllib.urlencode({
"instrument" : event.instrument,
"units" : event.units,
"type" : event.order_type,
"side" : event.side,
"stopLoss" : event.stopLoss,
"takeProfit" : event.takeProfit
})
self.conn.request(
"POST",
"/v1/accounts/%s/orders" % str(self.account_id),
params, headers)
try:
response = self.conn.getresponse().read()
except BadStatusLine as e:
print(e)
except CannotSendRequest as a: ######my attempt at catching the error
print(a)
else:
print response

If you change the final else to:
except:
print "Unexpected error:", sys.exc_info()[0]
raise
You should get the real uncaught error if it's really coming from the try-catch block. But are you sure you haven't gotten into a bad state which excepts outside that block?

Related

python configparser key error raised when using Globally

When I'm trying to pass the API endpoint values in the post API file, KeryError has unfortunately been raised. In the baseapi.ini file, I wrote [API] endpoint = value
Post API file:
import requests
from APIs.payLoad import addBookPayload
from Utilities.configration import config
from Utilities.resources import *
url = config()['API']['endpoint']+ApiResources.addBook
header = {"Content-Type": "application/json"}
response = requests.post(url, json=addBookPayload("pl74"), headers=header,)
print(response.json())
response_json = response.json()
book_ID = response_json['ID']
Error:
Traceback (most recent call last):
File "C:\Users\Muhammad Azmul Haq\PycharmProjects\BackEndProject\APIs\PostAPI.py", line 8, in <module>
url = config()['API']['endpoint']+ApiResources.addBook
File "C:\Users\Muhammad Azmul Haq\AppData\Local\Programs\Python\Python39\lib\configparser.py", line 960, in __getitem__
raise KeyError(key)
KeyError: 'API'
Does anyone have an idea what I did wrong Kind regards?
You are not initializing your global variable in config before accessing it. Try assigning value in the current file,
or
Put all configure in the separate configuration file and import that configuration file.

bot.sendAudio and bot.sendPhoto methods in telepot return { 'error code' : 400 , 'Bad Request: wrong HTTP URL specified'}

I am using the
telepot.Bot(bot_id).sendAudio(chat_id, file_url)
method, is supposed to send the file, but it returns
Traceback (most recent call last):
File "C:\Users\vinu\AppData\Local\Programs\Python\Python37\lib\site-packages\telepot\__init__.py", line 1158, in collector
callback(item)
File "bot.py", line 72, in handle
bot.sendAudio(chat_id, url)
File "C:\Users\vinu\AppData\Local\Programs\Python\Python37\lib\site-packages\telepot\__init__.py", line 556, in sendAudio
return self._api_request_with_file('sendAudio', _rectify(p), 'audio', audio)
File "C:\Users\vinu\AppData\Local\Programs\Python\Python37\lib\site-packages\telepot\__init__.py", line 496, in _api_request_with_file
return self._api_request(method, _rectify(params), **kwargs)
File "C:\Users\vinu\AppData\Local\Programs\Python\Python37\lib\site-packages\telepot\__init__.py", line 491, in _api_request
return api.request((self._token, method, params, files), **kwargs)
File "C:\Users\vinu\AppData\Local\Programs\Python\Python37\lib\site-packages\telepot\api.py", line 155, in request
return _parse(r)
File "C:\Users\vinu\AppData\Local\Programs\Python\Python37\lib\site-packages\telepot\api.py", line 150, in _parse
raise exception.TelegramError(description, error_code, data)
telepot.exception.TelegramError: ('Bad Request: wrong HTTP URL specified', 400, {'ok': False, 'error_code': 400, 'description': 'Bad Request: wrong HTTP URL specified'})
the same happened with sendPhoto, but I used python requests to send photos
response =requests.post('https://api.telegram.org/bot/sendphoto', files=files`)
I either want to know why the sendAudio() and sendPhoto() methods work or the http url to send audio
with telepot bot.SendPhoto and bot.sendVideo and bot.sendAudio work either with files and urls that contains a file.
In your case it seems that you used and url and it was uncorrect, can you share it?
In my experience it can be because the url contains & instead of &

JSONDecodeError with Scrapy: Expecting value: line 1 column 1 (char 0)

I am using requests in order to fetch and parse some data scraped using Scrapy with Scrapyrt (real time scraping).
This is how I do it:
#pass spider to requests parameters #
params = {
'spider_name': spider,
'start_requests':True
}
# scrape items
response = requests.get('http://scrapyrt:9080/crawl.json', params)
print ('RESPONSE JSON',response.json())
data = response.json()
As per Scrapy documentation, with 'start_requests' parameter set as True, the spider automatically requests urls and passes the response to the parse method which is the default method used for parsing requests.
start_requests
type: boolean
optional
Whether spider should execute Scrapy.Spider.start_requests method. start_requests are executed by default when you run Scrapy Spider normally without ScrapyRT, but this method is NOT executed in API by default. By default we assume that spider is expected to crawl ONLY url provided in parameters without making any requests to start_urls defined in Spider class. start_requests argument overrides this behavior. If this argument is present API will execute start_requests Spider method.
But the setup is not working. Log:
[2019-05-19 06:11:14,835: DEBUG/ForkPoolWorker-4] Starting new HTTP connection (1): scrapyrt:9080
[2019-05-19 06:11:15,414: DEBUG/ForkPoolWorker-4] http://scrapyrt:9080 "GET /crawl.json?spider_name=precious_tracks&start_requests=True HTTP/1.1" 500 7784
[2019-05-19 06:11:15,472: ERROR/ForkPoolWorker-4] Task project.api.routes.background.scrape_allmusic[87dbd825-dc1c-4789-8ee0-4151e5821798] raised unexpected: JSONDecodeError('Expecting value: line 1 column 1 (char 0)',)
Traceback (most recent call last):
File "/usr/lib/python3.6/site-packages/celery/app/trace.py", line 382, in trace_task
R = retval = fun(*args, **kwargs)
File "/usr/lib/python3.6/site-packages/celery/app/trace.py", line 641, in __protected_call__
return self.run(*args, **kwargs)
File "/usr/src/app/project/api/routes/background.py", line 908, in scrape_allmusic
print ('RESPONSE JSON',response.json())
File "/usr/lib/python3.6/site-packages/requests/models.py", line 897, in json
return complexjson.loads(self.text, **kwargs)
File "/usr/lib/python3.6/json/__init__.py", line 354, in loads
return _default_decoder.decode(s)
File "/usr/lib/python3.6/json/decoder.py", line 339, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "/usr/lib/python3.6/json/decoder.py", line 357, in raw_decode
raise JSONDecodeError("Expecting value", s, err.value) from None
json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)
The error was due to a bug with Twisted 19.2.0, a scrapyrt dependency, which assumed response to be of wrong type.
Once I installed Twisted==18.9.0, it worked.

Google Oauth2 refresh token error using python-social-auth

I'm using python-social-auth and when I try to refresh my Google Oauth2 access token I get the following error:
[2017-02-15 14:41:00,089: ERROR/MainProcess] Task tasks.tasks.test_login[169e5810-489d-4134-af8f-db3b80629fd2] raised unexpected: HTTPError(u'400 Client Error: Bad Request for url: https://accounts.google.com/o/oauth2/token',)
Traceback (most recent call last):
File "/usr/local/lib/python2.7/dist-packages/celery/app/trace.py", line 240, in trace_task
R = retval = fun(*args, **kwargs)
File "/usr/local/lib/python2.7/dist-packages/celery/app/trace.py", line 438, in __protected_call__
return self.run(*args, **kwargs)
File "/home/paulozullu/dev/workspaces/wopik/wopik/tasks/tasks.py", line 1928, in test_login
social.refresh_token(strategy)
File "/usr/local/lib/python2.7/dist-packages/social/storage/base.py", line 54, in refresh_token
response = backend.refresh_token(token, *args, **kwargs)
File "/usr/local/lib/python2.7/dist-packages/social/backends/oauth.py", line 418, in refresh_token
request = self.request(url, **request_args)
File "/usr/local/lib/python2.7/dist-packages/social/backends/base.py", line 225, in request
response.raise_for_status()
File "/usr/local/lib/python2.7/dist-packages/requests/models.py", line 909, in raise_for_status
raise HTTPError(http_error_msg, response=self)
HTTPError: 400 Client Error: Bad Request for url: https://accounts.google.com/o/oauth2/token
I use the following code to refresh the access token:
from social.apps.django_app.utils import load_strategy
w_user = WUser.objects.get(auth_user=A('username','xxxx'))
social = UserSocialAuth.objects.get(user_id=w_user.auth_user.id)
strategy = load_strategy()
social.refresh_token(strategy)
Am I doing something wrong?
I had the same problem when calling social.get_access_token(load_strategy()). If you don't want to implement Google sign-in manually, I used this workaround which forces the user to re-authenticate to refresh their tokens.
try:
strategy = load_strategy()
access_token = social.get_access_token(ls)
except HTTPError as e:
return HttpResponseRedirect(reverse('social:begin', kwargs={'backend': "google-oauth2"}))
As yilmazhuseyin pointed above, the issue is related to refresh token not being present. You need to pass access_type='offline' in the parameters in order for Google to return the refresh token. This can be done by adding the following in settings.py for python-social-auth in django:
SOCIAL_AUTH_GOOGLE_OAUTH2_AUTH_EXTRA_ARGUMENTS = {
'access_type': 'offline',
}
More details can be found in Google OAuth 2.0 documentation.

Odoo JSONRPC service (http.route type=json) not work

I'm trying create jsonrpc service in odoo. When I created clean module using doc https://www.odoo.com/documentation/8.0/howtos/website.html and added such code
**[controllers.py]**
#http.route(['/my_academy/ret/'], type='json', auth="public")
def change_size(self):
return {'x': 1, 'y': 2}
try to connect from js:
"use strict";
var requestUrl = '/my_academy/ret/';
openerp.jsonRpc(requestUrl, 'call', {})
.then(function (data) {
alert(data['x']);
});
All work fine. I receive message '1'.
When i created module using doc https://www.odoo.com/documentation/8.0/howtos/backend.html and added such code
**[controllers.py]**
#http.route(['/academy/jsonrpc/'], type='json', auth="public")
def return_map(self):
return {'x': 12345, 'y': 2222}
Modify js and try to connect
"use strict";
var requestUrl = '/academy/jsonrpc/';
openerp.jsonRpc(requestUrl, 'call', {})
.then(function (data) {
alert(data['x']);
});
I receive error
code: 200
data: Object
arguments: Array[0]
length: 0
__proto__: Array[0]
....
debug: "Traceback (most recent call last):↵
File "/home/skif/odoo/openerp/http.py", line 539, in _handle_exception↵
return super(JsonRequest, self)._handle_exception(exception)↵
File "/home/skif/odoo/openerp/addons/base/ir/ir_http.py", line 152, in _dispatch↵
rule, arguments = self._find_handler(return_rule=True)↵
File "/home/skif/odoo/openerp/addons/base/ir/ir_http.py", line 65, in _find_handler↵
return self.routing_map().bind_to_environ(request.httprequest.environ).match(return_rule=return_rule)↵
File "/usr/local/lib/python2.7/dist-packages/werkzeug/routing.py", line 1430, in match↵
raise NotFound()↵
NotFound: 404: Not Found↵"
message: ""
name: "werkzeug.exceptions.NotFound"
__proto__: Object
message: "Odoo Server Error"
__proto__:Object
What am I doing wrong? Why can't I use similar code?
try this code:
#http.route(['/academy/jsonrpc'], type='json', auth="public", website=True)
def return_map(self, **post):
return {'x': 12345, 'y': 2222}
it may help in your case.