Python中的Azure Functions与GnuPG调用
我在使用Python编写一个Azure函数,并尝试用python-gnupg这个工具来调用GnuPG的程序,目的是在本地开发时使用。
这是我在Azure函数中尝试的代码,触发方式是HTTP请求。
import gnupg
import tempfile
import subprocess
import azure.functions as func
import logging
@app.route(route="PGPOne")
def PGPOne(req: func.HttpRequest, context: func.Context) -> func.HttpResponse:
logging.info('Python HTTP trigger function processed a request.')
# Correctly obtaining the GPG binary path
gpg_path = r'C:\PGPD\dependencies\gpg.exe'
# Testing the GPG binary works
result = subprocess.run([gpg_path, '--version'], capture_output=True, text=True)
print(result.stdout)
# Creating a temporary directory for GPG home
temp_dir = tempfile.mkdtemp()
print(f"Temporary GPG home directory: {temp_dir}")
# Initializing GPG with the temporary home directory
gpg = gnupg.GPG(homedir=temp_dir, binary=gpg_path)
name = req.params.get('name')
if not name:
try:
req_body = req.get_json()
except ValueError:
pass
else:
name = req_body.get('name')
if name:
return func.HttpResponse(f"Hello, {name}. This HTTP triggered function executed successfully.")
else:
return func.HttpResponse(
"This HTTP triggered function executed successfully. Pass a name in the query string or in the request body for a personalized response.",
status_code=200
代码块[测试GPG程序是否正常]和[为GPG创建临时目录]都按预期工作,我在相应的打印语句中得到了以下输出。
Temporary directory: C:\Users\<myusername>\AppData\Local\Temp\tmpxacvv8_i
GPG binary path: C:\PGPD\dependencies\gpg.exe
但是调用
gnupg.GPG(homedir=temp_dir, binary=gpg_path)
时出现了一个以-开头的错误。
Python HTTP trigger function processed a request.
[2024-03-18T04:13:19.620Z] Creating directory: C:\PGPD\'C:\Users\<myusername>\AppData\Local\Temp\tmpxacvv8_i'
[2024-03-18T04:13:19.658Z] [WinError 123] The filename, directory name, or volume label syntax is incorrect: "C:\\PGPD\\'C:"
为什么在创建目录时调用的部分会有这个前缀呢:
C:\PGPD\'
我哪里做错了,应该怎么修正呢?
这是在使用Function Core Tools本地调试这个函数时进行的,使用的是Python 3.10,并在VS Code中设置了虚拟环境。
我已经按照微软文档的建议,把GnuPG的程序依赖放到了代码文件夹结构中。
1 个回答
1
下面是我用过的代码
,你可以把它整合到Azure函数里。我是按照这个文档来操作的:
import gnupg
import tempfile
import os
import subprocess as rithsb
rithgpg_path = r'C:\Program Files (x86)\GnuPG\bin\gpg.exe'
oute = rithsb.run([rithgpg_path, '--version'], capture_output=True, text=True)
print(oute.stdout)
rith_temp_dir = tempfile.mkdtemp()
print(f"Temporary GPG home directory: {rith_temp_dir}")
gpg = gnupg.GPG(gnupghome=os.path.abspath(rith_temp_dir))
print(gpg)
输出: