Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Import python module over the internet/multiple protocols or dynamically create module

Is it possible to import a Python module from over the internet using the http(s), ftp, smb or any other protocol? If so, how? If not, why?

I guess it's about making Python use more the one protocol(reading the filesystem) and enabling it to use others as well. Yes I agree it would be many folds slower, but some optimization and larger future bandwidths would certainly balance it out.

E.g.:

import site

site.addsitedir("https://bitbucket.org/zzzeek/sqlalchemy/src/e8167548429b9d4937caaa09740ffe9bdab1ef61/lib")

import sqlalchemy
import sqlalchemy.engine
like image 607
Bleeding Fingers Avatar asked Sep 11 '13 16:09

Bleeding Fingers


2 Answers

In principle, yes, but all of the tools built-in which kinda support this go through the filesystem.

To do this, you're going to have to load the source from wherever, compile it with compile, and exec it with the __dict__ of a new module. See below.

I have left the actually grabbing text from the internet, and parsing uris etc as an exercise for the reader (for beginners: I suggest using requests)

In pep 302 terms, this would be the implementation behind a loader.load_module function (the parameters are different). See that document for details on how to integrate this with the import statement.

import imp
modulesource = 'a=1;b=2' #load from internet or wherever
def makemodule(modulesource,sourcestr='http://some/url/or/whatever',modname=None):
    #if loading from the internet, you'd probably want to parse the uri, 
    # and use the last part as the modulename. It'll come up in tracebacks
    # and the like.
    if not modname: modname = 'newmodulename'
    #must be exec mode
    # every module needs a source to be identified, can be any value
    # but if loading from the internet, you'd use the URI
    codeobj = compile(modulesource, sourcestr, 'exec')
    newmodule = imp.new_module(modname)
    exec(codeobj,newmodule.__dict__)
    return newmodule
newmodule = makemodule(modulesource)
print(newmodule.a)

At this point newmodule is already a module object in scope, so you don't need to import it or anything.

modulesource = '''
a = 'foo'
def myfun(astr):
    return a + astr
'''
newmod = makemodule(modulesource)
print(newmod.myfun('bat'))

Ideone here: http://ideone.com/dXGziO

Tested with python 2, should work with python 3 (textually compatible print used;function-like exec syntax used).

like image 115
Marcin Avatar answered Oct 21 '22 08:10

Marcin


Another version,

I like this answer. when applied it, i simplified it a bit - similar to the look and feel of javascript includes over HTTP.

This is the result:

import os
import imp
import requests

def import_cdn(uri, name=None):
    if not name:
        name = os.path.basename(uri).lower().rstrip('.py')

    r = requests.get(uri)
    r.raise_for_status()

    codeobj = compile(r.content, uri, 'exec')
    module = imp.new_module(name)
    exec (codeobj, module.__dict__)
    return module

Usage:

redisdl = import_cdn("https://raw.githubusercontent.com/p/redis-dump-load/master/redisdl.py")

# Regular usage of the dynamic included library
json_text = redisdl.dumps(host='127.0.0.1')
  • Tip - place the import_cdn function in a common library, this way you could re-use this small function
  • Bear in mind It will fail when no connectivity to that file over http
like image 22
Jossef Harush Kadouri Avatar answered Oct 21 '22 09:10

Jossef Harush Kadouri