am not quite advanced python user, I am stuck trying to populate the below but I think am handling list_choices wrong.
class LocationManager(TranslationManager):
def get_location_list(self, lang_code, site=None):
# this function is for building a list to be used in the posting process
# TODO: tune the query to hit database only once
list_choices = {}
for parents in self.language(lang_code).filter(country__site=site, parent=None):
list_child = ((child.id, child.name) for child in self.language(lang_code).filter(parent=parents))
list_choices.setdefault(parents).append(list_child)
return list_choices
Below the error am getting
>>>
>>> Location.objects.get_location_list(lang_code='en', site=current_site)
Traceback (most recent call last):
File "<console>", line 1, in <module>
File "/home/mo/Projects/mazban/mazban/apps/listing/geo/models.py", line 108, in get_location_list
list_choices.setdefault(parents).append(list_child)
AttributeError: 'NoneType' object has no attribute 'append'
That is because you use setdefault without a second argument. And it returns None in this case.
Try this fixed code:
# this is much more confinient and clearer
from collections import defaultdict
def get_location_list(self, lang_code, site=None):
# this function is for building a list to be used in the posting process
# TODO: tune the query to hit database only once
list_choices = defaultdict(list)
for parent in self.language(lang_code).filter(country__site=site, parent=None):
list_child = self.language(lang_code).filter(parent=parent).values_list('id', 'name')
list_choices[parent].extend(list_child)
return list_choices
Related
I have the following code running on AWS lambda, but getting the following error.
Error
[ERROR] AttributeError: 'str' object has no attribute 'source_instructions'
Traceback (most recent call last):
File "/var/task/gremlin_python/driver/driver_remote_connection.py", line 56, in submit
result_set = self._client.submit(bytecode, request_options=self._extract_request_options(bytecode))
File "/var/task/gremlin_python/driver/driver_remote_connection.py", line 81, in _extract_request_options
options_strategy = next((x for x in bytecode.source_instructionsEND RequestId: 4ee8073c-e941-43b3-8014-8717893b3188
Source code
from gremlin_python.driver.driver_remote_connection import DriverRemoteConnection
def test_neptune(host):
remoteConn = DriverRemoteConnection('wss://{}:8182/gremlin','g'.format(host))
query = "g.V().groupCount().by(label).unfold().project('label','count').by(keys).by(values)"
response = remoteConn.submit(query)
print("response-> {}" .format(response))
# iterate repsonse
# go thru label
for set_item in response:
for item in set_item:
print("item-> item: {}".format(item))
remoteConn.close()
test_neptune()
Your DriverRemoteConnection call is wrong. You have:
remoteConn = DriverRemoteConnection('wss://{}:8182/gremlin','g'.format(host))
So you are sending {} as the hostname, and passing 'g' as a second parameter, which is probably where the error comes from. I don't know what you intended the 'g' for, but you probably want:
remoteConn = DriverRemoteConnection('wss://{}:8182/gremlin'.format(host))
If you send the query as a text string you need to create the Client object differently or write the query as in-line Python. There are two examples at (1) and (2) that show each option. The error you are seeing is because the server is trying to find Gremlin bytecode in the packet sent but only found a string (which does not have a source_instructions method).
Using a DriverRemoteConnection you can use a Python line of code such as:
result = (g.V().groupCount().
by(label).
unfold().
project('label','count').
by(keys).
by(values).
next())
If you actually want/need to send the query as a string instead of bytecode, please see my answer to this question
https://github.com/krlawrence/graph/blob/master/sample-code/basic-client.py
https://github.com/krlawrence/graph/blob/master/sample-code/glv-client.py
I predefined few dicts in my test.
eg.
TIME_DISCOUNT_OFFER = dict(
time_discount=dict(
discount_days=5,
discount_percent=15
)
)
This dict goes to my model (JSONfield), then in my test, I am taking data from it. When I name test test_add_the_rest_of_name django detect predefined dicts, but when I name test eg. test_time_sth django gives me output
discount = TIME_DISCOUNT_OFFER.get("time_discount").get("discount_percent")
AttributeError: 'NoneType' object has no attribute 'get'
I have noticed, that in the second case (test_time_sth) my predefined dict is empty according to django, no matter if I am taking data directly from dict or from model instance. If I name test differently, test pass. Does anyone have any clue why is it happening?
Minimal example:
Model:
from django.contrib.postgres.fields import JSONField
class Offer(models.Model):
details = JSONField()
Test:
TIME_DISCOUNT_OFFER = dict(
time_discount=dict(
discount_days=10,
discount_percent=25
)
)
class OfferTest(TestCase):
#classmethod
def setUpTestData(cls):
cls.offer = Offer.objects.create(details=TIME_DISCOUNT_OFFER)
def test_special_offer_removed(self):
self.offer.details.pop('time_discount', None)
def test_timeframe_offer(self):
discount = TIME_DISCOUNT_OFFER.get("time_discount").get("discount_percent")
def test_add_offer(self):
discount = TIME_DISCOUNT_OFFER.get("time_discount").get("discount_percent")
Traceback:
..E
======================================================================
ERROR: test_timeframe_offer (offers.tests.test_offer.OfferTest)
----------------------------------------------------------------------
Traceback (most recent call last):
File "/home/admin1/Dokumenty/project/offers/tests/test_offer.py", line 142, in test_timeframe_offer
discount = TIME_DISCOUNT_OFFER.get("time_discount").get("discount_percent")
AttributeError: 'NoneType' object has no attribute 'get'
----------------------------------------------------------------------
Ran 3 tests in 0.006s
FAILED (errors=1)
You did not clean up properly after your tests. Everything that has been change in a test should be cleaned up at its end.
In your special case you are removing the key time_discount in your test test_special_offer_removed. Now depending on the order of the tests you might start your failing test after test_special_offer_removed and it will find the dictionary with the now missing key.
To prevent such problem make sure you are restoring the environment after every test: bring TIME_DISCOUNT_OFFER back to its original state at the end of test_special_offer_removed!
I have an API which is built in Tornado, and I'm trying to document it using tornado-swirl. For some reason, it's unable to pick the optional query param from the defined URL. How could this be solved? I'm not sure what I'm doing wrong, or what I'm missing here.
I've changed the pattern and even used the exact one used in the
docs and tut.
import tornado.web
import tornado_swirl as swirl
from .base import BaseHandler
#swirl.restapi('/item/(?P<id>[\w-]+)?')
class ItemHandler(BaseHandler):
def post(self, id):
"""Item
Creating a new item
Tags:
Item
"""
# store the item
pass
async def get(self, id):
"""Item
Get items or item
Tags:
Item
"""
# return all items if no id was provided
# or return item by id when provided
pass
I'm getting the following error:
Traceback (most recent call last):
File "/Users/.../venv/lib/python3.7/site-packages/tornado/web.py", line 1697, in _execute
result = method(*self.path_args, **self.path_kwargs)
File "/Users/.../venv/lib/python3.7/site-packages/tornado_swirl/views.py", line 101, in get
for path, spec, operations in apis},
File "/Users/.../venv/lib/python3.7/site-packages/tornado_swirl/views.py", line 100, in <dictcomp>
'paths': {path: self.__get_api_spec(spec, operations)
File "/Users/.../venv/lib/python3.7/site-packages/tornado_swirl/views.py", line 368, in find_api
['{%s}' % arg for arg in [param.name for param in vals]]
TypeError: not enough arguments for format string
Apparently, it's not getting the arguments. I think it has something to do with how I'm defining the URL there.
You just need to inform the path parameter in the docstring, something like that:
"""Item
Creating a new item
Path Params:
id (string) -- Your id
Tags:
Item
"""
I'm trying to update a user attribute in Active Directory using pyad. This is my code
from pyad import *
pyad.set_defaults(ldap_server="server.domain.local",
username="admin", password="password")
pyad.adobject.ADObject.update_attribute(self='testuser1', attribute='mail',
newvalue='my#email.com')
and this is the error i recieve.
Traceback (most recent call last):
File "c:\Users\Administrator\Desktop\scripts\AD-Edit-user.py", line 12, in
<module>
pyad.adobject.ADObject.update_attribute(self='testuser1', attribute='mail',
newvalue='my#email.com')
File "C:\Users\Administrator\AppData\Local\Programs\Python\Python36-
32\lib\site-packages\pyad-0.5.20-py3.6.egg\pyad\adobject.py", line 318, in
update_attribute
elif pyadutils.generate_list(newvalue) != self.get_attribute(attribute):
AttributeError: 'str' object has no attribute 'get_attribute'
This makes me assume that I need to change the attribute type from str to something else. I have verified that mail is the correct attribute name.
I know ldap connection is working because i can create a user using a similar script.
Your problem is how you use pyad.
Specifically in this line:
pyad.adobject.ADObject.update_attribute(self='testuser1', attribute='mail',
newvalue='my#email.com')
if we look at the source of pyad.adobject.ADObject, we can see the following:
def update_attribute(self, attribute, newvalue, no_flush=False):
"""Updates any mutable LDAP attribute for the object. If you are adding or removing
values from a multi-valued attribute, see append_to_attribute and remove_from_attribute."""
if newvalue in ((),[],None,''):
return self.clear_attribute(attribute)
elif pyadutils.generate_list(newvalue) != self.get_attribute(attribute):
self._set_attribute(attribute, 2, pyadutils.generate_list(newvalue))
if not no_flush:
self._flush()
self here is not a parameter of the function, it is a reference to the class instance. Your call includes self='testuser1' which is str.
Please lookup the documentation on how to use this function / functionality / module, here. You will notice that there is no "self"... other than looking into the source code I am not sure how you got to the conclusion you needed self.
I have no way of testing the following, but this is roughly how it should work:
# first you create an instance of the object, based on
# the distinguished name of the user object which you
# want to change
my_ad_object = pyad.adobject.ADObject.from_dn('the_distinguished_name')
# then you call the update_attribute() method on the instance
my_ad_object.update_attribute(attribute='mail', newvalue='my#email.com')
I keep getting a FieldMissingError on a field ('severa_id') of which I am sure that it exists. I've checked ver_33.py which shows that the Exception triggers if the field is not in self._meta.fields.
table._meta.fields shows the field being there:
print(table._meta.fields)
>>>
['proj_code', 'severa_id', 'rec_id', 'ext_key']
>>>
This is the code I'm trying:
table = dbf.Table(path_to_dbf)
table.open()
for row in dbf.Process(table):
for project in projects:
if str(row.proj_code)[0:4] == project["ProjectNumber"]:
row.write_record(severa_id=project["GUID"])
I've also tried these methods of setting the field:
row.severa_id = project["ProjectNumber"]
#row.write()
row.write_record()
Lastly, I've also tried setting each of the other fields (with a random string) which results in the same error.
EDIT: I am using the dbf module (https://pypi.python.org/pypi/dbf/0.96.005)
EDIT: The original traceback:
Traceback (most recent call last):
File "<string>", line 420, in run_nodebug
File "C:\Users\Alexander\Documents\update_projecten\update_dbf.py", line 58, in <module>
row.write()
File "C:\Users\Alexander\Envs\vfp\lib\site-packages\dbf\ver_33.py", line 2451, in __getattr__
raise FieldMissingError(name)
dbf.ver_33.FieldMissingError: 'write: no such field in table'
EDIT: The final version of the script that worked. Note not using Process and indicating in dbf.write the row and field to be written.
table = dbf.Table(path_to_dbf)
table.open()
for row in table:
for project in projects:
if str(row.proj_code)[0:4] == project["ProjectNumber"]:
dbf.write(row, severa_id=project["GUID"])
write_record no longer exists as a row method, so the error you are seeing is probably stating that write_record is not a field.
Instead, try:
dbf.write(severa_id=project['GUID'])