[英]How to access file in /tmp directory of AWS Lambda
我已經從 URL 下載了一個文件到 AWS Lambda 的 /tmp 目錄中(因為這是 Lambda 中唯一的可寫路徑)。
我的動機是創建一個 Alexa Skill,它將從 URL 下載文件。 因此我創建了一個 lambda function。
如何從 lambda 的 /tmp 文件夾訪問下載的文件?
我的代碼是: -
#!/usr/bin/python
# -*- coding: utf-8 -*-
from __future__ import print_function
import xml.etree.ElementTree as etree
from datetime import datetime as dt
import os
import urllib
import requests
from urllib.parse import urlparse
def lambda_handler(event, context):
""" Route the incoming request based on type (LaunchRequest, IntentRequest,
etc.) The JSON body of the request is provided in the event parameter.
"""
print('event.session.application.applicationId=' + event['session'
]['application']['applicationId'])
# if (event['session']['application']['applicationId'] !=
# "amzn1.echo-sdk-ams.app.[unique-value-here]"):
# raise ValueError("Invalid Application ID")
if event['session']['new']:
on_session_started({'requestId': event['request']['requestId'
]}, event['session'])
if event['request']['type'] == 'LaunchRequest':
return on_launch(event['request'], event['session'])
elif event['request']['type'] == 'IntentRequest':
return on_intent(event['request'], event['session'])
elif event['request']['type'] == 'SessionEndedRequest':
return on_session_ended(event['request'], event['session'])
def on_session_started(session_started_request, session):
""" Called when the session starts """
print('on_session_started requestId='
+ session_started_request['requestId'] + ', sessionId='
+ session['sessionId'])
def on_launch(launch_request, session):
""" Called when the user launches the skill without specifying what they
want
"""
print('on_launch requestId=' + launch_request['requestId']
+ ', sessionId=' + session['sessionId'])
# Dispatch to your skill's launch
return get_welcome_response()
def on_intent(intent_request, session):
""" Called when the user specifies an intent for this skill """
print('on_intent requestId=' + intent_request['requestId']
+ ', sessionId=' + session['sessionId'])
intent = intent_request['intent']
intent_name = intent_request['intent']['name']
# Dispatch to your skill's intent handlers
if intent_name == 'DownloadFiles':
return get_file(intent, session)
elif intent_name == 'AMAZON.HelpIntent':
return get_welcome_response()
else:
raise ValueError('Invalid intent')
def on_session_ended(session_ended_request, session):
""" Called when the user ends the session.Is not called when the skill returns should_end_session=true """
print('on_session_ended requestId='
+ session_ended_request['requestId'] + ', sessionId='
+ session['sessionId'])
# add cleanup logic here
# --------------- Functions that control the skill's behavior ------------------
def get_welcome_response():
""" If we wanted to initialize the session to have some attributes we could add those here """
session_attributes = {}
card_title = 'Welcome'
speech_output = \
"Welcome to file download Application. Please ask me to download files by saying, Ask auto downloader for download"
# If the user either does not reply to the welcome message or says something
# that is not understood, they will be prompted again with this text.
reprompt_text = \
"Please ask me to download files by saying, Ask auto downloader for download"
should_end_session = False
return build_response(session_attributes,
build_speechlet_response(card_title,
speech_output, reprompt_text,
should_end_session))
def get_file(intent, session):
""" Grabs the files from the path that have to be downloaded """
card_title = intent['name']
session_attributes = {}
should_end_session = True
username = '*******'
password = '*******'
url = 'https://drive.google.com/drive/my-drive/abc.pdf'
filename = os.path.basename(urlparse(url).path)
# urllib.urlretrieve(url, "code.zip")
r = requests.get(url, auth=(username, password))
if r.status_code == 200:
with open("/tmp/" + filename, 'wb') as out:
for bits in r.iter_content():
out.write(bits)
speech_output = 'The file filename has been downloaded'
return build_response(session_attributes,
build_speechlet_response(card_title,
speech_output, reprompt_text,
should_end_session))
# --------------- Helpers that build all of the responses ----------------------
def build_speechlet_response(
title,
output,
reprompt_text,
should_end_session,
):
return {
'outputSpeech': {'type': 'PlainText', 'text': output},
'card': {'type': 'Simple', 'title': 'SessionSpeechlet - ' \
+ title, 'content': 'SessionSpeechlet - ' + output},
'reprompt': {'outputSpeech': {'type': 'PlainText',
'text': reprompt_text}},
'shouldEndSession': should_end_session,
}
def build_response(session_attributes, speechlet_response):
return {'version': '1.0', 'sessionAttributes': session_attributes,
'response': speechlet_response}
只需像往常一樣打開文件:
with open('/tmp/'+ filename, 'rb') as file:
...
這對我來說一直有效。 您是否嘗試過並遇到任何問題?
請注意,Lambda 在容器中運行。 下載一次后,該文件將位於/tmp
文件夾中,直到此容器存在為止。 在啟動容器以提供您的功能后,它通常會存活 10-30 分鍾(可能更少或更多,這不是官方的固定時間)。 因此,與其總是下載文件,不如檢查該文件是否不在/tmp
目錄中。 如果是,您顯然不必再次下載! ;)
要進行此檢查,請使用:
if not os.path.isfile('/tmp/' + filename):
download...
For anyone who ends up here and is using a Docker image as the Lambda function: AWS cleans out /tmp either when the Docker image is uploaded to ECS or when the Lambda function is executed.
這意味着,如果您依賴 /tmp 中的任何內容(例如,您正在將文件復制到 Dockerfile 中的 /tmp),您將觀察到 Docker 映像在本地運行良好,並且按預期包含 /tmp 中的文件,但是您當您嘗試在 AWS 中將相同的 Docker 圖像作為 Lambda function 運行時出現錯誤,因為該文件不在 /tmp 中。
我建議將文件放在只讀的 LAMBDA_TASK_ROOT(現在是 /var/task 目錄)中。 如果你需要修改這個文件,那么我會從 LAMBDA_TASK_ROOT 目錄中讀取它,並將它寫入 /tmp。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.