我有一个简单的 SQL 文件,我想在 SnapLogic 中使用 Python Script Snap 读取和执行它。我创建了一个表达式库文件来引用 Redshift 帐户,并将其作为参数包含在管道中。
我有下面来自另一篇文章的代码。有没有办法引用管道参数连接Redshift数据库,读取上传的SQL文件并执行命令?
fd = open('shared/PythonExecuteTest.sql', 'r')
sqlFile = fd.read()
fd.close()
sqlCommands = sqlFile.split(';')
for command in sqlCommands:
try:
c.execute(command)
except OperationalError, msg:
print "Command skipped: ", msg
最佳答案
您可以使用 $_
在脚本中访问管道参数。
假设您有一个管道参数 executionId
。然后要在脚本中访问它,您可以执行 $_executionId
。
以下是测试流水线。
使用以下管道参数。
以下为测试数据
脚本如下
# Import the interface required by the Script snap.
from com.snaplogic.scripting.language import ScriptHook
import java.util
class TransformScript(ScriptHook):
def __init__(self, input, output, error, log):
self.input = input
self.output = output
self.error = error
self.log = log
# The "execute()" method is called once when the pipeline is started
# and allowed to process its inputs or just send data to its outputs.
def execute(self):
self.log.info("Executing Transform script")
while self.input.hasNext():
try:
# Read the next document, wrap it in a map and write out the wrapper
in_doc = self.input.next()
wrapper = java.util.HashMap()
wrapper['output'] = in_doc
wrapper['output']['executionId'] = $_executionId
self.output.write(in_doc, wrapper)
except Exception as e:
errWrapper = {
'errMsg' : str(e.args)
}
self.log.error("Error in python script")
self.error.write(errWrapper)
self.log.info("Finished executing the Transform script")
# The Script Snap will look for a ScriptHook object in the "hook"
# variable. The snap will then call the hook's "execute" method.
hook = TransformScript(input, output, error, log)
输出:
在这里,你可以看到executionId
是从管道参数中读取的。
注意:从脚本访问管道参数是一种有效方案,但从脚本访问其他外部系统很复杂(因为您需要加载所需的库),因此不推荐使用。使用 SnapLogic 提供的快照访问外部系统。此外,如果您想在脚本中使用其他库,请尝试坚持使用 Javascript 而不是使用 python,因为您可以在脚本中使用许多开源 CDN。
此外,您不能直接从脚本访问任何已配置的表达式库。如果您需要脚本中的一些逻辑,您可以将其保留在脚本中而不是其他地方。而且,在脚本(或映射器)中访问帐户名是没有意义的,因为即使您知道帐户名,也不能直接使用存储在该帐户中的凭据/配置;由 SnapLogic 处理。尽可能使用提供的快照和映射器。
更新#1
- 您无法直接访问该帐户。帐户由快照在内部管理和使用。您只能通过相关快照的帐户选项卡创建和设置帐户。
- 尽可能避免使用 script snap;特别是,如果您可以使用普通快照做同样的事情。
更新#2
满足此要求的最简单解决方案如下。
- 使用文件阅读器读取文件
- 根据
拆分;
- 使用Generic JDBC Execute Snap 执行每个 SQL 命令
关于python - SnapLogic Python 读取和执行 SQL 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52936600/