搜尋
首頁後端開發Python教學使用 GitHub Actions 自動化建置、測試和部署流程

該專案是一個快速範例項目,演示了應用程式在推送到主分支時自動建置、測試和部署到暫存環境的過程。

為了充分示範 CI/CD 管道,我們將使用最少的程式碼建立一個簡單的 Python 項目,然後將其整合到 GitHub Actions 中。

創建一個簡單的 Python 項目

就像我之前所說的,我們將創建一個將在管道中使用的簡單項目。我選擇在 python 中執行此操作沒有特殊原因,您可以使用您選擇的任何其他程式語言,這個專案的主要目的是演示管道。

建立專案資料夾

所以繼續建立專案資料夾並導航到該資料夾:

mkdir automated-testing
cd automated-testing

撰寫申請文件

現在我們將編寫簡單的Python應用程式。在專案資料夾中建立一個新檔案app.py。

touch app.py

將以下程式碼區塊加入檔案:

def hello():
  return "Hello, World!"

if __name__ == "__main__":
  print(hello())

這是一個非常簡單的 Python「Hello world」函數,作為可以在 CI 管道中測試的基本功能的範例。

def hello() 定義了一個名為 hello 的函數,它不帶任何參數。呼叫此函數時,它會傳回字串「Hello, World!」。

if __name__ == "__main__" 是一個標準的 Python 構造,用於確保某些程式碼僅在直接執行檔案時運行(而不是作為模組導入時)。它充當腳本的入口點。

直接執行 app.py 時(例如,透過執行 python app.py),腳本將呼叫 hello() 函數並列印結果,即「Hello, World!」。

建立需求文件。

典型的專案會有依賴項,在 python 專案中,它們通常在requirements.txt 檔案中定義。

建立新檔案requirements.txt

touch requirements.txt

將其新增至檔案:

pytest

建立單元測試

現在我們將新增一個基本測試檔test_app.py來測試app.py中的功能。將以下內容新增至文件:

from app import hello

def test_hello():
  assert hello() == "Hello, World!"

現在我們已準備好建立管道。

為 CI/CD 設定 GitHub 操作

要設定 GitHub 操作,我們需要在儲存庫中建立一個 .github/workflows 資料夾,這是我們向 GitHub 通知儲存庫中的 CI/CD 管道的方式。

建立一個新檔案:

mkdir -p .github/workflows

您可以在一個儲存庫中擁有多個管道,因此請在 .github/workflows 資料夾中建立一個檔案 proj.yml。我們將在這裡定義建置、測試和部署 Python 專案的步驟。

將以下程式碼加入您的檔案:

name: Build, Test and Deploy

# Trigger the workflow on pushes to the main branch
on:
  push:
    branches:
      - main

jobs:
  build-and-test:
    runs-on: ubuntu-latest

    steps:
    # Checkout the code from the repository
    - name: Checkout repo
      uses: actions/checkout@v4

    # Set up Python environment
    - name: Setup Python
      uses: actions/setup-python@v5
      with:
        python-version: '3.x'

    # Install dependencies
    - name: Install Dependecies
      run: |
        python -m pip install --upgrade pip
        pip install -r requirements.txt

    # Build (this project deosn't require a build but we will simulate a build by creating a file)
    - name: Build Project
      run: |
        mkdir -p build
        # Simulate build output by creating a file
        touch build/output_file.txt

    # Run tests using pytest
    - name: Run tests
      run: 
        pytest

    # Upload the build output as an artifact (we created a file in the build step to simulate an artifact)
    - name: Upload build artifact
      uses: actions/upload-artifact@v4
      with:
        name: build-artifact
        path: build/

  deploy:
    runs-on: ubuntu-latest
    needs: build-and-test
    if: success()

    steps:
    # Download the artifact from the build stage
    - name: Download build artifact
      uses: actions/download-artifact@v4
      with:
        name: build-artifact
        path: build/

    - name: Simulate Deployment
      run: |
        echo "Deploying to staging..."
        ls build/

Breakdown of the CI/CD Pipeline Steps

  • Trigger on Push to main: The pipeline is triggered whenever there is a push to the main branch.
  • Checkout Code: This step uses GitHub’s checkout action to pull our code from the repository.
  • Set Up Python: The pipeline sets up a Python environment on the CI runner (GitHub's virtual machine), ensuring that the correct Python version is used.
  • Install Dependencies: It installs the required dependencies for our Python project (pytest in this case). This dependency was just added as an example of when a project has dependencies as this particular sample python application does not require any.
  • Build: This stage was also just added for demonstration purposes, supposing this was a JavaScript/Node.js project this is where we would run the npm run build command and this will create an artifact we can upload and use in the deploy stage. Since this is a python project and it doesn't really require a build, we will create a file and folder in this stage. The file will serve as our artifact for the deploy stage.
  • Run Tests: It runs the tests using pytest to validate the code.
  • Upload Build Artifact: After running the tests, the build-and-test stage creates and saves a build artifact (in this case, a simulated output_file.txt in the build folder from the build step). The action upload-artifact is used to store this artifact. You can replace this with whatever actual build output your project creates.
  • Deploy Stage: Our application will only be deployed if the test was successful which is why I have added the conditionals needs and if. Using “needs” we can require that the deploy job won’t even run unless the test job is successful. The download-artifact action retrieves the build artifact and the last step "Simulate Deployment" simulates deployment by printing a message and lists the artifact. If this was a live project we would have the actual deployment commands to deploy to a real staging environment here. You can replace the echo and ls commands with actual deployment commands (e.g., deploying to a cloud platform). This approach ensures that the output from the build-and-test stage is properly passed to the deploy stage, simulating how a real deployment would work with build artifacts.

Push to GitHub

If you haven't already, you need to initialize a git repository using the commands below:

git init
git add .
git commit -m "Create project as well as CI/CD pipeline"

Now we push to GitHub. Create a GitHub repository and push your code using the below commands:

git remote add origin <your-repo-url>
git push -u origin main
</your-repo-url>

Verify the Pipeline

After pushing the code, you can visit the Actions tab in your GitHub repository. You should see the pipeline triggered, running the steps defined in your proj.yml file.

If everything is set up correctly, the pipeline will build, test, and simulate deployment. You can changes things around in your project and make new pushes to see the the pipeline works, create errors intentional so you can see how the pipeline works when the tests fail.

On a successful run this is how your Actions tab should look.

Automate Build, Test & Deploy Processes with GitHub Actions

And that's it, this setup provides a working example of a CI/CD pipeline for a very basic Python project. If you found this helpful, please share with your connection and if you have any questions, do not hesitate to drop the question in the comments.

以上是使用 GitHub Actions 自動化建置、測試和部署流程的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
如何解決Linux終端中查看Python版本時遇到的權限問題?如何解決Linux終端中查看Python版本時遇到的權限問題?Apr 01, 2025 pm 05:09 PM

Linux終端中查看Python版本時遇到權限問題的解決方法當你在Linux終端中嘗試查看Python的版本時,輸入python...

我如何使用美麗的湯來解析HTML?我如何使用美麗的湯來解析HTML?Mar 10, 2025 pm 06:54 PM

本文解釋瞭如何使用美麗的湯庫來解析html。 它詳細介紹了常見方法,例如find(),find_all(),select()和get_text(),以用於數據提取,處理不同的HTML結構和錯誤以及替代方案(SEL)

如何使用TensorFlow或Pytorch進行深度學習?如何使用TensorFlow或Pytorch進行深度學習?Mar 10, 2025 pm 06:52 PM

本文比較了Tensorflow和Pytorch的深度學習。 它詳細介紹了所涉及的步驟:數據準備,模型構建,培訓,評估和部署。 框架之間的關鍵差異,特別是關於計算刻度的

如何使用Python創建命令行接口(CLI)?如何使用Python創建命令行接口(CLI)?Mar 10, 2025 pm 06:48 PM

本文指導Python開發人員構建命令行界面(CLIS)。 它使用Typer,Click和ArgParse等庫詳細介紹,強調輸入/輸出處理,並促進用戶友好的設計模式,以提高CLI可用性。

哪些流行的Python庫及其用途?哪些流行的Python庫及其用途?Mar 21, 2025 pm 06:46 PM

本文討論了諸如Numpy,Pandas,Matplotlib,Scikit-Learn,Tensorflow,Tensorflow,Django,Blask和請求等流行的Python庫,並詳細介紹了它們在科學計算,數據分析,可視化,機器學習,網絡開發和H中的用途

在Python中如何高效地將一個DataFrame的整列複製到另一個結構不同的DataFrame中?在Python中如何高效地將一個DataFrame的整列複製到另一個結構不同的DataFrame中?Apr 01, 2025 pm 11:15 PM

在使用Python的pandas庫時,如何在兩個結構不同的DataFrame之間進行整列複製是一個常見的問題。假設我們有兩個Dat...

解釋Python中虛擬環境的目的。解釋Python中虛擬環境的目的。Mar 19, 2025 pm 02:27 PM

文章討論了虛擬環境在Python中的作用,重點是管理項目依賴性並避免衝突。它詳細介紹了他們在改善項目管理和減少依賴問題方面的創建,激活和利益。

什麼是正則表達式?什麼是正則表達式?Mar 20, 2025 pm 06:25 PM

正則表達式是在編程中進行模式匹配和文本操作的強大工具,從而提高了各種應用程序的文本處理效率。

See all articles

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

AI Hentai Generator

AI Hentai Generator

免費產生 AI 無盡。

熱門文章

R.E.P.O.能量晶體解釋及其做什麼(黃色晶體)
3 週前By尊渡假赌尊渡假赌尊渡假赌
R.E.P.O.最佳圖形設置
3 週前By尊渡假赌尊渡假赌尊渡假赌
R.E.P.O.如果您聽不到任何人,如何修復音頻
3 週前By尊渡假赌尊渡假赌尊渡假赌

熱工具

SublimeText3 Mac版

SublimeText3 Mac版

神級程式碼編輯軟體(SublimeText3)

PhpStorm Mac 版本

PhpStorm Mac 版本

最新(2018.2.1 )專業的PHP整合開發工具

Atom編輯器mac版下載

Atom編輯器mac版下載

最受歡迎的的開源編輯器

mPDF

mPDF

mPDF是一個PHP庫,可以從UTF-8編碼的HTML產生PDF檔案。原作者Ian Back編寫mPDF以從他的網站上「即時」輸出PDF文件,並處理不同的語言。與原始腳本如HTML2FPDF相比,它的速度較慢,並且在使用Unicode字體時產生的檔案較大,但支援CSS樣式等,並進行了大量增強。支援幾乎所有語言,包括RTL(阿拉伯語和希伯來語)和CJK(中日韓)。支援嵌套的區塊級元素(如P、DIV),

Dreamweaver Mac版

Dreamweaver Mac版

視覺化網頁開發工具