Python 用于下载和上传具有不同扩展名的文件的 Webhook
Python Webhook to download and upload files with different extensions
我正在创建一个 Python Webhook 来拦截包含文件附件 url 的 FormStack 数据(以 JSON 格式发送)。我需要下载文件附件并通过 SendGrid API.
将其作为邮件附件发送
SendGrid API 需要文件名和路径作为附加文件的参数。
message.add_attachment('stuff.txt', './stuff.txt')
我提到了 urllib2
,但我似乎无法找到一种方法来下载任何扩展名的文件并获取其位置以进一步上传它。
将其下载到一个临时文件中,例如使用 tempfile
.
关键行(简体):
s = urllib2.urlopen(url).read()
tf = tempfile.NamedTemporaryFile(suffix='.txt', delete=False) # OPT: dir=mytempdir
tf.write(s)
path = tf.name
tf.close()
对我有用的完整详细代码
import tempfile
import sendgrid
url = 'your download url'
file_name = file_name = url.split('/')[-1]
t_file = tempfile.NamedTemporaryFile(suffix=file_name, dir="/mydir_loc" delete=False)
# Default directory is '/tmp' but you can explicitly mention a directory also
# Set Delete to True if you want the file to be deleted after closing
data = urllib2.urlopen(url).read()
t_file.write(data)
# SendGrid API calls
message.add_attachment(file_name, tf.name)
status, msg = sg.send(message)
t_file.close()
我正在创建一个 Python Webhook 来拦截包含文件附件 url 的 FormStack 数据(以 JSON 格式发送)。我需要下载文件附件并通过 SendGrid API.
将其作为邮件附件发送SendGrid API 需要文件名和路径作为附加文件的参数。
message.add_attachment('stuff.txt', './stuff.txt')
我提到了 urllib2
,但我似乎无法找到一种方法来下载任何扩展名的文件并获取其位置以进一步上传它。
将其下载到一个临时文件中,例如使用 tempfile
.
关键行(简体):
s = urllib2.urlopen(url).read()
tf = tempfile.NamedTemporaryFile(suffix='.txt', delete=False) # OPT: dir=mytempdir
tf.write(s)
path = tf.name
tf.close()
对我有用的完整详细代码
import tempfile
import sendgrid
url = 'your download url'
file_name = file_name = url.split('/')[-1]
t_file = tempfile.NamedTemporaryFile(suffix=file_name, dir="/mydir_loc" delete=False)
# Default directory is '/tmp' but you can explicitly mention a directory also
# Set Delete to True if you want the file to be deleted after closing
data = urllib2.urlopen(url).read()
t_file.write(data)
# SendGrid API calls
message.add_attachment(file_name, tf.name)
status, msg = sg.send(message)
t_file.close()