该项目是一个快速示例项目,演示了应用程序在推送到主分支时自动构建、测试和部署到暂存环境的过程。
为了充分演示 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.
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中文网其他相关文章!

toAppendElementStoApythonList,usetheappend()方法forsingleements,Extend()formultiplelements,andinsert()forspecificpositions.1)useeAppend()foraddingoneOnelementAttheend.2)useextendTheEnd.2)useextendexendExendEnd(

TocreateaPythonlist,usesquarebrackets[]andseparateitemswithcommas.1)Listsaredynamicandcanholdmixeddatatypes.2)Useappend(),remove(),andslicingformanipulation.3)Listcomprehensionsareefficientforcreatinglists.4)Becautiouswithlistreferences;usecopy()orsl

金融、科研、医疗和AI等领域中,高效存储和处理数值数据至关重要。 1)在金融中,使用内存映射文件和NumPy库可显着提升数据处理速度。 2)科研领域,HDF5文件优化数据存储和检索。 3)医疗中,数据库优化技术如索引和分区提高数据查询性能。 4)AI中,数据分片和分布式训练加速模型训练。通过选择适当的工具和技术,并权衡存储与处理速度之间的trade-off,可以显着提升系统性能和可扩展性。

pythonarraysarecreatedusiseThearrayModule,notbuilt-Inlikelists.1)importThearrayModule.2)指定tefifythetypecode,例如,'i'forineizewithvalues.arreaysofferbettermemoremorefferbettermemoryfforhomogeNogeNogeNogeNogeNogeNogeNATATABUTESFELLESSFRESSIFERSTEMIFICETISTHANANLISTS。

除了shebang线,还有多种方法可以指定Python解释器:1.直接使用命令行中的python命令;2.使用批处理文件或shell脚本;3.使用构建工具如Make或CMake;4.使用任务运行器如Invoke。每个方法都有其优缺点,选择适合项目需求的方法很重要。

ForhandlinglargedatasetsinPython,useNumPyarraysforbetterperformance.1)NumPyarraysarememory-efficientandfasterfornumericaloperations.2)Avoidunnecessarytypeconversions.3)Leveragevectorizationforreducedtimecomplexity.4)Managememoryusagewithefficientdata

Inpython,ListSusedynamicMemoryAllocationWithOver-Asalose,而alenumpyArraySallaySallocateFixedMemory.1)listssallocatemoremoremoremorythanneededinentientary上,respizeTized.2)numpyarsallaysallaysallocateAllocateAllocateAlcocateExactMemoryForements,OfferingPrediCtableSageButlessemageButlesseflextlessibility。

Inpython,YouCansspecthedatatAtatatPeyFelemereModeRernSpant.1)Usenpynernrump.1)Usenpynyp.dloatp.dloatp.ploatm64,formor professisconsiscontrolatatypes。


热AI工具

Undresser.AI Undress
人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover
用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool
免费脱衣服图片

Clothoff.io
AI脱衣机

Video Face Swap
使用我们完全免费的人工智能换脸工具轻松在任何视频中换脸!

热门文章

热工具

记事本++7.3.1
好用且免费的代码编辑器

安全考试浏览器
Safe Exam Browser是一个安全的浏览器环境,用于安全地进行在线考试。该软件将任何计算机变成一个安全的工作站。它控制对任何实用工具的访问,并防止学生使用未经授权的资源。

SecLists
SecLists是最终安全测试人员的伙伴。它是一个包含各种类型列表的集合,这些列表在安全评估过程中经常使用,都在一个地方。SecLists通过方便地提供安全测试人员可能需要的所有列表,帮助提高安全测试的效率和生产力。列表类型包括用户名、密码、URL、模糊测试有效载荷、敏感数据模式、Web shell等等。测试人员只需将此存储库拉到新的测试机上,他就可以访问到所需的每种类型的列表。

禅工作室 13.0.1
功能强大的PHP集成开发环境

SublimeText3 Linux新版
SublimeText3 Linux最新版