在App Engine中部署Django后出现500服务器错误

时间:2020-05-17 21:49:48

标签: python django google-app-engine

我正在尝试部署Django网站,以便使用应用程序引擎共享笔记。

一切正常,直到我尝试通过应用程序界面或管理界面将文件上传到数据库中,因为它会导致500 Server error

我经历了类似的问题,我知道此错误不是由应用程序引擎引起的,但我真的很困惑,因为它在本地可以正常工作。

我能够将文件上传到通过云代理连接它的数据库。

我试图检查日志并进行调试,但是没有提供任何线索。

更多信息: 部署设置设置DEBUG = True时,上传时显示此错误...

[Errno 30] Read-only file system: '/srv/media/storage/hall_ETTBXhS.jpeg'

其他信息:我正在使用django 3.0.3

这是我的views.py

from django.shortcuts import render, redirect
from .models  import notes
from .forms import upload
import datetime

# Create your views here.
def home(request):
    context={}
    context["dataset"] = notes.objects.all()
    return render(request, "noteitdown/home.html", context)

def upload_view(request):
    context = {}
    date = datetime.date.today()
    if (request.method == 'POST'):
        form = upload(request.POST, request.FILES)
        if form.is_valid():
            data = form.cleaned_data
            entry = notes(author_name=data["author_name"], date_of_pub=date, department=data["department"], file=data["file"])
            entry.save()
            return redirect('home')
        else:
            print(form.errors)
    form = upload()
    context["form"] = form
    return render(request, "noteitdown/upload.html", context)

def about(request):
    return render(request, "noteitdown/about.html")

我的Models.py

from django.db import models

# Create your models here.
class notes(models.Model):
    author_name = models.CharField(max_length=20)
    date_of_pub = models.DateField()
    department = models.CharField(max_length=20)
    file = models.FileField(upload_to="storage/")

,这里是我的settings.py

"""
Django settings for website project.

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

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

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

import os

# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))


# Quick-start development settings - unsuitable for production
# See 

    https://docs.djangoproject.com/en/3.0/howto/deployment/checklist/

    # SECURITY WARNING: keep the secret key used in production secret!
    SECRET_KEY = '[SECRET_KEY]'

    # SECURITY WARNING: don't run with debug turned on in production!
    DEBUG = False

    ALLOWED_HOSTS = ["*"]


    # Application definition

    INSTALLED_APPS = [
        'noteitdown.apps.NoteitdownConfig',
        'django.contrib.admin',
        'django.contrib.auth',
        'django.contrib.contenttypes',
        'django.contrib.sessions',
        'django.contrib.messages',
        'django.contrib.staticfiles',
    ]

    MIDDLEWARE = [
        'django.middleware.security.SecurityMiddleware',
        'django.contrib.sessions.middleware.SessionMiddleware',
        'django.middleware.common.CommonMiddleware',
        'django.middleware.csrf.CsrfViewMiddleware',
        'django.contrib.auth.middleware.AuthenticationMiddleware',
        'django.contrib.messages.middleware.MessageMiddleware',
        'django.middleware.clickjacking.XFrameOptionsMiddleware',
    ]

    ROOT_URLCONF = 'website.urls'

    TEMPLATES = [
        {
            'BACKEND': 'django.template.backends.django.DjangoTemplates',
            'DIRS': ['noteitdown/templates'],
            '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 = 'website.wsgi.application'


    # Database
    # https://docs.djangoproject.com/en/3.0/ref/settings/#databases
    import pymysql
    pymysql.version_info = (1, 3, 13, "final", 0)
    pymysql.install_as_MySQLdb()

    if os.getenv('GAE_APPLICATION', None):
        # Running on production App Engine, so connect to Google Cloud SQL using
        # the unix socket at /cloudsql/<your-cloudsql-connection string>
        DATABASES = {
            'default': {
                'ENGINE': 'django.db.backends.mysql',
                'HOST': '/cloudsql/[SQL_INSTANCE_CONNECTION_NAME]',
                'USER': '[USER]',
                'PASSWORD': '[PASSWORD]',
                'NAME': 'website_db',
            }
        }
    else:
        DATABASES = {
            'default': {
                'ENGINE': 'django.db.backends.mysql',
                'HOST': '127.0.0.1',
                'PORT': '3306',
                'NAME': 'website_db',
                'USER': '[USER]',
                'PASSWORD': '[PASSWORD]',
            }
        }
    # Password validation
    # https://docs.djangoproject.com/en/3.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',
        },
    ]


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

    LANGUAGE_CODE = 'en-us'

    TIME_ZONE = 'UTC'

    USE_I18N = True

    USE_L10N = True

    USE_TZ = True


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

    STATIC_URL = '/static/'
    STATIC_ROOT = os.path.join(BASE_DIR,'static/')
    MEDIA_URL = '/media/'
    MEDIA_ROOT = os.path.join(BASE_DIR,'media/')

    try:
      import googleclouddebugger
      googleclouddebugger.enable()
    except ImportError:
  pass

App Engine日志:

2020-05-18 02:34:36.192 IST GET 200 1.07 KiB 12 ms Chrome 81 /noteitdown/upload
2020-05-18 02:35:13.219 IST POST 500 337 B 3.2 s Chrome 81 /noteitdown/upload

本地Django日志:

[17/May/2020 20:20:43] "POST /noteitdown/upload HTTP/1.1" 302 0
[17/May/2020 20:20:43] "GET /noteitdown/ HTTP/1.1" 200 2158

1 个答案:

答案 0 :(得分:0)

您似乎面临的错误是因为您正在将文件写入实例的文件系统中。根据{{​​3}},您只能将临时文件写入目录/tmp。请记住,这样做将使用RAM内存(而不是存储空间),并且仅在创建文件的实例上可用。

如果您打算保留文件,则应the documentation