setattr() for an item in Redmine issues, is failing, with the following error.
Traceback (most recent call last):
File "E:\test\get_redmine_data.py", line 47, in <module>
print (item.assigned_to)
File "C:\Python27\lib\site-packages\redminelib\resources\standard.py", line 150, in __getattr__
return super(Issue, self).__getattr__(attr)
File "C:\Python27\lib\site-packages\redminelib\resources\base.py", line 164, in __getattr__
attr, encoded = self.encode(attr, decoded, self.manager)
File "C:\Python27\lib\site-packages\redminelib\resources\base.py", line 266, in encode
return attr, manager.new_manager(cls._resource_map[attr]).to_resource(value)
File "C:\Python27\lib\site-packages\redminelib\managers\base.py", line 29, in to_resource
return self.resource_class(self, resource)
File "C:\Python27\lib\site-packages\redminelib\resources\base.py", line 130, in __init__
self._decoded_attrs = dict(dict.fromkeys(relations_includes), **attributes)
TypeError: type object argument after ** must be a mapping, not str
I am trying to set some default assignee, for issues where the assignee is not set. The code fails at the line, where I print the attribute I just set. My code is given below:
redmine = Redmine('http://redmine_url', username='uname', password='pwd')
project = redmine.project.get('proj_name')
work_items = project.issues
for item in work_items:
assignee_not_set = getattr(item,'assigned_to',True)
if assignee_not_set == True:
print item.id
setattr(item,'assigned_to','Deepak')
print (item.assigned_to)
I also tried using the update() method,
redmine.project.update(item.id, assigned_to='Deepak')
That also fails with another error - redminelib.exceptions.ResourceNotFoundError: Requested resource doesn't exist.
I verifed that the issue id exists in Redmine.
You have several problems here:
The attribute name is assigned_to_id and not assigned_to
It accepts user id which is int and not a username which is str
No need to use setattr() here, just use item.assigned_to_id = 123
You need to call item.save() after setting assigned_to_id otherwise it won't be saved to Redmine
When you're trying to use update() method, you're using in on a Project resource and not on Issue resource, this is why you're getting ResourceNotFoundError
All this information is available in the docs: https://python-redmine.com/resources/issue.html
Related
I have the following code:
s = Search(using=Elasticsearch('http://user:passwd#ipaddress'), index="myindex")
q = Q("multi_match", query='some query', fields=['_all'])
s = s.query(q)
response = s.execute()
print('Total %d hits found.' % response.hits.total)
for hit in response:
print(hit.title)
And I get the error:
Traceback (most recent call last):
File "/usr/local/lib/python3.5/dist-packages/elasticsearch_dsl/utils.py", line 102, in __getattr__
return _wrap(self._d_[attr_name])
KeyError: 'title'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "FindImage.py", line 89, in <module>
main(args.image_file)
File "FindImage.py", line 82, in main
query_db([1], [2])
File "FindImage.py", line 77, in query_db
print(hit.title)
File "/usr/local/lib/python3.5/dist-packages/elasticsearch_dsl/utils.py", line 105, in __getattr__
'%r object has no attribute %r' % (self.__class__.__name__, attr_name))
AttributeError: 'Result' object has no attribute 'title'
However that is in direct contradiction to what the docs state:
Docs
What am I doing wrong? How can I correctly extract the hits and my values from the response?
EDIT
Also the response object ist supposed to have a method "toDict" but when I try to call it I again get an AttributeError.
For the "toDict" question, response.to_dict() works for me. Not sure if this behaviour is the same across lib versions.
Apparently the ".title" references an actual column in their example.
When I used hit.doc.FIRSTTAG, FIRSTTAG being a column in MY NoSQL-db it worked.
Still does not explain the missing method, but I am happy with it for now.
So to anyone having the same problem:
Use your own columns names when evaluating the response object e.g. in my example:
for hit in response:
print(hit.doc.FIRSTTAG)
I want to create an entity object and after its construction, before writing it into the datastore, I want to set parent and id.
According to App Engine docs, the constructor accepts these keyword arguments:
- id
- key
- parent
You cannot easily define a property named "key", "id", "parent", or
"namespace". If you pass, for example, key="foo" in a constructor or
populate() call, it sets the entity's key, not a property attribute
named "key".
For populate(), it says it would accept the same keyword arguments as the constructor. However, it seems I'm doing something wrong, because the only keyword argument that works is key. Using id and/or parent gives me errors.
class Foo(ndb.Model):
pass
foo = Foo()
foo.populate(key=ndb.Key('Bar', 1, 'Foo', 123))
foo.key == ndb.Key('Bar', 1, 'Foo', 123) # True
When instead I use the keyword parent...
f.populate(parent=ndb.Key('Bar', 1))
...I get this traceback:
Traceback (most recent call last):
File "<console>", line 1, in <module>
File "/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/google/appengine/ext/ndb/model.py", line 2960, in _populate
self._set_attributes(kwds)
File "/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/google/appengine/ext/ndb/model.py", line 2970, in _set_attributes
prop = getattr(cls, name) # Raises AttributeError for unknown properties.
AttributeError: type object 'Foo' has no attribute 'parent'
or sometimes this (not sure what makes the difference):
File "<console>", line 1, in <module>
File "/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/google/appengine/ext/ndb/model.py", line 2960, in _populate
self._set_attributes(kwds)
File "/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/google/appengine/ext/ndb/model.py", line 2972, in _set_attributes
raise TypeError('Cannot set non-property %s' % name)
TypeError: Cannot set non-property parent
If I use id...
f.populate(id=123)
I get again an attribute error:
Traceback (most recent call last):
File "<console>", line 1, in <module>
File "/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/google/appengine/ext/ndb/model.py", line 2960, in _populate
self._set_attributes(kwds)
File "/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/google/appengine/ext/ndb/model.py", line 2970, in _set_attributes
prop = getattr(cls, name) # Raises AttributeError for unknown properties.
AttributeError: type object 'Foo' has no attribute 'id'
Shouldn't all of my populate() examples above work with any of the keyword arguments?
I know, I could only use key to achieve the same as with parent and id together, but I would like to know what I'm missing here.
parent is a property of a Key when using ancestor paths. The constructor accepts it as a convenience but since it is not its own property, populate() will complain that it does not exist. Same goes for id. The constructor uses id to construct a Key using _get_kind() and the value of id.
An example is worth 1000 comments. See how id and parent are used to construct a key
>>> from google.appengine.ext import ndb
>>>>
>>> class Foo(ndb.Model):
... pass
...
>>> foo = Foo(id=123, parent=ndb.Key('Bar', 1))
>>> foo.key
Key('Bar', 1, 'Foo', 123)
>>> foo.id
Traceback (most recent call last):
File "<console>", line 1, in <module>
AttributeError: 'Foo' object has no attribute 'id'
>>> foo.parent
Traceback (most recent call last):
File "<console>", line 1, in <module>
AttributeError: 'Foo' object has no attribute 'parent'
The docs may not be clear enough on this issue, but you're only supposed to use populate to update properties of the model (actual data).
This is clear looking at the source code, for example this line of the model constructor:
Note: you cannot define a property named key; the .key attribute always refers to the entity's key. But you can define properties named id or parent. Values for the latter cannot be passed through the constructor, but can be assigned to entity attributes after the entity has been created.
Suggesting we could use id and parent as properties/attributes, thus populate calls will try to set them.
It gets even clearer once we get to the populate implementation, where the inline documentation has a provision for your exact question:
Each keyword argument will be used to set a corresponding property. Keywords must refer to valid property name. This is similar to passing keyword arguments to the Model constructor, except that no provisions for key, id or parent are made.
Maybe the docs should be updated with this information to avoid the confusion. I never ran into this issue myself, maybe because I've been following the recommendation of "only setting the key when instantiating a model", however I can't find a quote for this statement; I take it as a rule of thumb, and am under the impression that trying to assign it afterwards should raise exceptions everywhere.
And as if the previous references weren't enough, look at this line in the constructor:
self._key = _validate_key(key, entity=self)
You won't find that anywhere else, so this is the only instance of a key being assigned [properly] to a model (as you can imagine, populate only iterates and sets values).
I'm testing ebaysdk Python library that lets you connect to ebay. Now I'm trying examples from: https://github.com/timotheus/ebaysdk-python/
So far I got stuck at this example:
from ebaysdk.shopping import Connection as Shopping
shopping = Shopping(domain="svcs.sandbox.ebay.com", config_file="ebay.yaml")
response = shopping.execute('FindPopularItems',
{'QueryKeywords': 'Python'})
print response.disct()
When I run it. It gives me this error:
Traceback (most recent call last):
File "ebay-test.py", line 13, in <module>
{'QueryKeywords': 'Python'})
File "/usr/local/lib/python2.7/dist-packages/ebaysdk-2.1.0-py2.7.egg/ebaysdk/connection.py", line 123, in execute
self.error_check()
File "/usr/local/lib/python2.7/dist-packages/ebaysdk-2.1.0-py2.7.egg/ebaysdk/connection.py", line 193, in error_check
estr = self.error()
File "/usr/local/lib/python2.7/dist-packages/ebaysdk-2.1.0-py2.7.egg/ebaysdk/connection.py", line 305, in error
error_array.extend(self._get_resp_body_errors())
File "/usr/local/lib/python2.7/dist-packages/ebaysdk-2.1.0-py2.7.egg/ebaysdk/shopping/__init__.py", line 188, in _get_resp_body_errors
dom = self.response.dom()
File "/usr/local/lib/python2.7/dist-packages/ebaysdk-2.1.0-py2.7.egg/ebaysdk/response.py", line 229, in dom
return self._dom
File "/usr/local/lib/python2.7/dist-packages/ebaysdk-2.1.0-py2.7.egg/ebaysdk/response.py", line 216, in __getattr__
return getattr(self._obj, name)
AttributeError: 'Response' object has no attribute '_dom'
Am I missing something here or it could be some kind of bug in library?
Do you have a config file? I had a lot of problems getting started with this SDK. To get the yaml config file to work, I had to specify the directory that it was in. So in your example, it would be:
shopping = Shopping(domain="svcs.sandbox.ebay.com", config_file=os.path.join(os.path.dirname(os.path.realpath(__file__)), 'ebay.yaml'))
You should also be able to specify debug=true in your Shopping() declaration as in Shopping(debug=True).
Make sure if you have not, to specify your APP_ID and other necessary values in the config file.
You have the wrong domain, it should be open.api.sandbox.ebay.com. See this page on the ebaysdk github.
I've added a list property to an entity model with a large number of existing instances.
class MyModel(db.Model):
new_property = db.ListProperty(item_type=str, default=None)
Upon deployment to the live environment the app runs without issues for a short time and then starts throwing BadValueError error's as it tries to retrieve records from the datastore.
The code throwing the error is just a straight call to the datastore:
app_item = db.get(app_item_key)
I'm using 1.7.5. of the Python 2.7 runtime.
Any ideas on what I can do to prevent this, or at least trap it so that I can get data from the store?
Traceback (most recent call last):
File "/base/data/home/apps/app/4-15.365909351579418812/app.py", line 1739, in app_get
app_item = db.get(app_item_key)
File "/python27_runtime/python27_lib/versions/1/google/appengine/ext/db/__init__.py", line 1533, in get
return get_async(keys, **kwargs).get_result()
File "/python27_runtime/python27_lib/versions/1/google/appengine/api/apiproxy_stub_map.py", line 604, in get_result
return self.__get_result_hook(self)
File "/python27_runtime/python27_lib/versions/1/google/appengine/datastore/datastore_rpc.py", line 1459, in __get_hook
entities = rpc.user_data(entities)
File "/python27_runtime/python27_lib/versions/1/google/appengine/api/datastore.py", line 600, in local_extra_hook
return extra_hook(result)
File "/python27_runtime/python27_lib/versions/1/google/appengine/ext/db/__init__.py", line 1503, in extra_hook
model = cls1.from_entity(entity)
File "/python27_runtime/python27_lib/versions/1/google/appengine/ext/db/__init__.py", line 1438, in from_entity
return cls(None, _from_entity=entity, **entity_values)
File "/python27_runtime/python27_lib/versions/1/google/appengine/ext/db/__init__.py", line 970, in __init__
prop.__set__(self, value)
File "/python27_runtime/python27_lib/versions/1/google/appengine/ext/db/__init__.py", line 614, in __set__
value = self.validate(value)
File "/python27_runtime/python27_lib/versions/1/google/appengine/ext/db/__init__.py", line 3460, in validate
value = super(ListProperty, self).validate(value)
File "/python27_runtime/python27_lib/versions/1/google/appengine/ext/db/__init__.py", line 641, in validate
raise BadValueError('Property %s is required' % self.name)
BadValueError: Property new_property is required
For those that follow:
As per Aaron D's suggestion, changing the default value to an empty list resolved this issue, so:
new_property = db.ListProperty(item_type=str, default=None)
Should read:
new_property = db.ListProperty(item_type=str, default=[])
Looking at the source code of the Google App Engine in the __init__.py referenced in your traceback, you can see a comment in the ListProperty doc comments (line 3428) that says:
Note that the only permissible value for 'required' is True.
So, even though you are not providing it, it looks like line 3442 is setting it automatically:
self._require_parameter(kwds, 'required', True)
If you look further into the source code (line 3500), you can see the definition of empty() for a ListProperty:
def empty(self, value):
"""Is list property empty.
[] is not an empty value.
Returns:
True if value is None, else false.
"""
return value is None
I could think of two issues that might cause error but I haven't verified through testing.
1) If for some reason, you already have data in that field (perhaps you are reusing the new_property name?) and it was empty, then it seems likely to generate the error you have. I am not sure how to fix this problem, except to suggest that you use a unique name for your new_property instead. The post I referenced in my comment explains how to "fix" the data.
2) Since you already have records, your code is trying to populate those using your default value of None, which matches the empty() test and then throws the exception. In that case, if you just provide a default value of [] instead, it should work.
I am pretty sure you example code here is not what you are using. I would bet you have required=True in the new property. You are then retrieving an old record which doesn't have a value for the required property. Just dropping 'required=True` will make those errors go away. If you need to have that value required then you need to add the default value to the field before enforcing the constraint.
* removed some complete garbage about None not being a valid default value for ListProperty *
So I tried to replicate the situation based on the information you have supplied
and I have the answer. I can generate the problem by first creating a model that has a name new_property of type StringProperty with a default of None. put() the record with no value for new_property getting the default of None written, then change the model definition of new_property toListProperty`, and the fetch the record. We get the same stack trace. See shell log below.
s~lightning-catfish> class MyModel(db.Model):
... pass
...
s~lightning-catfish> x = MyModel()
s~lightning-catfish> x.put()
datastore_types.Key.from_path(u'MyModel', 1001L, _app=u's~lightning-catfish')
s~lightning-catfish> class MyModel(db.Model):
... new_property = db.ListProperty(item_type=str,default=None)
...
s~lightning-catfish> y = db.get(x.key())
s~lightning-catfish> y
<MyModel object at 0x9e09dcc>
s~lightning-catfish> y.new_property
[]
s~lightning-catfish> new_property = db.StringProperty(defaul
KeyboardInterrupt
s~lightning-catfish> class MyModel(db.Model):
... new_property = db.StringProperty(default=None)
...
s~lightning-catfish> z = MyModel()
s~lightning-catfish> z.put()
datastore_types.Key.from_path(u'MyModel', 2001L, _app=u's~lightning-catfish')
s~lightning-catfish> class MyModel(db.Model):
... new_property = db.ListProperty(item_type=str,default=None)
...
s~lightning-catfish> a1 = db.get(z.key())
Traceback (most recent call last):
File "<console>", line 1, in <module>
File "/home/timh/google_appengine/google/appengine/ext/db/__init__.py", line 1533, in get
return get_async(keys, **kwargs).get_result()
File "/home/timh/google_appengine/google/appengine/api/apiproxy_stub_map.py", line 604, in get_result
return self.__get_result_hook(self)
File "/home/timh/google_appengine/google/appengine/datastore/datastore_rpc.py", line 1459, in __get_hook
entities = rpc.user_data(entities)
File "/home/timh/google_appengine/google/appengine/api/datastore.py", line 600, in local_extra_hook
return extra_hook(result)
File "/home/timh/google_appengine/google/appengine/ext/db/__init__.py", line 1503, in extra_hook
model = cls1.from_entity(entity)
File "/home/timh/google_appengine/google/appengine/ext/db/__init__.py", line 1438, in from_entity
return cls(None, _from_entity=entity, **entity_values)
File "/home/timh/google_appengine/google/appengine/ext/db/__init__.py", line 970, in __init__
prop.__set__(self, value)
File "/home/timh/google_appengine/google/appengine/ext/db/__init__.py", line 614, in __set__
value = self.validate(value)
File "/home/timh/google_appengine/google/appengine/ext/db/__init__.py", line 3460, in validate
value = super(ListProperty, self).validate(value)
File "/home/timh/google_appengine/google/appengine/ext/db/__init__.py", line 641, in validate
raise BadValueError('Property %s is required' % self.name)
BadValueError: Property new_property is required
s~lightning-catfish>
To fix the data you will need to access it at a low level and change the data types stored in the record.
I have code for fetching and putting entities without using models if you want it.
* last thing you should try *
Try using the following code or something like it to fetch objects without using the model.
You get the underlying data back, with types etc.. in dicts. That will show you what is in the datastore.
from google.appengine.api import datastore
from google.appengine.api import datastore_errors
def get_entities(keys):
rpc = datastore.GetRpcFromKwargs({})
keys, multiple = datastore.NormalizeAndTypeCheckKeys(keys)
entities = None
try:
entities = datastore.Get(keys, rpc=rpc)
except datastore_errors.EntityNotFoundError:
assert not multiple
return entities
x = get_entities([some_key])
I get the following error when our program is run on Windows XP using ActivePerl 2.6 (although it runs fine on linux). Any ideas of what is going on? Is this a bug in the module or a problem with our code?
Error log:
File "C:\Python26\lib\site-packages\Scientific\IO\PDB.py", line 1163, in __ini
t__
self.parseFile(PDBFile(file_or_filename))
File "C:\Python26\lib\site-packages\Scientific\IO\PDB.py", line 1371, in parse
File
type, data = file.readLine()
File "C:\Python26\lib\site-packages\Scientific\IO\PDB.py", line 200, in readLi
ne
line = self.file.readline()
AttributeError: 'unicode' object has no attribute 'readline'
Exception AttributeError: "'unicode' object has no attribute 'close'" in <bound
method PDBFile.__del__ of <Scientific.IO.PDB.PDBFile instance at 0x00FD0440>> ig
nored
UPDATE: Following Joe's suggestion below, I get the following error instead:
Traceback (most recent call last):
File "NewParseV1_00.py", line 47, in <module>
PromptUser()
File "NewParseV1_00.py", line 45, in PromptUser
parseGroupFile(grpfilepath, outputPPYfilepath, sorcePDBfilepath)
File "NewParseV1_00.py", line 39, in parseGroupFile
return GeneratePPY(LL,GRPNAME,SRCPDB,OUTPPY)
File "NewParseV1_00.py", line 10, in __init__
self.PDBStruct = Scientific.IO.PDB.Structure(SRCPDB)
File "C:\Python26\lib\site-packages\Scientific\IO\PDB.py", line 1163, in __ini
t__
self.parseFile(PDBFile(file_or_filename))
File "C:\Python26\lib\site-packages\Scientific\IO\PDB.py", line 161, in __init
__
if isinstance(file_or_filename, basestr):
NameError: global name 'basestr' is not defined
Exception AttributeError: "PDBFile instance has no attribute 'open'" in <bound m
ethod PDBFile.__del__ of <Scientific.IO.PDB.PDBFile instance at 0x00FDB418>> ign
ored
I'm guessing, but it looks like a bug in Scientific.IO.PDB where they do something like:
if type(file_or_filename) == str:
file = open(file_or_filename)
else:
file = file_or_filename
rather than doing:
if isinstance(file_or_filename, basestr):
...
For whatever reason, you appear to be passing in a unicode filename on the windows side, and a raw string on the linux side.
Again, though, I'm just taking a guess. I'm assuming Scientific here is this module? http://dirac.cnrs-orleans.fr/plone/software/scientificpython/ (I'm not familiar with it...)
Edit: Yep!
Here's the relevant code from Scientific.IO.PDB:
class PDBFile:
"""
X{PDB} file with access at the record level
The low-level file access is handled by the module
L{Scientific.IO.TextFile}, therefore compressed files and URLs
(for reading) can be used as well.
"""
def __init__(self, file_or_filename, mode = 'r', subformat = None):
"""
#param file_or_filename: the name of the PDB file, or a file object
#type file_or_filename: C{str} or C{file}
#param mode: the file access mode, 'r' (read) or 'w' (write)
#type mode: C{str}
#param subformat: indicates a specific dialect of the PDB format.
Subformats are defined in
L{Scientific.IO.PDBExportFilters}; they are used
only when writing.
#type subformat: C{str} or C{NoneType}
"""
if isinstance(file_or_filename, str):
self.file = TextFile(file_or_filename, mode)
else:
self.file = file_or_filename
<snip>
It should be as simple as changing isinstance(file_or_filename, str) to isinstance(file_or_filename, basestr). You might want to file a bug report...
Changing the code in Scientific.IO.PDB as explained by Joe needs one final modification to work:
On line 161, change if isinstance(file_or_filename, str): to if isinstance(file_or_filename, basestring):
(Note that Joe wrote that the second argument should be basestr but that gives the error in the update in the original question.)