Creating Import Hooks

Sreejith K sreejithemk at gmail.com
Thu Feb 18 10:28:37 CET 2010


On Feb 18, 1:57 pm, Steven D'Aprano
<ste... at REMOVE.THIS.cybersource.com.au> wrote:
> On Thu, 18 Feb 2010 00:03:51 -0800, Jonathan Gardner wrote:
> > On Feb 17, 10:48 pm, Sreejith K <sreejith... at gmail.com> wrote:
> >> Hi everyone,
>
> >> I need to implement custom import hooks for an application
> >> (http://www.python.org/dev/peps/pep-0302/). I want to restrict an
> >> application to import certain modules (say socket module). Google app
> >> engine is using a module hook to do this (HardenedModulesHook in
> >> google/ appengine/tools/dev_appserver.py). But I want to allow that
> >> application to use an sdk module (custom) which imports and uses socket
> >> module. But the module hook restricts the access by sdk. Finding out,
> >> which file is importing a module give a solution?? ie. If the
> >> application is importing socket module, I want to restrict it. But if
> >> the sdk module is importing socket I want to allow it. Is there any way
> >> I can do this ?
>
> >> Application
> >> ========
> >> import sdk
> >> import socket               # I dont want to allow this (need to raise
> >> ImportError)
>
> >> SDK
> >> ====
> >> import socket               # need to allow this
>
> > SDK
> > ===
> > import socket
>
> > App
> > ===
> > import SDK
> > import sys
> > socket = sys.modules['socket']
>
> I'm not sure, but I think Sreejith wants to prohibit imports from the App
> layer while allowing them from the SDK layer, not work around a
> prohibition in the SDK layer.
>
> In other words, he wants the import hook to do something like this:
>
> if module is socket and the caller is not SKD:
>     prohibit
> else
>     allow
>
> I could be wrong of course.
>
> --
> Steven

@Steven, Thats exactly what I want.. Anyway to do that ??



More information about the Python-list mailing list