django-permission == 0.8.0, code in readthedocs not working? - python

I am following the code in the readthedocs (http://django-permission.readthedocs.org/en/latest/). Difficulty starts at Apply permission logic section of the docs. All works fine as I cut&paste
art1 = Article.objects.create(
title="Article 1",
body="foobar hogehoge",
author=user1
)
The following traceback is generated
Traceback (most recent call last):
File "<console>", line 4, in <module>
File "C:\Django\test_permissions\lib\site-packages\django\db\models\manager.py", line 157, in create
return self.get_queryset().create(**kwargs)
File "C:\Django\test_permissions\lib\site-packages\django\db\models\query.py", line 320, in create
obj = self.model(**kwargs)
File "C:\Django\test_permissions\lib\site-packages\django\db\models\base.py", line 417, in __init__
raise TypeError("'%s' is an invalid keyword argument for this function" % list(kwargs)[0])
TypeError: 'author' is an invalid keyword argument for this function
If it is changed to
art1 = Project.objects.create(
rest of code is okay
It works okay. So I guess an error. Maybe, I'm unsure.
Anyway, still cut&paste into shell until I get to
>>> assert user1.has_perm('permission.change_article') == False
Traceback (most recent call last):
File "<console>", line 1, in <module>
AssertionError
So I try
>>> assert user1.has_perm('permission.change_article') == True
Works fine. I have to say at this stage I have no idea as to what is going on.
So next line is
assert user1.has_perm('permission.change_article', art1) == True
And now the traceback
>>> assert user1.has_perm('permission.change_article', art1) == True
Traceback (most recent call last):
File "<console>", line 1, in <module>
File "c:\django\test_permissions\lib\site-packages\django\contrib\auth\models.py", line 336, in has_perm return _user_has_perm(self, perm, obj)
File "c:\django\test_permissions\lib\site-packages\django\contrib\auth\models.py", line 273, in _user_has_perm if backend.has_perm(user, perm, obj):
File "c:\django\test_permissions\lib\site-packages\permission\backends.py", line 71, in has_perm if handler.has_perm(user_obj, perm, obj=obj):
File "c:\django\test_permissions\lib\site-packages\permission\handlers.py", line 237, in has_perm if permission_logic.has_perm(user_obj, perm, obj):
File "c:\django\test_permissions\lib\site-packages\permission\logics\author.py", line 122, in has_perm author = field_lookup(obj, self.field_name)
File "c:\django\test_permissions\lib\site-packages\permission\utils\field_lookup.py", line 42, in field_lookup return field_lookup(field_lookup(obj, field_path[0]), field_path[1])
File "c:\django\test_permissions\lib\site-packages\permission\utils\field_lookup.py", line 41, in field_lookup return getattr(obj, field_path[0])
AttributeError: 'Project' object has no attribute 'project'
Have I done something wrong?
I have no idea what to do. I am as far out as Bishops Rock Lighthouse ;-)
I need to get permissions working for my project. Is this the app to go with?
BTW.
(test_permissions) c:\django\test_permissions\test_permissions>pip freeze
Django==1.6.5
Pillow==2.2.2
South==0.8.4
app-version==0.1.2
django-appconf==0.6
django-crispy-forms==1.4.0
django-permission==0.8.0
six==1.7.0
tolerance==0.1.1
Working in virtualenv on Win7
Tommy.

I'm the author of this library.
I'm really sorry but the example code was mis-leading. If you follow the Note section which said "From django-permission version 0.8.0, you can specify related object with field__name attribute like django queryset lookup. See the working example below:", the Article does not have author that's why django blame your code. It should be something like
prj1 = Project.objects.create(
title="Project 1",
body="hello",
author=user1,
)
art1 = Article.objects.create(
title="Article 1",
body="foobar hogehoge",
project=prj1,
)
Then the example should work.
I'll update the document as soon as possible.

Related

What does 'File "<string>"' stands for on python debugger and traceback?

Eventually, when I am in a debug session, the current file is named "<string>". What I would expect to see is the name of the module where the debugger is currently on.
The same happens on the traceback:
Traceback (most recent call last):
...
File "~/project_x/app/services/contacts.py", line 23, in find_account
account = self._account_repo.get_by_id(id)
File "<string>", line 2, in get_by_id
File "~/project_x/lib/python3.7/site-packages/pony/orm/core.py", li
ne 528, in new_func
result = func(*args, **kwargs)
It means that the code came from something that was not a file, but a string. My guess would be an exec() call, but maybe there are other ways of getting the same effect. The previous stack frame might give some clues.

twitterImgBot stops working after some hours

I'm trying to get this, https://github.com/joaquinlpereyra/twitterImgBot, to work
and it works and it seems ok.
But after some hours, it stops working and this error comes up:
*python3 twitterbot.py
Traceback (most recent call last):
File "/home/user/.local/lib/python3.7/site-packages/tweepy/binder.py", line 118, in build_path
value = quote(self.session.params[name])
KeyError: 'id'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "twitterbot.py", line 209, in <module>
main()
File "twitterbot.py", line 200, in main
orders()
File "twitterbot.py", line 118, in orders
timeline.delete_tweet_by_id(tweet.in_reply_to_status_id, api)
File "/home/user/Skrivebord/twitterboot/lo/bot/timeline.py", line 12, in delete_tweet_by_id
api.destroy_status(id_to_delete)
File "/home/user/.local/lib/python3.7/site-packages/tweepy/binder.py", line 245, in _call
method = APIMethod(args, kwargs)
File "/home/user/.local/lib/python3.7/site-packages/tweepy/binder.py", line 71, in __init__
self.build_path()
File "/home/user/.local/lib/python3.7/site-packages/tweepy/binder.py", line 120, in build_path
raise TweepError('No parameter value found for path variable: %s' % name)
tweepy.error.TweepError: No parameter value found for path variable: id*
It seems like the Python has some problem because if I make a new install on a another PC it works for some hours and then stops.
Strange.
This is likely because tweet is not in reply to a status, so has an in_reply_to_status_id attribute that's None, so API.destroy_status is called with an id of None.

Dynamically alter traceback/stack frame function name

From time to time, I write a generic function in Python that gets called multiple times with different arguments. Usually, this is driven by a definition somewhere else.
For example:
def issue_sql_query(name, select_stmt):
...
QUERIES = [
"get_user_rows", "SELECT name, rowid FROM table WHERE type == 'USER';"
...
]
results = []
for name, select_stmt in QUERIES:
results.append((name, issue_sql_query(name, select_stmt)))
If there's an exception in the generic function (i.e., issue_sql_query or somewhere deeper), I have relatively little info in the traceback to identify which definition caused the error.
What I'd like to do is dynamically rename or augment the function name/stack frame so that tracebacks would include some identifying info.
What would be nice is something like this:
File "test.py", line 21, in <module>
results.append((name, issue_sql_query(select_stmt)))
File "test.py", line 11, in issue_sql_query(name="get_user_rows")
raise RuntimeError("Some error")
RuntimeError: Some error
I could, of course, stick exception handling at the generic points and rebuild the exception using traceback to have more context, which is pretty straightforward and likely the right choice. It gets a little tricky when you have multiple levels of generic functions, but that's certainly possible to handle.
Any other ideas on how to accomplish this? Did I miss some easy way to change the stack frame name?
Edit:
Adding an example traceback showing a relatively not useful traceback:
Traceback (most recent call last):
File "C:\Python27\lib\runpy.py", line 162, in _run_module_as_main
"__main__", fname, loader, pkg_name)
File "C:\Python27\lib\runpy.py", line 72, in _run_code
exec code in run_globals
File "c:\tmp\report.py", line 767, in <module>
main()
File "c:\tmp\report.py", line 750, in main
charts.append(report.get_chart(title, definition))
File "c:\tmp\report.py", line 614, in get_chart
return self.get_bar_chart(title, definition)
File "c:\tmp\report.py", line 689, in get_bar_chart
definition, cursor, **kwargs))
File "c:\tmp\report.py", line 627, in create_key_table
for row in cursor.execute(full_select_stmt):
sqlite3.OperationalError: near "==": syntax error
You could create wrapper functions for each named query so that you can control the exception thrown:
>>> fns = {}
>>> def issue_sql_query(name, stmt):
... if name not in fns:
... def f(name, stmt):
... # run query here
... raise Exception(name)
...
... fns[name] = f
... return fns[name](name, stmt)
...
>>>
>>> issue_sql_query('b', 'SQL')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 9, in issue_sql_query
File "<stdin>", line 5, in f
Exception: b
>>> issue_sql_query('a', 'SQL')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 9, in issue_sql_query
File "<stdin>", line 5, in f
Exception: a
>>>

GetItem(),ItemCount(),SubElements() functions not working in pywinauto

I'm trying to automate tasks for teamcenter using pywinauto python module.But I was not able to work properly with TreeViews. When ever I'm trying to use GetItem(),SubElements(),Item() and many other function under _treeview_element giving error.Please look into below errors.
I'm using python 2.7 and i also have pywin32 module installed
for i in range(tr.ItemCount()):
print tr.GetItem(i)
Traceback (most recent call last):
File "<pyshell#61>", line 2, in <module>
print tr.GetItem(i) File "C:\Users\patibj\Desktop\pywinauto-
master\pywinauto\controls\common_controls.py", line 1010, in GetItem
if isinstance(path[0], int):
TypeError: 'int' object has no attribute '__getitem__'
This is when i'm trying to use GetChild()
a[0] is <pywinauto.controls.common_controls._treeview_element object at 0x02EC11B0> a[0].GetChild((1))
Traceback (most recent call last):
File "<pyshell#49>", line 1, in <module>
a[0].GetChild((1))
File "C:\Users\patibj\Desktop\pywinauto- master\pywinauto\controls\common_controls.py", line 840, in GetChild
return self.Children()[index]
File "C:\Users\patibj\Desktop\pywinauto-master\pywinauto\controls\common_controls.py", line 739, in Children
if self.Item().cChildren not in (0, 1):
File "C:\Users\patibj\Desktop\pywinauto-master\pywinauto\controls\common_controls.py", line 539, in Item
return self._readitem()[0]
File "C:\Users\patibj\Desktop\pywinauto-master\pywinauto\controls\common_controls.py", line 904, in _readitem
raise ctypes.WinError() WindowsError: [Error 0] The operation completed successfully.
Please help me out .Thanks in advance.
TreeViewWrapper.GetItem() method gets path argument which should be the string starting with back-slash \\ symbol. Example:
app.Dialog.TreeView.GetItem('\\1st_level_item_name\\2ndlevelitem').Click()
For access by index use a list of integers:
app.Dialog.TreeView.GetItem([1, 0])
GetChild() works with explorer.exe TreeView:
>>> tree.GetItem([1]).GetChild(2).Text()
u'Computer'

AttributeError: 'Response' object has no attribute '_dom'

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.

Categories