在 azure 应用服务上托管 Django 应用程序

问题描述 投票:0回答:1

按照官方的 host python with postgres 教程,并在我的 gh actions 文件中进行修改(因为我的 django 应用程序不存在于存储库的根目录中)后,我在尝试访问它时收到 404 错误。

这是我的设置.py

"""
Django settings for server project.

Generated by 'django-admin startproject' using Django 5.0.3.

For more information on this file, see
https://docs.djangoproject.com/en/5.0/topics/settings/

For the full list of settings and their values, see
https://docs.djangoproject.com/en/5.0/ref/settings/
"""

from decouple import config
from os import environ
from google.oauth2 import service_account

from pathlib import Path

from django.conf import global_settings

# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent


# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/5.0/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = config(
    "SECRET_KEY",
    default="django-insecure-g8khpcexyyb0q@p40^d5#r_j#ezf%(-90r-y^2@x1)2$wpch9+",
)

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = config("DEBUG", default=False, cast=bool)

ALLOWED_HOSTS = (
    [environ["WEBSITE_HOSTNAME"]]
    if "WEBSITE_HOSTNAME" in environ
    else config(
        "ALLOWED_HOSTS", cast=lambda v: [s.strip() for s in v.split(",")], default=[]
    )
)

CORS_ALLOWED_ORIGINS = config(
    "CORS_ALLOWED_ORIGINS",
    cast=lambda v: [s.strip() for s in v.split(",")],
    default="http://localhost:5173,http://127.0.0.1:5173",
)


# Application definition

INSTALLED_APPS = [
    "django.contrib.admin",
    "django.contrib.auth",
    "django.contrib.contenttypes",
    "django.contrib.sessions",
    "django.contrib.messages",
    "django.contrib.staticfiles",
    "rest_framework",
    "rest_framework.authtoken",
    "djoser",
    "corsheaders",
    "drf_spectacular",
    "accounts.apps.AccountsConfig",
    "videos.apps.VideosConfig",
]

MIDDLEWARE = [
    "django.middleware.security.SecurityMiddleware",
    "whitenoise.middleware.WhiteNoiseMiddleware",
    "django.contrib.sessions.middleware.SessionMiddleware",
    "corsheaders.middleware.CorsMiddleware",
    "django.middleware.common.CommonMiddleware",
    "django.middleware.csrf.CsrfViewMiddleware",
    "django.contrib.auth.middleware.AuthenticationMiddleware",
    "django.contrib.messages.middleware.MessageMiddleware",
    "django.middleware.clickjacking.XFrameOptionsMiddleware",
]

ROOT_URLCONF = "server.urls"

TEMPLATES = [
    {
        "BACKEND": "django.template.backends.django.DjangoTemplates",
        "DIRS": [],
        "APP_DIRS": True,
        "OPTIONS": {
            "context_processors": [
                "django.template.context_processors.debug",
                "django.template.context_processors.request",
                "django.contrib.auth.context_processors.auth",
                "django.contrib.messages.context_processors.messages",
            ],
        },
    },
]

WSGI_APPLICATION = "server.wsgi.application"


# Database
# https://docs.djangoproject.com/en/5.0/ref/settings/#databases

DATABASES = {
    "default": {
        "ENGINE": config("DB_ENGINE", default="django.db.backends.sqlite3"),
        "NAME": config("DB_NAME", default=BASE_DIR / "db.sqlite3"),
        "USER": config("DB_USER", default=""),
        "PASSWORD": config("DB_PASSWORD", default=""),
        "HOST": config("DB_HOST", default=""),
        "PORT": config("DB_PORT", default=""),
    }
}


# Password validation
# https://docs.djangoproject.com/en/5.0/ref/settings/#auth-password-validators

AUTH_PASSWORD_VALIDATORS = [
    {
        "NAME": "django.contrib.auth.password_validation.UserAttributeSimilarityValidator",
    },
    {
        "NAME": "django.contrib.auth.password_validation.MinimumLengthValidator",
    },
    {
        "NAME": "django.contrib.auth.password_validation.CommonPasswordValidator",
    },
    {
        "NAME": "django.contrib.auth.password_validation.NumericPasswordValidator",
    },
]

REST_FRAMEWORK = {
    "DEFAULT_AUTHENTICATION_CLASSES": [
        "rest_framework.authentication.TokenAuthentication",
        "rest_framework.authentication.SessionAuthentication",
        "rest_framework.authentication.BasicAuthentication",  # simple cmd line tools can access the API
    ],
    "DEFAULT_SCHEMA_CLASS": "drf_spectacular.openapi.AutoSchema",
    "DEFAULT_PAGINATION_CLASS": "rest_framework.pagination.LimitOffsetPagination",
    "PAGE_SIZE": 100,
}


SPECTACULAR_SETTINGS = {
    "TITLE": "Video API",
    "DESCRIPTION": "Amalitech Video API",
    "VERSION": "1.0.0",
    "SERVE_INCLUDE_SCHEMA": False,
    # OTHER SETTINGS
}

DJOSER = {"PASSWORD_RESET_CONFIRM_URL": "password-reset-confirm/{uid}/{token}"}

EMAIL_HOST = config("EMAIL_HOST", default="localhost")
EMAIL_HOST_PASSWORD = config("EMAIL_HOST_PASSWORD", default="")
EMAIL_HOST_USER = config("EMAIL_HOST_USER", default="")
EMAIL_PORT = config("EMAIL_PORT", default=25, cast=int)
EMAIL_USE_TLS = config("EMAIL_USE_TLS", default=False, cast=bool)

# Internationalization
# https://docs.djangoproject.com/en/5.0/topics/i18n/

LANGUAGE_CODE = "en-us"

TIME_ZONE = "UTC"

USE_I18N = True

USE_TZ = True


# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/5.0/howto/static-files/

STATIC_URL = "static/"

STATIC_ROOT = BASE_DIR / "static"

SESSION_ENGINE = "django.contrib.sessions.backends.cache"
STATICFILES_STORAGE = "whitenoise.storage.CompressedManifestStaticFilesStorage"

DEFAULT_FILE_STORAGE = config(
    "DEFAULT_FILE_STORAGE", default=global_settings.DEFAULT_FILE_STORAGE
)

GS_CREDENTIALS = service_account.Credentials.from_service_account_file(
    BASE_DIR / "serviceaccount.json"
)

GS_BUCKET_NAME = config("GS_BUCKET_NAME", default="")
GS_DEFAULT_ACL = config("GS_DEFAULT_ACL", default="")

# Default primary key field type
# https://docs.djangoproject.com/en/5.0/ref/settings/#default-auto-field

DEFAULT_AUTO_FIELD = "django.db.models.BigAutoField"

以及用于部署到应用程序服务的 gh 操作

# Docs for the Azure Web Apps Deploy action: https://github.com/Azure/webapps-deploy
# More GitHub Actions for Azure: https://github.com/Azure/actions
# More info on Python, GitHub Actions, and Azure App Service: https://aka.ms/python-webapps-actions

name: Build and deploy Python app to Azure Web App - plvids

on:
  push:
    branches:
      - main
  workflow_dispatch:

jobs:
  build:
    runs-on: ubuntu-latest
    defaults:
      run:
        working-directory: ./apps/server
    environment:
      name: 'Production'
    steps:
      - uses: actions/checkout@v4

      - name: Set up Python version
        uses: actions/setup-python@v1
        with:
          python-version: '3.11'

      - name: Create settings.ini file
        run: |
          echo [settings] >> settings.ini
          echo "ALLOWED_HOSTS = ${{ secrets.ALLOWED_HOSTS }}" >> settings.ini
          echo "SECRET_KEY = ${{ secrets.SECRET_KEY }}" >> settings.ini
          echo "DB_NAME = ${{ secrets.DBNAME }}" >> settings.ini
          echo "DB_USER = ${{ secrets.DBUSER }}" >> settings.ini
          echo "DB_PASSWORD = ${{ secrets.DBPASSWORD }}" >> settings.ini
          echo "DB_ENGINE = ${{ secrets.DB_ENGINE }}" >> settings.ini
          echo "DB_HOST = ${{ secrets.DBHOST }}" >> settings.ini
          echo "DB_PORT = ${{ secrets.DBPORT }}" >> settings.ini
          echo "DEFAULT_FILE_STORAGE = ${{ secrets.DEFAULT_FILE_STORAGE }}" >> settings.ini
          echo "EMAIL_HOST = ${{ secrets.EMAIL_HOST }}" >> settings.ini
          echo "EMAIL_PORT = ${{ secrets.EMAIL_PORT }}" >> settings.ini
          echo "EMAIL_HOST_USER = ${{ secrets.EMAIL_HOST_USER }}" >> settings.ini
          echo "EMAIL_HOST_PASSWORD = ${{ secrets.EMAIL_HOST_PASSWORD }}" >> settings.ini
          echo "GS_BUCKET_NAME = ${{ secrets.EMAIL_HOST_PASSWORD }}" >> settings.ini
          echo "GS_DEFAULT_ACL = ${{ secrets.GS_DEFAULT_ACL }}" >> settings.ini
          echo '${{secrets.GS_SERVICE_ACCOUNT}}' >> serviceaccount.json
        shell: bash

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

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

      # Optional: Add step to run tests here (PyTest, Django test suites, etc.)

      - name: Zip artifact for deployment
        run: zip release.zip ./* -r

      - name: Upload artifact for deployment jobs
        uses: actions/upload-artifact@v3
        with:
          name: python-app
          path: |
            ./apps/server/release.zip
            !venv/

  deploy:
    runs-on: ubuntu-latest
    needs: build
    environment:
      name: 'Production'
      url: ${{ steps.deploy-to-webapp.outputs.webapp-url }}
    permissions:
      id-token: write #This is required for requesting the JWT

    steps:
      - name: Download artifact from build job
        uses: actions/download-artifact@v3
        with:
          name: python-app

      - name: Unzip artifact for deployment
        run: unzip release.zip

      - name: Login to Azure
        uses: azure/login@v1
        with:
          client-id: ${{ secrets.*** }}
          tenant-id: ${{ secrets.*** }}
          subscription-id: ${{ secrets.*** }}

      - name: 'Deploy to Azure Web App'
        uses: azure/webapps-deploy@v2
        id: deploy-to-webapp
        with:
          app-name: '***'
          slot-name: 'Production'

应用程序服务中的日志没有显示任何内容

构建日志显示构建成功,没有任何错误

这是存储库的链接

python django azure continuous-integration azure-web-app-service
1个回答
0
投票

导航到 Web 应用程序的 KUDU 站点 (

https://videoplatform30.scm.azurewebsites.net/newui
) 并检查日志流中的日志。

enter image description here


我已将您的 Django 项目部署到 Azure 并使其按预期工作。

GitHub 工作流程:

name: Build and deploy Python app to Azure Web App - appname

on:
  push:
    branches:
      - main
  workflow_dispatch:

jobs:
  build:
    runs-on: ubuntu-latest
    defaults:
      run:
        working-directory: ./apps/server
    steps:
      - uses: actions/checkout@v4

      - name: Set up Python version
        uses: actions/setup-python@v1
        with:
          python-version: '3.11'

      - 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: Zip artifact for deployment
        run: zip release.zip ./* -r

      - name: Upload artifact for deployment jobs
        uses: actions/upload-artifact@v3
        with:
          name: python-app
          path: |
            ./apps/server/release.zip
            !venv/
  deploy:
    runs-on: ubuntu-latest
    needs: build
    environment:
      name: 'Production'
      url: ${{ steps.deploy-to-webapp.outputs.webapp-url }}
    
    steps:
      - name: Download artifact from build job
        uses: actions/download-artifact@v3
        with:
          name: python-app

      - name: Unzip artifact for deployment
        run: unzip release.zip

      
      - name: 'Deploy to Azure Web App'
        uses: azure/webapps-deploy@v2
        id: deploy-to-webapp
        with:
          app-name: 'appname'
          slot-name: 'Production'
          publish-profile: ${{ secrets.AZUREAPPSERVICE_PUBLISHPROFILE_7793CXXXX4DA }}
  • 使用 GitHub 操作部署到 Python Azure 应用服务(Linux):

enter image description here

  • 能够运行应用程序:

enter image description here

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.