简体   繁体   English

如何在Python中使用/集成第三​​方模块

[英]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. 我是Python的新手,最近开始编写一个脚本,该脚本本质上是读取MySQL数据库并通过将某些文件上传到Amazon Glacier来存档一些文件。 I am using the Amazon-provided boto module along with a few other modules. 我正在使用Amazon提供的boto模块以及其他一些模块。

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 . 例如,目前,我的boto包装器模块名为awsbox ,它包含诸如getConnectionglacierUpload类的函数。 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? 这是使用Python方式使用这些第三方模块的方法吗? 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. 如我所见, awsbox是包含符合您需求的功能的实现的模块。

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? 这是使用Python方式使用这些第三方模块的方法吗? , Is the Python way. ,是Python的方式。 Authors write modules for you tu use(import). 作者编写模块供您使用(导入)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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