简体   繁体   中英

How to consume/integrate third-party modules in Python

I am new to Python and recently started writing a script which essentially reads a MySQL database and archives some files by uploading them to Amazon Glacier. I am using the Amazon-provided boto module along with a few other modules.

I noticed that I seem to be replicating the same pattern over and over again when installing and taking advantage of these modules that connect to external services. First, I write a wrapper module which reads my global config values and then defines a connection function, then I start writing functions in that module which perform the various tasks. For example, at the moment, my boto wrapper module is named awsbox and it consists of functions like getConnection and glacierUpload . Here's a brief example:

import config,sys,os
import boto,uuid

_awsConfig = config.get()['aws']

def getGlacierConnection():
  return boto.connect_glacier( aws_access_key_id=_awsConfig['access_key_id'],
                               aws_secret_access_key=_awsConfig['secret_access_key'])


def glacierUpload( filePath ):

  if not os.path.isfile( filePath ):
    return False

  awsConnect = getGlacierConnection()    

  vault = awsConnect.get_vault( _awsConfig['vault'] )

  vault.upload_archive( filePath )

  return True

My question is, should I be writing these "wrapper" modules? Is this the Pythonic way to consume these third-party modules? This method makes sense to me but I wonder if creating these interfaces makes my code less portable or modular, or whether or not there is a better way to integrate these various disparate modules into my main script structure.

You're using the modules as intented. You import them and then use them. As I see it, awsbox is the module that holds the implementation of the functions that match your needs.

So answering your cuestion:

should I be writing these "wrapper" modules? , yes (you can stop calling them "wrappers"), an error would be to rewrite those installed modules.

Is this the Pythonic way to consume these third-party modules? , Is the Python way. Authors write modules for you tu use(import).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM