Python Tuple Problems - python

I'm new to python and as far as i can tell i'm recieving this Tuple Error:
Traceback (most recent call last):
File "/home/cambria/Main.py", line 10, in <module>
main()
File "/home/cambria/Main.py", line 5, in main
respons3 = api.get_summoner_by_name('hi im gosan')
File "/home/cambria/RiotAPI.py", line 31, in get_summoner_by_name
return self._request(api_url)
File "/home/cambria/RiotAPI.py", line 12, in _request
for key, value in params.items():
AttributeError: 'tuple' object has no attribute 'items'
in
def _request(self, api_url, params=()):
args = {'api_key': self.api_key}
for key, value in params.items():
if key not in args:
args[key] = value
response = requests.get(
Consts.URL['base'].format(
proxy=self.region,
region=self.region,
url=api_url
),
params=args
)
print response.url
return response.json()
this is the only error i have received that i really don't know much on. Is this a result of there being no .items on my params? or i left it initialized as an empty dictionary?
EDIT 1: Have tried tinkering with the Tuple and items thing but just not having any luck, my error message is as follows
Traceback (most recent call last):
File "/home/cambria/Desktop/api/Main.py", line 10, in <module>
main()
File "/home/cambria/Desktop/api/Main.py", line 5, in main
respons3 = api.get_summoner_by_name('hi im gosan')
File "/home/cambria/Desktop/api/RiotAPI.py", line 33, in get_summoner_by_name
return self._request(api_url)
File "/home/cambria/Desktop/api/RiotAPI.py", line 23, in _request
params=args
File "/home/cambria/.local/lib/python2.7/site-packages/requests/api.py", line 69, in get
return request('get', url, params=params, **kwargs)
File "/home/cambria/.local/lib/python2.7/site-packages/requests/api.py", line 50, in request
response = session.request(method=method, url=url, **kwargs)
File "/home/cambria/.local/lib/python2.7/site-packages/requests/sessions.py", line 465, in request
resp = self.send(prep, **send_kwargs)
File "/home/cambria/.local/lib/python2.7/site-packages/requests/sessions.py", line 573, in send
r = adapter.send(request, **kwargs)
File "/home/cambria/.local/lib/python2.7/site-packages/requests/adapters.py", line 415, in send
raise ConnectionError(err, request=request)
ConnectionError: ('Connection aborted.', gaierror(-2, 'Name or service not known'))
>>>
as far as i can tell and have searched, this is a result of the python REQUESTS not going through completely?
and my new code as follows,
def _request(self, api_url, params=None): #edit
if params is None: #edit
params = {} #edit
args = {'api_key': self.api_key}
for key, value in params.items(): #remove?? since there is no .items()?
if key not in args:
args[key] = value
response = requests.get(
Consts.URL['base'].format(
proxy=self.region,
region=self.region,
url=api_url
),
params=args
)
print response.url
return response.json()

Your code expects params to be a dict {} (or have a .items method). You've passed a tuple (). The two are not equivalent.
Set params to None by default, and pass a when needed.
def _request(self, api_url, params=None):
params = params if params is not None else {}
...
Or expect a list of tuples, rather than a dict.
def _request(self, api_url, params=()):
for key, value in params:
...

A tuple () doesn't have a method named items. You probably mistake that for dictionary. Change you code as follows:
def _request(self, api_url, params=None):
if params is None:
params = {}
...

Related

TypeError: 'int' object is not iterable from unittest for api

This is the logs I received from my unittest for my APIs flask application which is using flask-restful, it showed that I have an int object not iterable error.
Really appreciate if anyone tell me what is actually wrong in my unittest codes :(
.
======================================================================
ERROR: test_brand_create (test.brand.BrandTest)
----------------------------------------------------------------------
Traceback (most recent call last):
File "/Users/david/ITP-Team3/test/brand.py", line 37, in test_brand_create
response = tester.post('/api/brand/', data=json.dumps(payload), headers=headers)
File "/Users/david/.local/share/virtualenvs/ITP-Team3-bpvJtb_C/lib/python3.10/site-packages/werkzeug/test.py", line 1140, in post
return self.open(*args, **kw)
File "/Users/david/.local/share/virtualenvs/ITP-Team3-bpvJtb_C/lib/python3.10/site-packages/flask/testing.py", line 217, in open
return super().open(
File "/Users/david/.local/share/virtualenvs/ITP-Team3-bpvJtb_C/lib/python3.10/site-packages/werkzeug/test.py", line 1089, in open
response = self.run_wsgi_app(request.environ, buffered=buffered)
File "/Users/david/.local/share/virtualenvs/ITP-Team3-bpvJtb_C/lib/python3.10/site-packages/werkzeug/test.py", line 956, in run_wsgi_app
rv = run_wsgi_app(self.application, environ, buffered=buffered)
File "/Users/david/.local/share/virtualenvs/ITP-Team3-bpvJtb_C/lib/python3.10/site-packages/werkzeug/test.py", line 1255, in run_wsgi_app
for item in app_iter:
File "/Users/david/.local/share/virtualenvs/ITP-Team3-bpvJtb_C/lib/python3.10/site-packages/werkzeug/wsgi.py", line 462, in __next__
return self._next()
File "/Users/david/.local/share/virtualenvs/ITP-Team3-bpvJtb_C/lib/python3.10/site-packages/werkzeug/wrappers/response.py", line 50, in _iter_encoded
for item in iterable:
TypeError: 'int' object is not iterable
======================================================================
ERROR: test_brand_put (test.brand.BrandTest)
----------------------------------------------------------------------
Traceback (most recent call last):
File "/Users/david/ITP-Team3/test/brand.py", line 49, in test_brand_put
response = tester.put('/api/brand/'+id, data=json.dumps(payload), headers=headers)
File "/Users/david/.local/share/virtualenvs/ITP-Team3-bpvJtb_C/lib/python3.10/site-packages/werkzeug/test.py", line 1145, in put
return self.open(*args, **kw)
File "/Users/david/.local/share/virtualenvs/ITP-Team3-bpvJtb_C/lib/python3.10/site-packages/flask/testing.py", line 217, in open
return super().open(
File "/Users/david/.local/share/virtualenvs/ITP-Team3-bpvJtb_C/lib/python3.10/site-packages/werkzeug/test.py", line 1089, in open
response = self.run_wsgi_app(request.environ, buffered=buffered)
File "/Users/david/.local/share/virtualenvs/ITP-Team3-bpvJtb_C/lib/python3.10/site-packages/werkzeug/test.py", line 956, in run_wsgi_app
rv = run_wsgi_app(self.application, environ, buffered=buffered)
File "/Users/david/.local/share/virtualenvs/ITP-Team3-bpvJtb_C/lib/python3.10/site-packages/werkzeug/test.py", line 1255, in run_wsgi_app
for item in app_iter:
File "/Users/david/.local/share/virtualenvs/ITP-Team3-bpvJtb_C/lib/python3.10/site-packages/werkzeug/wsgi.py", line 462, in __next__
return self._next()
File "/Users/david/.local/share/virtualenvs/ITP-Team3-bpvJtb_C/lib/python3.10/site-packages/werkzeug/wrappers/response.py", line 50, in _iter_encoded
for item in iterable:
TypeError: 'int' object is not iterable
----------------------------------------------------------------------
Ran 11 tests in 2.370s
FAILED (errors=2)
Here's my test code that I had the error on:
# brand.py
def test_brand_create(self):
tester = app.test_client(self)
headers = login(tester)
payload = {'brandName': 'test1'}
response = tester.post('/api/brand/', data=json.dumps(payload), headers=headers)
self.assertEqual(response.status_code, 200)
self.assertEqual(response.content_type, 'application/json')
def test_brand_put(self):
tester = app.test_client(self)
headers = login(tester)
payload = {'brandName': 'test'}
print("TYPE", type(get_id(app, Brand, 'test1')))
print("VALUE", get_id(app, Brand, 'test1'))
id = get_id(app, Brand, 'test1')
response = tester.put('/api/brand/'+id, data=json.dumps(payload), headers=headers)
self.assertEqual(response.status_code, 200)
self.assertEqual(response.content_type, 'application/json')
and the utils code as well
# utils.py
def login(tester):
headers = {'Content-Type': 'application/json'}
# put user and password in .env file
payload = {'username': os.getenv("user"), 'password_hash': os.getenv("password")}
response = tester.post('/api/user/login/', data= json.dumps(payload), headers=headers)
jwt_str = response.data.decode('utf-8')
header_jwt= ast.literal_eval(jwt_str)
return {'Content-Type': 'application/json', 'Authorization': 'Bearer ' + header_jwt['jwt_token']}
def get_id(app, model, brandName) -> None:
with app.app_context():
test_query = model.query.filter_by(brandName=brandName).first()
id_lookup = model.query.get(test_query.id)
return str(id_lookup.id)

How do i correct JSONDecoderError?

import requests
I am trying to send data to an API which works fine but all of a sudden i start getting JSON error
This is the code
def payment(phone, receiver_phone, amount):
req_header = os.environ.get('APP_KEY')
payload = {
'receiver_phone': receiver_phone,
'amount': amount,
'payer_phone': phone
}
res = requests.post('https://sspay.com/payment?key={0}'.format(req_header), data=payload)
return res.json()
print(payment('07XXXXXX', '0XXXXXXXXX', '1'))
This is the output i get
Traceback (most recent call last):
File "test.py", line 25, in <module>
print(payment('07xxxxx', '09xxxxxxxx', '1'))
File "test.py", line 14, in payment
return res.json()
File "/home/pc/.virtualenvs/talk/lib/python3.8/site-packages/requests/models.py", line 897, in json
return complexjson.loads(self.text, **kwargs)
File "/home/pc/.virtualenvs/talk/lib/python3.8/site-packages/simplejson/__init__.py", line 516, in loads
return _default_decoder.decode(s)
File "/home/pc/.virtualenvs/talk/lib/python3.8/site-packages/simplejson/decoder.py", line 370, in decode
obj, end = self.raw_decode(s)
File "/home/pc/.virtualenvs/talk/lib/python3.8/site-packages/simplejson/decoder.py", line 400, in raw_decode
return self.scan_once(s, idx=_w(s, idx).end())
simplejson.scanner.JSONDecodeError: Expecting value: line 1 column 1 (char 0)
use the code below - it will make you to find the issue
req_header = os.environ.get('APP_KEY')
res = requests.post('https://sspay.com/payment?key={0}'.format(req_header), data=payload)
if res.status_code == 200:
data = res.json()
return data
else:
print('We have a problem. status code : {}'.format(res.status_code))
you are not checking the API response (status code)
what if req_header is None

requests' MissingSchema exception for Invalid URL

I am trying to scrape content from a website but I am getting the below mentioned error
The method:
def scrape_newtimes():
"""Scrapes content from the NewTimes"""
url = 'https://www.newtimes.co.rw/'
r = requests.get(url, headers=HEADERS)
tree = fromstring(r.content)
links = tree.xpath('//div[#class="x-small-push clearfix"]/a/#href')
for link in links:
r = requests.get(link, headers=HEADERS)
blog_tree = fromstring(r.content)
paras = blog_tree.xpath('//div[#class="article-content"]/p')
para = extract_paratext(paras)
text = extract_text(para)
if not text:
continue
yield '"%s" %s' % (text, link)
The error I am getting:
>>> sc = scrape_newtimes()
>>> string_1 = next(sc)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "D:\Projects\bird\bird-env\bot.py", line 58, in scrape_newtimes
r = requests.get(link, headers=HEADERS)
File "D:\Projects\bird\venv\lib\site-packages\requests\api.py", line 75, in get
return request('get', url, params=params, **kwargs)
File "D:\Projects\bird\venv\lib\site-packages\requests\api.py", line 60, in request
return session.request(method=method, url=url, **kwargs)
File "D:\Projects\bird\venv\lib\site-packages\requests\sessions.py", line 519, in request
prep = self.prepare_request(req)
File "D:\Projects\bird\venv\lib\site-packages\requests\sessions.py", line 462, in prepare_request
hooks=merge_hooks(request.hooks, self.hooks),
File "D:\Projects\bird\venv\lib\site-packages\requests\models.py", line 313, in prepare
self.prepare_url(url, params)
File "D:\Projects\bird\venv\lib\site-packages\requests\models.py", line 387, in prepare_url
raise MissingSchema(error)
requests.exceptions.MissingSchema: Invalid URL '/news/londons-kings-college-launch-civil-service-programme-rwanda': No schema supplied. Perhaps you meant http:///news/londons-kings-college-launch-civil-service-programme-rwanda?
>>>
The exception basically tells you what is wrong:
requests.exceptions.MissingSchema: Invalid URL '/news/londons-kings-college-launch-civil-service-programme-rwanda': No schema supplied. Perhaps you meant http:///news/londons-kings-college-launch-civil-service-programme-rwanda?
Or with line wrapping the line:
Invalid URL '/news/londons-kings-college-launch-civil-service-programme-rwanda':
No schema supplied. Perhaps you meant
http:///news/londons-kings-college-launch-civil-service-programme-rwanda?
You link does not contain a complete URL

Return a json on browser - Flask

I have this function, it returns a result on console:
numbers_to_add = list(range(10000001))
try:
req = request.Request('http://127.0.0.1:5000/total'
, data=bytes(json.dumps(numbers_to_add), 'utf_8')
, headers={'Content-Type': 'application/json'}
, method='POST')
result = json.loads(request.urlopen(req).read(), encoding='utf_8')
print(json.dumps(result, indent=4))
except Exception as ex:
print(ex)
It returns a result on range 10000001
Now , I want to return this on browser request, in a Flask application, I've tried this:
def hardCoded():
numbers_to_add = list(range(10000001))
try:
req = request.Request('http://127.0.0.1:5000/total'
, data=bytes(json.dumps(numbers_to_add), 'utf_8')
, headers={'Content-Type': 'application/json'}
, method='POST')
result = json.loads(request.urlopen(req).read(), encoding='utf_8')
print(json.dumps(result, indent=4))
except Exception as ex:
print(ex)
class rangeNumbers(Resource):
def get(self, range):
return {'data': directSum.hardCoded(range)}
api.add_resource(rangeNumbers, '/range/<range>')
When I query this on my browser, it throws me this:
Traceback (most recent call last):
File "/home/user/.virtualenvs/test_sum/lib/python3.6/site-packages/flask/app.py", line 1612, in full_dispatch_request
rv = self.dispatch_request()
File "/home/user/.virtualenvs/test_sum/lib/python3.6/site-packages/flask/app.py", line 1598, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
File "/home/user/.virtualenvs/test_sum/lib/python3.6/site-packages/flask_restful/__init__.py", line 480, in wrapper
resp = resource(*args, **kwargs)
File "/home/user/.virtualenvs/test_sum/lib/python3.6/site-packages/flask/views.py", line 84, in view
return self.dispatch_request(*args, **kwargs)
File "/home/user/.virtualenvs/test_sum/lib/python3.6/site-packages/flask_restful/__init__.py", line 595, in dispatch_request
resp = meth(*args, **kwargs)
File "app.py", line 16, in get
return {'data': directSum.hardCoded()}
TypeError: hardCoded() takes 0 positional arguments but 1 was given
Any ideas?
If range is meant to be the n number to return, in this case, 10000001, then you will want to do this instead:
In your directSum file:
def hardCoded(rng):
numbers_to_add = list(range(rng))
try:
# ... rest of code ...
In your main file:
class rangeNumbers(Resource):
def get(self, rng):
return {'data': directSum.hardCoded(rng)}
Where when you call rangeNumbers().get you do this:
rng_num = rangeNumbers()
rng_num.get(10000001)
Notice I changed your variable range to rng. It's in your best interest to not overshadow the builtin names even within a local scope. Otherwise calling range(range) is going to give you endless pain.

rest api throwing max tries exceeded error

I am trying to connect to a website via RESTful API. A token has to be generated to access the methods. And its working file since i can access data through all the methods but i am stuck at this one.
My code So far:
class FlipkartAPI:
def __init__(self, token, sandbox=False):
self.token = token
self.session = self.get_session()
self.sandbox = sandbox
def get_session(self):
session = requests.Session()
session.headers.update({
'Authorization': 'Bearer %s' % self.token,
'Content-type': 'application/json',
})
return session
def returns(self, source, modified_after=None, created_after = None):
if self.sandbox == False:
url = "http://api.flipkart.net/returns"
else:
url = "http://sandbox-api.flipkart.net/returns"
payload = {'source':source,
'modifiedAfter':modified_after,
'createdAfter': created_after}
return self.session.get(url, params = payload)
test.py:
class ListOrders:
def __init__(self):
self.app_id = 'app_id'
self.app_secret = 'app_secret'
auth = Authentication(self.app_id, self.app_secret, sandbox=False)
get_token = auth.get_access_token()
token_str = get_token.json()
token = token_str['access_token']
self.flipkart = FlipkartAPI(token, sandbox=False)
def ret(self):
r = self.flipkart.returns('customer_return', modified_after='2015-09-01', created_after='2015-09-01')
print r.url
print r.status_code
The problem is that i am getting max tries exceeded error every time i call ret method. And It doesn't even print url and the status_code for the request. Link to Documentation. What i am i doing wrong? I can access other method so there is no problem with the token generation.
Traceback:
Traceback (most recent call last):
File "test.py", line 131, in <module>
r = x.ret()
File "test.py", line 123, in ret
r = self.flipkart.returns('customer_return')
File "/home/manish/Desktop/Flipkart_Api_Main/api.py", line 77, in returns
return self.session.get(url)
File "/usr/lib/python2.7/dist-packages/requests/sessions.py", line 467, in get
return self.request('GET', url, **kwargs)
File "/usr/lib/python2.7/dist-packages/requests/sessions.py", line 455, in request
resp = self.send(prep, **send_kwargs)
File "/usr/lib/python2.7/dist-packages/requests/sessions.py", line 558, in send
r = adapter.send(request, **kwargs)
File "/usr/lib/python2.7/dist-packages/requests/adapters.py", line 378, in send
raise ConnectionError(e)
requests.exceptions.ConnectionError: HTTPConnectionPool(host='api.flipkart.net', port=80): Max retries exceeded with url: /returns (Caused by <class 'socket.error'>: [Errno 111] Connection refused)
EDIT: POSTMAN APP DATA
Images

Categories