Timer 트리거를 Azure Function에서 시도(Windows 10, Python)


Azure Function에서 파이톤의 자체 제작 프로그램 라이브러리를 사용하고 로컬 서버로 Timer 트리거를 이동하는 것이 힘들기 때문에 총괄해 봤습니다.
코드는 여기.
Windows 10, Python을 전제로 합니다.
나는 프로그램에 관해 쓰지 않지만 환경 설정을 포함하여 아래의 사이트는 매우 상세하다.
https://blog.beachside.dev/entry/2020/08/13/224000
https://blog.beachside.dev/entry/2020/09/09/190000
다음은 비망록 정도의 비망록.

환경 설정


VS 코드의 사용을 전제로 한 것 같습니다.
Azure Function Core Tools에 필요한 Node.js를 설치하고 VS 코드에 Azure Function의 확장 기능을 설치합니다.
npm의 명령줄에 Azure Function Core Tools V3을 설치합니다.
npm install --global azure-functions-core-tools@3 --unsafe-perm true --save-dev
https://docs.microsoft.com/ja-jp/azure/developer/javascript/tutorial/vscode-function-app-http-trigger/tutorial-vscode-serverless-node-install?tabs=bash
이렇게 하면 명령줄에서func 명령을 사용할 수 있다.
또한func 명령을 식별할 수 없으면 환경 변수Path를 사용하여 다음 npm 폴더를 설정하십시오.
C:\Users\ユーザーネーム\AppData\Roaming\npm
func 명령에 대한 상세한 내용은 아래의 내용을 참조한다.
https://docs.microsoft.com/ja-jp/azure/azure-functions/functions-core-tools-reference?tabs=v2#func-new

실행 파일 만들기


Python용 AzureFunction 항목을 만들도록 명령합니다.
필요한 파일이 자동으로 생성됩니다.
또한 GUI를 사용하여 VScode의 Azure 탭에서 작업하는 것도 동일합니다.
func init 任意のプロジェクトフォルダ --python
프로젝트 폴더로 이동합니다.
cd 任意のプロジェクトフォルダ名
venv를 통해 가상 환경을 만듭니다.
python -m venv .venv
.venv\scripts\activate
이후에 나타나는 Function은 로컬에서 실행되는 func start를 가상 환경에서 실행해야 합니다.
이 명령은 가상 환경에서 실행되어야 합니다.
https://docs.microsoft.com/ja-jp/azure/azure-functions/functions-run-local?tabs=v3%2Cwindows%2Cpython%2Cportal%2Cbash%2Ckeda
필요할 때 pip와 Requirement를 업그레이드할 수 있습니다.txt에서 라이브러리를 설치하는 게 좋겠죠?
python -m pip install  --upgrade pip
pip install -r requirements.txt
로컬에서 실행되는 Function을 만듭니다.
HTTP 트리거는temlate 이름을 지정하여 만들 수 있습니다.
func new --name ファンクションのフォルダ名 --template "HTTP trigger"
명령줄에서 일람표에서 트리거를 선택할 수 있습니다.
func new --name ファンクションのフォルダ名
다음 func 명령으로 만들 수 있는template 목록을 출력할 수 있습니다.
func template list
Timer 트리거를 로컬로 실행하는 동안 다음 오류가 발생했습니다.
The listener for function 'Functions.HelloTimer' was unable to start. Azure.Core: Retry failed after 6 tries. Retry settings can be adjusted in ClientOptions.Retry.
이유는 아주어의 시뮬레이터가 작동하지 않았기 때문이다.
https://stackoverflow.com/questions/59026572/listener-for-function-was-unable-to-start-azure-function-app-timetrigger
Azurite를 사용하면 시뮬레이터의 구축이 편리합니다.
https://qiita.com/uzresk/items/538c0f997faa736a75aa
Azurete를 사용하려면 npm에 Azurete를 설치합니다.
npm install -g azurite
C: 바로 아래에 azurite라는 폴더를 만들고 VS 코드와 다른 명령줄에 다음 명령을 입력합니다.
azurite --silent --location c:\azurite --debug c:\azurite\debug.log
https://docs.microsoft.com/ja-jp/azure/storage/common/storage-use-azurite?tabs=visual-studio-code
다음 로그를 출력하고 Azure 에뮬레이터를 시작합니다.
Azurite Blob service is starting at http://127.0.0.1:10000
Azurite Blob service is successfully listening at http://127.0.0.1:10000
Azurite Queue service is starting at http://127.0.0.1:10001
Azurite Queue service is successfully listening at http://127.0.0.1:10001
Azurite Table service is starting at http://127.0.0.1:10002
Azurite Table service is successfully listening at http://127.0.0.1:10002
VS 코드의 명령줄에서 Timer 트리거를 실행합니다.
func start
그럼, init.py 파일 주석이 추가된 부분을 실행합니다.
def main(mytimer: func.TimerRequest) -> None:
    utc_timestamp = datetime.datetime.utcnow().replace(
        tzinfo=datetime.timezone.utc).isoformat()

    if mytimer.past_due:
        logging.info('The timer is past due!') ## ココが初期実行

    logging.info('Python timer trigger function ran at %s', utc_timestamp) ## ココが定期実行
일지는 다음과 같다.
[2021-10-24T10:28:47.349Z] Worker process started and initialized.
[2021-10-24T10:28:47.461Z] The timer is past due!
[2021-10-24T10:28:47.464Z] Python timer trigger function ran at 2021-10-24T10:28:47.459041+00:00
[2021-10-24T10:28:47.481Z] Executed 'Functions.HelloTimer' (Succeeded, Id=8e31eaf8-7ad7-49df-a756-bae82aa01543, Duration=396ms)
[2021-10-24T10:28:51.970Z] Host lock lease acquired by instance ID '00000000000000000000000088A4879D'.
Timer가 트리거하는 실행 시간을 바꾸기 위해function.제이슨 안의 schedule을 다 고치면 됩니다.
function.json
"schedule": "0 */1 * * * *"
각 숫자는 다음과 같은 뜻을 나타낸다.
{second} {minute} {hour} {day} {month} {day-of-week}  
이외에 다음과 같은 기술로 조건을 설정할 수 있다.
Type
예제
촉발 시기
특정 값
0 5 * * * *
시간당 1회, 1일 시간당 5분
모든 값(*)
0 * 5 * * *
5시부터 1분마다.
영역(-연산자)
5-7 * * * * *
1분 3회 - 매일, 각 시간, 분당 5초에서 7초
값 설정(, 연산자)
5,8,10 * * * * *
1분 3회 - 매일, 시간별, 분당 5초, 8초, 10초
간격(/연산자)
0 */5 * * * *
1시간 12회-매일, 시간당 5분 0초
https://docs.microsoft.com/ja-jp/azure/azure-functions/functions-bindings-timer?tabs=python#configuration

자체 제작 라이브러리 사용


프로젝트 폴더 바로 아래에 라이브러리에 저장된 폴더를 만들고 그 중에서 실행하려고 합니다.py 파일과 빈 init.py 파일을 저장하는 경우 Function 폴더 내의 init입니다.py 파일 import 라이브러리를 사용하여 실행을 터치할 수 있습니다.
폴더 구성
|----- .venv/
|----- .vscode/
|----- functionフォルダ(HelloTimer)/
|   |----- __init__.py   # 実行ファイル
|   |----- function.json # トリガー情報(実行時間)が記載されたファイル
|
|----- 自作ライブラリを格納するフォルダ/
|   |----- __init__.py   # 中身は空っぽで問題ない
|   |----- 自作ライブラリの.pyファイル(display_time.py)
|
|----- .gitignore
|----- getting_started.md
|----- host.json
|----- local.settings.json
|----- requirements.txt
https://docs.microsoft.com/ja-jp/azure/azure-functions/functions-reference-python?tabs=azurecli-linux%2Capplication-level
현재 시간만 출력할 수 있는 간단한 자작 프로그램 라이브러리를 실행해 보십시오.
display_time>display_time.py
import datetime

class display_time_now:
  def time_now(self):
    time = datetime.datetime.now()
    return time
HelloTimer>__init__.py
import datetime
import logging
import azure.functions as func
from display_time import display_time # 追加した自作ライブラリ

nowtime = display_time.display_time_now()     # 追加
time = nowtime.time_now()                     # 追加
time_str = time.strftime('%Y/%m/%d %H:%M:%S') # 追加

def main(mytimer: func.TimerRequest) -> None:
    utc_timestamp = datetime.datetime.utcnow().replace(
        tzinfo=datetime.timezone.utc).isoformat()

    if mytimer.past_due:
        logging.info('The timer is past due!')

    logging.info('Python timer trigger function ran at %s', utc_timestamp)
    print(f"現在時刻 {time_str}")             # 追加
로그 출력은 다음과 같습니다.
내보낼 로그
[2021-10-24T11:07:00.028Z] Python timer trigger function ran at 2021-10-24T11:07:00.027065+00:00
[2021-10-24T11:07:00.028Z] 現在時刻 2021/10/24 20:05:29
이상은 끝까지 읽어주셔서 감사합니다.

좋은 웹페이지 즐겨찾기