LoginSignup
1
0

More than 1 year has passed since last update.

GitHub Actionsを利用してplaywrightを使ったAzure Functionsアプリをデプロイする(Python)

Posted at

はじめに

playwrightは実行前に以下のコマンドを実行してブラウザをインストールしておく必要がある。

playwright install

このときデフォルトではユーザーディレクトリ下にインストールされるが、環境変数のPLAYWRIGHT_BROWSERS_PATHにインストール先のパスを設定しておくことで任意の場所にブラウザをインストールすることが可能になる。
これを利用してAzure Functionsでplaywrightを使えるようにする。

今回動かすアプリ

コードは公式のサンプルコードをAzure Functions用に少し変更した。
アプリの内容はhttp://playwright.devにアクセスし、ページのタイトルを返すというもの。

ポイントはexecutable_path='./browser/chromium-1005/chrome-linux/chromeの部分。
executable_pathはブラウザの実行ファイルを指定するための引数で何も指定しないとデフォルトでインストールされているブラウザを使用する。
今回はブラウザのインストール時にPLAYWRIGHT_BROWSERS_PATH./browser/としているためexecutable_path./browser/chromium-1005/chrome-linux/chromeとする。

__init__.py
import azure.functions as func
from playwright.sync_api import sync_playwright


def main(req: func.HttpRequest) -> func.HttpResponse:
    with sync_playwright() as p:
        browser = p.chromium.launch(executable_path='./browser/chromium-1005/chrome-linux/chrome')
        page = browser.new_page()
        page.goto("http://playwright.dev")
        res = page.title()
        browser.close()

    return func.HttpResponse(res)
requirements.txt
azure-functions
playwright

GitHub Workflowを書く

環境変数のPLAYWRIGHT_BROWSERS_PATHを設定して作業ディレクトリ内にブラウザがインストールされるようにする。
あとは、ブラウザと一緒にAzure Functionへデプロイ。

name: Build and deploy Python project to Azure Function App

on:
  push:
    branches:
      - master
  workflow_dispatch:

env:
  AZURE_FUNCTIONAPP_PACKAGE_PATH: '.'
  PYTHON_VERSION: '3.9'

jobs:
  build:
    runs-on: ubuntu-latest
    steps:
      - name: Checkout repository
        uses: actions/checkout@v2

      - name: Setup Python version
        uses: actions/setup-python@v1
        with:
          python-version: ${{ env.PYTHON_VERSION }}

      - name: Create and start virtual environment
        run: |
          python -m venv venv
          source venv/bin/activate

      - name: Install dependencies
        run: pip install -r requirements.txt

      # ブラウザのインストール
      - name: Install browser
        run: playwright install chromium
        # 環境変数の設定(作業ディレクトリのbrowserディレクトリにインストール)
        env:
          PLAYWRIGHT_BROWSERS_PATH: ./browser

      - name: 'Deploy to Azure Functions'
        uses: Azure/functions-action@v1
        id: deploy-to-function
        with:
          app-name: 'playwright-azurefunc' # 適宜変更
          slot-name: 'production'
          package: ${{ env.AZURE_FUNCTIONAPP_PACKAGE_PATH }}
          publish-profile: ${{ secrets.AzureAppService_PublishProfile }}
          scm-do-build-during-deployment: true
          enable-oryx-build: true
1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0