quick search:
 

make Products importable to (Script) Python

Submitted by: runyaga
Last Edited: 2004-10-14

Category: Product Development

Average rating is: 4.22 out of 5 (9 ratings)

Description:
there are lots of modules in the python world. and getting
access to them in (Script) Pythons makes a world of difference.
this allows you to import stripogram module from Squishdot Product.


Source (Text):
#in Products/Squishdot/__init__.py edit it and at the bottom add
"""
from Products.PythonScripts.Utility import allow_module, allow_class
from AccessControl import ModuleSecurityInfo, ClassSecurityInfo
from Globals import InitializeClass
import stripogram
from stripogram import HTML2SafeHTML

ModuleSecurityInfo('Products').declarePublic('Squishdot')
ModuleSecurityInfo('Products.Squishdot').declarePublic('stripogram')
ModuleSecurityInfo('Products.Squishdot.stripogram').declarePublic('html2safehtml')

allow_module('Products.Squishdot.stripogram')
allow_class(HTML2SafeHTML)
"""

#then create a test (Script) Python called stripHTML

from Products.Squishdot.stripogram import html2safehtml

html = "<html><body><title>import power</title> " \
     + "<a href='http://www.zope.org'>zope.org</a> </body></html>"
good = html2safehtml(html, valid_tags=('a', 'br'))
return good

save and click Test, viola.  stripped html.

Explanation:
the first 3 lines of imports are for ZOPE Permissions machinery.
import stripogram (your inside the /Squishdot directory) to get module into namespace
as well as the HTML2SafeHTML class (just to show off how to get classes into (Script) Python.

ModuleSecuritInfo('Products').declarePublic('Package') signals security to
the existence of Products.Package. (you do this for all of your modules)

allow_module('Package.module.mymodule') is the trick (its a string) that
this tells the permissions machinery to let you access mymodule which is in the
Package/module directory. (if you know more about python you will know
it doesnt necessarily HAVE To be a directory)

allow_class() accepts a class instance, not a string.



Comments:

It works by Cheez - 2004-10-14
Despite misgivings I tried this and it works. 
In 2.4 it worked w/o ModuleSecurityInfo('Products.Squishdot.stripogram').declarePublic('html2safehtml')
and 
allow_class(HTML2SafeHTML)

not sure why



New from 2.5b4 by gotcha - 2004-10-14
You do not need to use multiple declarePublic() anymore.
The ModuleSecurityInfo makes the package traversal recursively for you.

IOW, you replace 

ModuleSecurityInfo('Products').declarePublic('Squishdot')
ModuleSecurityInfo('Products.Squishdot').declarePublic('stripogram')
ModuleSecurityInfo('Products.Squishdot.stripogram').declarePublic('html2safehtml')


by only

ModuleSecurityInfo('Products.Squishdot.stripogram').declarePublic('html2safehtml')


Thanks! by jcaustin - 2004-10-14
This kind of example is invaluable for someone trying to get up to speed with Zope.