ThinkChat🤖让你学习和工作更高效,注册即送10W Token,即刻开启你的AI之旅 广告
# Test and deploy a Python application with GitLab CI/CD > 原文:[https://docs.gitlab.com/ee/ci/examples/test-and-deploy-python-application-to-heroku.html](https://docs.gitlab.com/ee/ci/examples/test-and-deploy-python-application-to-heroku.html) * [Configure project](#configure-project) * [Store API keys](#store-api-keys) * [Create Heroku application](#create-heroku-application) * [Create Runner](#create-runner) # Test and deploy a Python application with GitLab CI/CD[](#test-and-deploy-a-python-application-with-gitlab-cicd "Permalink") 本示例将指导您如何在 Python 应用程序中运行测试,以及如何将其自动部署为 Heroku 应用程序. 您也可以查看或生成完整的[示例源](https://gitlab.com/ayufan/python-getting-started) . ## Configure project[](#configure-project "Permalink") 这是此项目的`.gitlab-ci.yml`文件的外观: ``` stages: - test - deploy test: stage: test script: # this configures Django application to use attached postgres database that is run on `postgres` host - export DATABASE_URL=postgres://postgres:@postgres:5432/python-test-app - apt-get update -qy - apt-get install -y python-dev python-pip - pip install -r requirements.txt - python manage.py test staging: stage: deploy script: - apt-get update -qy - apt-get install -y ruby-dev - gem install dpl - dpl --provider=heroku --app=gitlab-ci-python-test-staging --api-key=$HEROKU_STAGING_API_KEY only: - master production: stage: deploy script: - apt-get update -qy - apt-get install -y ruby-dev - gem install dpl - dpl --provider=heroku --app=gitlab-ci-python-test-prod --api-key=$HEROKU_PRODUCTION_API_KEY only: - tags ``` 这个项目有三个工作: * `test` -用于测试 Django 应用程序. * `staging` -用于每次推送到`master`分支时自动部署登台环境. * `production` -用于为每个创建的标签自动部署生产环境. ## Store API keys[](#store-api-keys "Permalink") 您需要在 GitLab 项目的**"设置">" CI / CD">"环境变量"**中创建两个变量: * `HEROKU_STAGING_API_KEY` -Heroku API 密钥,用于部署登台应用程序. * `HEROKU_PRODUCTION_API_KEY` -Heroku API 密钥,用于部署生产应用程序. 在" [管理帐户"中](https://dashboard.heroku.com/account)找到您的 Heroku API 密钥. ## Create Heroku application[](#create-heroku-application "Permalink") 对于每个环境,您都需要创建一个新的 Heroku 应用程序. 您可以通过[仪表板](https://dashboard.heroku.com/)执行此操作. ## Create Runner[](#create-runner "Permalink") 首先安装[Docker Engine](https://s0docs0docker0com.icopy.site/installation/) . 要构建此项目,您还需要安装[GitLab Runner](https://docs.gitlab.com/runner/index.html) . 您可以使用`gitlab.com`上的公共跑步者,也可以注册自己的跑步者: ``` cat > /tmp/test-config.template.toml << EOF [[runners]] [runners.docker] [[runners.docker.services]] name = "postgres:latest" EOF gitlab-runner register \ --non-interactive \ --url "https://gitlab.com/" \ --registration-token "PROJECT_REGISTRATION_TOKEN" \ --description "python-3.5" \ --executor "docker" \ --template-config /tmp/test-config.template.toml \ --docker-image python:3.5 ``` 使用上面的命令,您将创建一个使用[`python:3.5`](https://hub.docker.com/_/python)图像并使用[PostgreSQL](https://hub.docker.com/_/postgres)数据库的运行器. 要访问 PostgreSQL 数据库,请以没有密码的用户`postgres`身份连接到`host: postgres` .