Diazo, parameters and restrictedTraverse - plone

if in my diazo controlpanel > 'Parameter expressions' I put
have_left_portlets = python:context and context.restrictedTraverse('##plone').have_portlets('plone.leftcolumn',context)
I obtain an error only when I'm on the portal homepage:
2012-06-26 16:51:42 ERROR plone.transformchain Unexpected error whilst trying to apply transform chain
Traceback (most recent call last):
File "/Users/vito/.buildout/eggs/plone.transformchain-1.0.2-py2.6.egg/plone/transformchain/transformer.py", line 48, in __call__
newResult = handler.transformIterable(result, encoding)
File "/Users/vito/.buildout/eggs/plone.app.theming-1.0-py2.6.egg/plone/app/theming/transform.py", line 257, in transformIterable
params[name] = quote_param(expression(expressionContext))
File "/Users/vito/.buildout/eggs/Zope2-2.13.13-py2.6.egg/Products/PageTemplates/ZRPythonExpr.py", line 48, in __call__
return eval(self._code, vars, {})
File "PythonExpr", line 1, in <expression>
File "/Users/vito/.buildout/eggs/AccessControl-2.13.7-py2.6-macosx-10.6-x86_64.egg/AccessControl/ImplPython.py", line 675, in guarded_getattr
v = getattr(inst, name)
AttributeError: 'FilesystemResourceDirectory' object has no attribute 'restrictedTraverse'
How I can solve this?

I suspect this is a bug in plone.app.theming: the context isn't set correctly. Strange, though.

Just confirming that the issue exits:
I get about the same traceback, the site itself looks fine, but for every click inside the site I get a the following traceback in my instance fg:
2012-08-10 15:05:05 ERROR plone.transformchain Unexpected error whilst trying to apply transform chain
Traceback (most recent call last):
File "/opt/etc/buildout/eggs/plone.transformchain-1.0.2-py2.6.egg/plone/transformchain/transformer.py", line 48, in __call__
newResult = handler.transformIterable(result, encoding)
File "/opt/etc/buildout/eggs/plone.app.theming-1.0-py2.6.egg/plone/app/theming/transform.py", line 257, in transformIterable
params[name] = quote_param(expression(expressionContext))
File "/opt/etc/buildout/eggs/Zope2-2.13.10-py2.6.egg/Products/PageTemplates/ZRPythonExpr.py", line 48, in __call__
return eval(self._code, vars, {})
File "PythonExpr", line 1, in <expression>
AttributeError: 'FilesystemResourceDirectory' object has no attribute 'Language'
This is because I have the following line in my manifest.cfg (which is about the same as the parameter line in the plone_control_panel:
lang = python: context.Language()
In a way in my case this is sort of logical, since not all content objects have an index called Language().
But the 'context' in this case is apparently refering to the 'FileSystemResourceDirectory' and not to the piece of content you are on?
I'll try with pdb if I can find some more info...

Related

BS4: AttributeError: 'NoneType' object stops the parser from working

I'm currently working on a parser to make a small preview of a page from a URL given by the user in PHP.
I'd like to retrieve only the title of the page and a little chunk of information (a bit of text)
The project: for a list of meta-data of popular wordpress-plugins and gathering the first 50 URLs - that are 50 plugins which are of interest! The challenge is: i want to fetch meta-data of all the existing plugins. What i subsequently want to filter out after the fetch is - those plugins that have the newest timestamp - that are updated (most) recently. It is all aobut acutality...
https://wordpress.org/plugins/wp-job-manager
https://wordpress.org/plugins/ninja-forms
import requests
from bs4 import BeautifulSoup
from concurrent.futures.thread import ThreadPoolExecutor
url = "https://wordpress.org/plugins/browse/popular/{}"
def main(url, num):
with requests.Session() as req:
print(f"Collecting Page# {num}")
r = req.get(url.format(num))
soup = BeautifulSoup(r.content, 'html.parser')
link = [item.get("href")
for item in soup.findAll("a", rel="bookmark")]
return set(link)
with ThreadPoolExecutor(max_workers=20) as executor:
futures = [executor.submit(main, url, num)
for num in [""]+[f"page/{x}/" for x in range(2, 50)]]
allin = []
for future in futures:
allin.extend(future.result())
def parser(url):
with requests.Session() as req:
print(f"Extracting {url}")
r = req.get(url)
soup = BeautifulSoup(r.content, 'html.parser')
target = [item.get_text(strip=True, separator=" ") for item in soup.find(
"h3", class_="screen-reader-text").find_next("ul").findAll("li")[:8]]
head = [soup.find("h1", class_="plugin-title").text]
new = [x for x in target if x.startswith(
("V", "Las", "Ac", "W", "T", "P"))]
return head + new
with ThreadPoolExecutor(max_workers=50) as executor1:
futures1 = [executor1.submit(parser, url) for url in allin]
for future in futures1:
print(future.result())
see the results:
Extracting https://wordpress.org/plugins/tuxedo-big-file-uploads/Extracting https://wordpress.org/plugins/cherry-sidebars/
Extracting https://wordpress.org/plugins/meks-smart-author-widget/
Extracting https://wordpress.org/plugins/wp-limit-login-attempts/
Extracting https://wordpress.org/plugins/automatic-translator-addon-for-loco-translate/
Extracting https://wordpress.org/plugins/event-organiser/
Traceback (most recent call last):
File "/home/martin/unbenannt0.py", line 45, in <module>
print(future.result())
File "/home/martin/anaconda3/lib/python3.7/concurrent/futures/_base.py", line 428, in result
return self.__get_result()
File "/home/martin/anaconda3/lib/python3.7/concurrent/futures/_base.py", line 384, in __get_result
raise self._exception
File "/home/martin/anaconda3/lib/python3.7/concurrent/futures/thread.py", line 57, in run
result = self.fn(*self.args, **self.kwargs)
File "/home/martin/unbenannt0.py", line 34, in parser
"h3", class_="screen-reader-text").find_next("ul").findAll("li")[:8]]
AttributeError: 'NoneType' object has no attribute 'find_next'
well i have a severe error - the
AttributeError: 'NoneType' object has no attribute 'find_next'
It looks like soup.find("h3", class_="screen-reader-text") has not found anything.
Well we could either break this line up and only call find_next if there was a result or use a try/except that captures the AttributeError.
at the moment i do not know how to fix this whole thing - only that we can surround the offending code with:
try:
code that causes error
except AttributeError:
print(f"Attribution error on {some data here}, {whatever else would be of value}, {...}")
... whatever action is thinkable to take here.
btw.- besides this error i want to add a option that gives the results back: see complete and unaltered error traceback. It contains valuable process call stack information.
Extracting https://wordpress.org/plugins/automatic-translator-addon-for-loco-translate/
Extracting https://wordpress.org/plugins/wpforo/Extracting https://wordpress.org/plugins/accesspress-social-share/
Extracting https://wordpress.org/plugins/mailoptin/
Extracting https://wordpress.org/plugins/tuxedo-big-file-uploads/
Extracting https://wordpress.org/plugins/post-snippets/
Extracting https://wordpress.org/plugins/woocommerce-payfast-gateway/Extracting https://wordpress.org/plugins/woocommerce-grid-list-toggle/
Extracting https://wordpress.org/plugins/goodbye-captcha/
Extracting https://wordpress.org/plugins/gravity-forms-google-analytics-event-tracking/
Traceback (most recent call last):
File "/home/martin/dev/wordpress_plugin.py", line 44, in <module>
print(future.result())
File "/home/martin/anaconda3/lib/python3.7/concurrent/futures/_base.py", line 428, in result
return self.__get_result()
File "/home/martin/anaconda3/lib/python3.7/concurrent/futures/_base.py", line 384, in __get_result
raise self._exception
File "/home/martin/anaconda3/lib/python3.7/concurrent/futures/thread.py", line 57, in run
result = self.fn(*self.args, **self.kwargs)
File "/home/martin/dev/wordpress_plugin.py", line 33, in parser
"h3", class_="screen-reader-text").find_next("ul").findAll("li")[:8]]
AttributeError: 'NoneType' object has no attribute 'find_next'
hope that this was not too long and complex - thank you for the help!

AuthorizationFailed - "The client 'xxx' with object id 'xxx does not have authorization to perform action

I've tried to get Workspace from config which I do have access to, but it fails with the following error:
import azureml.core
print("SDK version:", azureml.core.VERSION)
from azureml.core.workspace import Workspace
ws = Workspace.from_config()
print(ws.name, ws.resource_group, ws.location, ws.subscription_id, sep='\n')
SDK version: 0.1.80 Found the config file in:
C:\Users\gubert\Repos\Gimmonix\HotelMappingAI\aml_config\config.json
get_workspace error using subscription_id=xxxxxxxxxxxxxxxxxxxxxxx,
resource_group_name=xxxxxxxxxxxx, workspace_name=gmx-ml-mapping
Traceback (most recent call last): File
"C:\Users\gubert.azureml\envs\myenv\lib\site-packages\azureml_project_commands.py",
line 320, in get_workspace workspace_name) File
"C:\Users\gubert.azureml\envs\myenv\lib\site-packages\azureml_base_sdk_common\workspace\operations\workspaces_operations.py",
line 78, in get raise
models.ErrorResponseWrapperException(self._deserialize, response)
azureml._base_sdk_common.workspace.models.error_response_wrapper.ErrorResponseWrapperException:
Operation returned an invalid status code 'Forbidden'
During handling of the above exception, another exception occurred:
Traceback (most recent call last): File
"c:\Users\gubert.vscode\extensions\ms-python.python-2018.10.1\pythonFiles\experimental\ptvsd_launcher.py",
line 38, in main(sys.argv) File
"c:\Users\gubert.vscode\extensions\ms-python.python-2018.10.1\pythonFiles\experimental\ptvsd\ptvsd_main_.py",
line 265, in main wait=args.wait) File
"c:\Users\gubert.vscode\extensions\ms-python.python-2018.10.1\pythonFiles\experimental\ptvsd\ptvsd_main_.py",
line 256, in handle_args run_main(addr, name, kind, *extra, **kwargs)
File
"c:\Users\gubert.vscode\extensions\ms-python.python-2018.10.1\pythonFiles\experimental\ptvsd\ptvsd_local.py",
line 52, in run_main runner(addr, name, kind == 'module', *extra,
**kwargs) File "c:\Users\gubert.vscode\extensions\ms-python.python-2018.10.1\pythonFiles\experimental\ptvsd\ptvsd\runner.py",
line 32, in run set_trace=False) File
"c:\Users\gubert.vscode\extensions\ms-python.python-2018.10.1\pythonFiles\experimental\ptvsd\ptvsd_vendored\pydevd\pydevd.py",
line 1283, in run return self._exec(is_module, entry_point_fn,
module_name, file, globals, locals) File
"c:\Users\gubert.vscode\extensions\ms-python.python-2018.10.1\pythonFiles\experimental\ptvsd\ptvsd_vendored\pydevd\pydevd.py",
line 1290, in _exec pydev_imports.execfile(file, globals, locals) #
execute the script File
"c:\Users\gubert.vscode\extensions\ms-python.python-2018.10.1\pythonFiles\experimental\ptvsd\ptvsd_vendored\pydevd_pydev_imps_pydev_execfile.py",
line 25, in execfile exec(compile(contents+"\n", file, 'exec'), glob,
loc) File "c:\Users\gubert\Repos\Gimmonix\HotelMappingAI\test.py",
line 8, in ws = Workspace.from_config() File
"C:\Users\gubert.azureml\envs\myenv\lib\site-packages\azureml\core\workspace.py",
line 153, in from_config auth=auth) File
"C:\Users\gubert.azureml\envs\myenv\lib\site-packages\azureml\core\workspace.py",
line 86, in init auto_rest_workspace = _commands.get_workspace(auth,
subscription_id, resource_group, workspace_name) File
"C:\Users\gubert.azureml\envs\myenv\lib\site-packages\azureml_project_commands.py",
line 326, in get_workspace resource_error_handling(response_exception,
WORKSPACE) File
"C:\Users\gubert.azureml\envs\myenv\lib\site-packages\azureml_base_sdk_common\common.py",
line 270, in resource_error_handling raise
ProjectSystemException(response_message)
azureml.exceptions._azureml_exception.ProjectSystemException: {
"error_details": { "error": { "code": "AuthorizationFailed",
"message": "The client 'xxxxxxxxxx#microsoft.com' with object id
'xxxxxxxxxxxxx' does not have authorization to perform action
'Microsoft.MachineLearningServices/workspaces/read' over scope
'/subscriptions/xxxxxxxxxxxxxx/resourceGroups/CarsolizeCloud - Test
Global/providers/Microsoft.MachineLearningServices/workspaces/gmx-ml-mapping'."
} }, "status_code": 403, "url":
"https://management.azure.com/subscriptions/xxxxxxxxxxxxx/resourceGroups/CarsolizeCloud%20-%20Test%20Global/providers/Microsoft.MachineLearningServices/workspaces/gmx-ml-mapping?api-version=2018-03-01-preview"
}
Try using the newest SDK version 1.0.10, this is a fairly old preview version you're using. If you still have a problem, let me know as I work on this SDK.

mocking a function called multiple times using pymox

I have a function in the code that is being called twice.
get_user_settings
once it is getting called in the function I am testing and second time some different module has a function that calls it again.
I have mocked it using pymox like this:
mox = mox.Mox()
mox.StubOutWithMock(utils, "get_user_settings")
utils.get_user_settings("config").AndReturn(mocked_data)
the mocking works for the first call from my test code but when it gets called again in the utils module I get the below error
======================================================================
FAIL: test_uncommited_changes (test_scmCommandBase.TestSCMCommandBase)
----------------------------------------------------------------------
Traceback (most recent call last):
File "/local/ciasto/git/myproject/tests/test_scmCommandBase.py", line
79, in test_uncommited_changes
branch.rebase()
File "/local/ciasto/git/myproject/bin/local/cmds/update/core.py",
line 81, in rebase
_utils.save_branch_signature_to_config(user_branch)
File "/local/ciasto/git/myproject/bin/local/config/utils.py", line
146, in save_branch_signature_to_config
content = get_user_settings(project_config)
File "/sw/thirdparty/pymox/0.7.6-bfx1/lib/mox.py", line 886, in __call__
return mock_method(*params, **named_params)
File "/sw/thirdparty/pymox/0.7.6-bfx1/lib/mox.py", line 1193, in __call__
expected_method = self._VerifyMethodCall()
File "/sw/thirdparty/pymox/0.7.6-bfx1/lib/mox.py", line 1246, in
_VerifyMethodCall
expected = self._PopNextMethod()
File "/sw/thirdparty/pymox/0.7.6-bfx1/lib/mox.py", line 1232, in
_PopNextMethod
raise exception
UnexpectedMethodCallError: Unexpected method call
function.__call__('/tmp/tmpbNI_L4/.myproject') -> None

"Adapter does not support geometry" exception when declaring geometry field

In my application, an "Adapter does not support geometry" exception is being thrown when attempting to create a field of type, "geometry()". For my test application, I'm using an sqlite DB (production will use postgres):
db = DAL('sqlite://storage.sqlite', pool_size = 1, fake_migrate_all= False)
The DB table in question is declared within a class, inside of a module, and contains a several fields, some of which contain location data:
from gluon.dal import Field, geoPoint, geoLine, geoPolygon
class Info(Base_Model):
def __init__(...):
try:
db.define_table('t_info',
...
Field('f_geolocation', type='geometry()',
label = current.T('Geolocation')),
Field('f_city', type='string',
label = current.T('City')),
...
except Exception as e:
...
Edit:
As per Anthony's suggestion, I've modified the DAL constructor call to the following:
db = DAL('spatialite://storage.sqlite', pool_size = 1)
It produces the following error message:
Traceback (most recent call last):
File "C:\...\web2py\gluon\restricted.py", line 227, in restricted
exec ccode in environment
File "C:/My_Stuff/Programs/web2py/applications/Proj/models/db.py", line 38, in <module>
db = DAL('spatialite://storage.sqlite', pool_size = 1)
File "C:\...\web2py\gluon\packages\dal\pydal\base.py", line 171, in __call__
obj = super(MetaDAL, cls).__call__(*args, **kwargs)
File "C:\...\web2py\gluon\packages\dal\pydal\base.py", line 457, in __init__
raise RuntimeError("Failure to connect, tried %d times:\n%s" % (attempts, tb))
RuntimeError: Failure to connect, tried 5 times:
Traceback (most recent call last):
File "C:\...\web2py\gluon\packages\dal\pydal\base.py", line 435, in __init__
self._adapter = ADAPTERS[self._dbname](**kwargs)
File "C:\...\web2py\gluon\packages\dal\pydal\adapters\base.py", line 53, in __call__
obj = super(AdapterMeta, cls).__call__(*args, **kwargs)
File "C:\...\web2py\gluon\packages\dal\pydal\adapters\sqlite.py", line 169, in __init__
if do_connect: self.reconnect()
File "C:\...\web2py\gluon\packages\dal\pydal\connection.py", line 129, in reconnect
self.after_connection_hook()
File "C:\...\web2py\gluon\packages\dal\pydal\connection.py", line 81, in after_connection_hook
self.after_connection()
File "C:\...\web2py\gluon\packages\dal\pydal\adapters\sqlite.py", line 177, in after_connection
self.execute(r'SELECT load_extension("%s");' % libspatialite)
File "C:\...\web2py\gluon\packages\dal\pydal\adapters\base.py", line 1326, in execute
return self.log_execute(*a, **b)
File "C:\...\web2py\gluon\packages\dal\pydal\adapters\base.py", line 1320, in log_execute
ret = self.cursor.execute(command, *a[1:], **b)
OperationalError: The specified module could not be found.
If you want to use geometry fields with SQLite, you must use the spatialite adapter, which makes use of the SpatialLite extension for SQLite:
db = DAL('spatialite://storage.sqlite', pool_size = 1)
Note, you must have spatialite installed for this to work.

zope.annotation example in documentation fails. Help needed to correct it

I am trying to understand Annotations from this document:
http://docs.zope.org/zope.annotation/index.html
However the example fails when run.
I get:
Traceback (most recent call last):
File "./zopepy", line 366, in <module>
exec(compile(__file__f.read(), __file__, "exec"))
File "test1.py", line 29, in <module>
bar = IBar(foo)
File "eggs/zope.component-3.9.5-py2.7.egg/zope/component/_api.py", line 156, in adapter_hook
return sitemanager.queryAdapter(object, interface, name, default)
File "eggs/zope.component-3.9.5- py2.7.egg/zope/component/registry.py", line 228, in queryAdapter
return self.adapters.queryAdapter(object, interface, name, default)
File "eggs/zope.annotation-3.5.0-py2.7.egg/zope/annotation/factory.py", line 42, in getAnnotation
annotations = zope.annotation.interfaces.IAnnotations(context)
TypeError: ('Could not adapt', <__main__.Foo object at 0xb6d6956c>, <InterfaceClass zope.annotation.interfaces.IAnnotations>)
Example missing the following statements:
from zope.annotation.attribute import AttributeAnnotations
provideAdapter(AttributeAnnotations)

Resources