basic python syntax that i don't quite get - python

I keep getting this error, I'm not sure why though.
Traceback (most recent call last):
File "/home/cambria/Main.py", line 1, in <module>
from RiotAPI import RiotAPI
File "/home/cambria/RiotAPI.py", line 6
def __init__(self, api_key, region=Consts.REGIONS['north_america'])
^
SyntaxError: invalid syntax
I have not used Python for that long, I am just using it because it facilitates what I'm trying to do well, but I have used various other languages and as far as I can tell you would want to close these ()'s in this statement def __init__(self, api_key, region=Consts.REGIONS['north_america']) however I keep getting a SyntaxError: invalid syntax?
the rest of that definition is as follows, if it helps.
class RiotAPI(object):
def __init__(self, api_key, region=Consts.REGIONS['north_america'])
self.api_key = api_key
self.region = region
EDIT 1: if i add a : at the end of def __init__(self, api_key, region=Consts.REGIONS['north_america']): like so, why? and after doing this i get a new syntax error that i will address after some wisedom
EDIT 2: new syntax error after fixing the first is,
Traceback (most recent call last):
File "/home/cambria/Main.py", line 1, in <module>
from RiotAPI import RiotAPI
File "/home/cambria/RiotAPI.py", line 11
args = ('api_key': self.api_key)
^
SyntaxError: invalid syntax
which is
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
EDIT 3: This should be the last of it.. no more syntax, just a
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?

The problem is just that you're missing a : at the end of the line.
def __init__(self, api_key, region=Consts.REGIONS['north_america']):
self.api_key = api_key
self.region = region

You forgot a ::
class RiotAPI(object):
def __init__(self, api_key, region=Consts.REGIONS['north_america']): # <HERE
self.api_key = api_key
self.region = region

Related

Error with python ecdsa public key to_string()

I'm trying to make somebody Alice sign a message with a [privateKey], then letting somebody Bob verify that message with a [publicKey] (Bob doesn't know Alice`s private key).
class digitalSign:
def __init__(self):
self.privateKey = SigningKey.generate(curve = NIST384p)
self.publicKey = self.privateKey.verifying_key
def sign(self, privateKey, msg):
signature = self.privateKey.sign(msg.encode())
return signature
test = digitalSign()
rawPublicKey = test.publicKey.to_string() #suppose this is from database
publicKey = SigningKey.from_string(rawPublicKey, curve = NIST384p)
Getting this error:
Traceback (most recent call last):
File "bc.py", line 28, in <module>
publicKey = SigningKey.from_string(rawPublicKey, curve = NIST384p)
File "C:\...\site-packages\ecdsa-0.16.1-py3.7.egg\ecdsa\keys.py", line 885, in from_string
ecdsa.keys.MalformedPointError: Invalid length of private key, received 96, expected 48

Missing data for required field in Marshmallow 3.10.0

I am new to Marshmallow (3.10.0) and I am lost and need help trying to figure out what causes the following error:
AssertionError: ["Input Error - exten: ['Missing data for required field.']"]
The traceback of the error is the following:
Traceback (most recent call last):
File "/root/wazo_virtualenv_python37/lib/python3.7/site-packages/nose/case.py", line 198, in runTest
self.test(*self.arg)
File "/root/wazo-confd/integration_tests/suite/helpers/wrappers.py", line 81, in decorated
result = func(*new_args, **kwargs)
File "/root/wazo-confd/integration_tests/suite/helpers/wrappers.py", line 81, in decorated
result = func(*new_args, **kwargs)
File "/root/wazo-confd/integration_tests/suite/base/test_call_filter_surrogate_user.py", line 216, in test_get_surrogates_callfilter_exten_when_disabled
confd.extensions.features(feature['id']).put({'enabled': False}).assert_updated()
File "/root/wazo-confd/integration_tests/suite/helpers/client.py", line 272, in assert_updated
self.assert_status(204)
File "/root/wazo-confd/integration_tests/suite/helpers/client.py", line 242, in assert_status
assert_that(self.response.status_code, is_in(statuses), self.response.text)
So it seems that the test function test_get_surrogates_callfilter_exten_when_disabled is failing:
def test_get_surrogates_callfilter_exten_when_disabled(call_filter, user):
response = confd.extensions.features.get(search="bsfilter")
feature = response.items[0]
---> (line 216 in traceback): confd.extensions.features(feature['id']).put({'enabled': False}).assert_updated()
with a.call_filter_surrogate_user(call_filter, user):
response = confd.callfilters(call_filter['id']).get()
assert_that(
response.item,
has_entries(
surrogates=has_entries(
users=contains(has_entries(exten=None, uuid=user['uuid']))
)
),
)
confd.extensions.features(feature['id']).put(
{'enabled': feature['enabled']}
).assert_updated()
the feature_extension schema is defined as the following:
class ExtensionFeatureSchema(BaseSchema):
id = fields.Integer(dump_only=True)
exten = fields.String(validate=Regexp(EXTEN_REGEX), required=True)
context = fields.String(dump_only=True)
feature = fields.String(attribute='typeval', dump_only=True)
enabled = fields.Boolean()
links = ListLink(Link('extensions_features'))
and the put function:
def put(self):
form = self.schema().load(request.get_json())
variables = [self.model(**option) for option in form]
self.service.edit(self.section_name, variables)
return '', 204
I have tried many solutions that I found online; but they did not fix the issue for me:
1 + pass partial=True to the load function:
form = self.schema().load(request.get_json(), partial=True)
2 + remove required=True from the field definition; this made the above error go away but failed many other tests that I have.
I am currently out of ideas, so if anyone has an idea how to fix the issue.

Scrapinghub Getting Error caught on signal handler: <bound method ? on Yield

I have a scrapy script that works locally, but when I deploy it to Scrapinghub, it's giving all errors. Upon debugging, the error is coming from Yielding the item.
This is the error I get.
ERROR [scrapy.utils.signal] Error caught on signal handler: <bound method ?.item_scraped of <sh_scrapy.extension.HubstorageExtension object at 0x7fd39e6141d0>> Less
Traceback (most recent call last):
File "/usr/local/lib/python2.7/site-packages/twisted/internet/defer.py", line 150, in maybeDeferred
result = f(*args, **kw)
File "/usr/local/lib/python2.7/site-packages/pydispatch/robustapply.py", line 55, in robustApply
return receiver(*arguments, **named)
File "/usr/local/lib/python2.7/site-packages/sh_scrapy/extension.py", line 45, in item_scraped
item = self.exporter.export_item(item)
File "/usr/local/lib/python2.7/site-packages/scrapy/exporters.py", line 304, in export_item
result = dict(self._get_serialized_fields(item))
File "/usr/local/lib/python2.7/site-packages/scrapy/exporters.py", line 75, in _get_serialized_fields
value = self.serialize_field(field, field_name, item[field_name])
File "/usr/local/lib/python2.7/site-packages/scrapy/exporters.py", line 284, in serialize_field
return serializer(value)
File "/usr/local/lib/python2.7/site-packages/scrapy/exporters.py", line 290, in _serialize_value
return dict(self._serialize_dict(value))
File "/usr/local/lib/python2.7/site-packages/scrapy/exporters.py", line 300, in _serialize_dict
key = to_bytes(key) if self.binary else key
File "/usr/local/lib/python2.7/site-packages/scrapy/utils/python.py", line 117, in to_bytes
'object, got %s' % type(text).__name__)
TypeError: to_bytes must receive a unicode, str or bytes object, got int
It doesn't specify the field with issues, but by process of elimination, I came to realize it's this part of the code:
try:
item["media"] = {}
media_index = 0
media_content = response.xpath("//audio/source/#src").extract_first()
if media_content is not None:
item["media"][media_index] = {}
preview = item["media"][media_index]
preview["Media URL"] = media_content
preview["Media Type"] = "Audio"
media_index += 1
except IndexError:
print "Index error for media " + item["asset_url"]
I cleared some parts up to make it easier to tackle, but basically this part is the issue. Something it doesn't like about the item media.
I'm beginner in both Python and Scrapy. So sorry if this turns out to be silly basic Python mistake. Any idea?
EDIT: So after getting the answer from ThunderMind, the solution was to simply do str(media_index) for key
Yeah, right here:
item["media"][media_index] = {}
media_index is a mutable. and Keys can't be mutable.
Read Python dict, to know what should be used as keys.

firebase TypeError: __init__() missing 2 required positional arguments: 'session' and 'build_headers'

I am just starting to learn python and firebase. I want to set a listener to a node in firebase. the node is in
https://database.firebaseio.com/NSN
so I was looking through this tutorial
https://github.com/firebase/EventSource-Examples/blob/master/python/chat.py
based on the above tutorial I came up with this code
URL ="https://database.firebaseio.com/Missing NSN.json"
class ClosableSSEClient(SSEClient):
"""
Hack in some closing functionality on top of the SSEClient
"""
def __init__(self, *args, **kwargs):
self.should_connect = True
super(ClosableSSEClient, self).__init__(*args, **kwargs)
def _connect(self):
if self.should_connect:
super(ClosableSSEClient, self)._connect()
else:
raise StopIteration()
def close(self):
self.should_connect = False
self.retry = 0
# HACK: dig through the sseclient library to the requests library down to the underlying socket.
# then close that to raise an exception to get out of streaming. I should probably file an issue w/ the
# requests library to make this easier
self.resp.raw._fp.fp._sock.shutdown(socket.SHUT_RDWR)
self.resp.raw._fp.fp._sock.close()
self.sse = ClosableSSEClient(URL)
for msg in self.sse:
msg_data = json.loads(msg.data)
if msg_data is None: # keep-alives
continue
path = msg_data['path']
data = msg_data['data']
if path == '/':
# initial update
if data:
keys = data.keys()
keys.sort()
print(keys)
for k in keys:
self.message_queue.put(data[k])
else:
self.message_queue.put(data)
when i run this script i get this error
>> Traceback (most recent call last):
File "NSNListener.py", line 96, in <module>
self.sse = ClosableSSEClient(URL)
File "NSNListener.py", line 78, in __init__
super(ClosableSSEClient, self).__init__(*args, **kwargs)
TypeError: __init__() missing 2 required positional arguments: 'session' and 'build_headers'
TypeError: __init__() missing 2 required positional arguments: 'session' and 'build_headers'
how can I fix this ?

Python Tuple Problems

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 = {}
...

Categories