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

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

Everything works fine until I try to upload file to my database, either through app interface or admin interface, as it results in 500 Server error.

当我经历类似的问题时,我知道此错误不是由应用程序引擎引起的,但我真的很困惑,因为它在本地运行良好。

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

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

附加信息:我正在使用django 3.0.3

Here is my 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")

my 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/")

and here my 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 = 'levu865j#$#)+b$1bgh44u=tw(cd%j(3213je9ixk6=v5i5g7$'

    # 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()

    #DATABASES = {
    #    'default': {
    #        'ENGINE': 'django.db.backends.sqlite3',
    #        'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
    #    }
    #}
    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/first-project-272107:asia-south1:first-project-272107-sql-instance',
                'USER': 'admin',
                'PASSWORD': 'admin',
                'NAME': 'website_db',
            }
        }
    else:
        DATABASES = {
            'default': {
                'ENGINE': 'django.db.backends.mysql',
                'HOST': '127.0.0.1',
                'PORT': '3306',
                'NAME': 'website_db',
                'USER': 'admin',
                'PASSWORD': 'admin',
            }
        }
    # 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
评论
sesse
sesse

也是Django的新手,我遇到了类似的问题,在其他计算机上出现500错误,但是当我没有用户登录出现500错误的计算机时,我的笔记本电脑就没有问题。我认为那是因为我有一个视图正在更改其中有用户的字段,因此它无权更改数据库。您的代码似乎没有这个问题,但是也许您正在访问数据库。就我而言,只要我通过/ admin手动登录,就可以运行出现问题的页面。不过,我没有使用postgress,但我怀疑如果用户未登录,您也会获得500。不确定这是否有帮助,但我想将它扔在那里。

点赞
评论