调试时500错误= True Django

时间:2014-01-16 16:19:45

标签: python django internal-server-error

我有一个问题让我发疯。我有一个Apache的Django应用程序,它在特定部分抛出500错误。最奇怪的是我在Django设置中设置了DEBUG = True。实际上,该应用程序不会启动500页。除非我进入Firefox(或其他)的“页面检查器”,然后我看到页面和错误,否则我看不到500错误页面。我无法想象这是什么问题。我的Django版本是1.4。这是我的settings.py:

# -*- encoding: utf-8 -*-

import os
import logging

DEBUG = True
TEMPLATE_DEBUG = DEBUG

ADMINS = (
    # ('Your Name', 'your_email@domain.com'),
)

MANAGERS = ADMINS

CACHE_BACKEND = 'dummy://'

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql', # Add 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'.
        'NAME': 'teams',                      # Or path to database file if using sqlite3.
        'USER': 'xxxx',                      # Not used with sqlite3.
        'PASSWORD': 'xxxx',                  # Not used with sqlite3.
        'HOST': '',                      # Set to empty string for localhost. Not used with sqlite3.
        'PORT': '',                      # Set to empty string for default. Not used with sqlite3.
    }
}

TIME_ZONE = 'Europe/Madrid'
LANGUAGE_CODE = 'en-US'
SITE_ID = 3
USE_I18N = True
USE_L10N = True

PROJECT_ROOT = os.path.dirname(__file__)
MEDIA_ROOT = os.path.join(PROJECT_ROOT, 'media')
MEDIA_URL = '/media/'

ADMIN_MEDIA_PREFIX = '/admin_media/'

# Make this unique, and don't share it with anybody.
SECRET_KEY = 'j3v+(m*7wb^kbomqz&ask!)7k^%)=e8x9si3s2e-ywg6zonf(u'

# List of callables that know how to import templates from various sources.
TEMPLATE_LOADERS = (
    'django.template.loaders.filesystem.Loader',
    'django.template.loaders.app_directories.Loader',
#     'django.template.loaders.eggs.Loader',
)

MIDDLEWARE_CLASSES = (
    'django.middleware.common.CommonMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
#    'debug_toolbar.middleware.DebugToolbarMiddleware',
)
TEMPLATE_CONTEXT_PROCESSORS = (
#    "django.core.context_processors.auth",
    "django.core.context_processors.debug",
    "django.core.context_processors.i18n",
    "django.core.context_processors.media",
    "django.core.context_processors.request",
    "django.contrib.auth.context_processors.auth"
)

ROOT_URLCONF = 'urls'

TEMPLATE_DIRS = (
  os.path.join(PROJECT_ROOT, "templates"),
)

INSTALLED_APPS = (
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.sites',
    'django.contrib.messages',
    'django.contrib.admin',
    'south',
    # sentry
    'indexer',
    'paging',
    'sentry',
    'sentry.client',
#    'djcelery',
    'debug_toolbar',
    'django_beanstalkd',
    'webadmin',
    'teams_test',
    'video',
)

DEBUG_TOOLBAR_PANELS = (
    'debug_toolbar.panels.version.VersionDebugPanel',
    'debug_toolbar.panels.timer.TimerDebugPanel',
    'debug_toolbar.panels.settings_vars.SettingsVarsDebugPanel',
    'debug_toolbar.panels.headers.HeaderDebugPanel',
    'debug_toolbar.panels.request_vars.RequestVarsDebugPanel',
    'debug_toolbar.panels.template.TemplateDebugPanel',
    'debug_toolbar.panels.sql.SQLDebugPanel',
    'debug_toolbar.panels.signals.SignalDebugPanel',
    'debug_toolbar.panels.logger.LoggingPanel',
)
DEBUG_TOOLBAR_CONFIG = {
    'INTERCEPT_REDIRECTS': False
}

INTERNAL_IPS = ('127.0.0.1',)
INTERCEPT_REDIRECTS = False

GROUP_ADMINISTRATOR = 1
GROUP_TEAMS_ADMIN = 2
GROUP_CLIENT = 3
GROUP_TEAMS_SUPERVISOR = 4

CACHE_BACKEND = 'locmem:///?timeout=1000'
#CACHE_BACKEND = 'memcached://127.0.0.1:11211/'¬
CACHE_MIDDLEWARE_SECONDS = 60*5
CACHE_MIDDLEWARE_KEY_PREFIX = 'teams.'
CACHE_MIDDLEWARE_ANONYMOUS_ONLY = True

# video app conf
STATIC_URL = MEDIA_URL
STATIC_ROOT = MEDIA_ROOT

# celery conf
CELERYD_CONCURRENCY = 4
BROKER_HOST = "localhost"
BROKER_PORT = 5672
BROKER_USER = "guest"
BROKER_PASSWORD = "guest"
BROKER_VHOST = "/"

# mysql backend
#CELERY_RESULT_BACKEND = "database"
#CELERY_RESULT_DBURI = "mysql://root:root@localhost/teams"

MEDIA_ROOT = os.path.join(PROJECT_ROOT, 'media')

LOGIN_REDIRECT_URL = '/project/ongoing/'
PATH_ORIGIN_VIDEOS = os.path.join(MEDIA_ROOT, 'video')
PATH_TO_STORED_VIDEOS =  "/backup/"
URL_TO_STORED_VIDEOS = "/videos/"

# sentry conf
"""
from sentry.client.handlers import SentryHandler
logger = logging.getLogger()
# ensure we havent already registered the handler
if SentryHandler not in map(lambda x: x.__class__, logger.handlers):
    logger.addHandler(SentryHandler())

    # Add StreamHandler to sentry's default so you can catch missed exceptions
    logger = logging.getLogger('sentry.errors')
    logger.propagate = False
    logger.addHandler(logging.StreamHandler())
"""

#import djcelery
#djcelery.setup_loader()
##########################################
# this code must be at the end of this file
##########################################

try:
   from local_settings import *
except ImportError:
   pass

而不是,apache error.log不包含任何错误。我希望有人可以帮助我,因为我需要尽可能快地运行它。我可以看到Django的Debug页面本地化错误是非常有用的。

提前致谢。

版 - #1:

这些是我的views.py的几个部分,以及我在错误发生之前修改的另一个文件。我修改的唯一部分是功能finish_phase,它在那里表示。

def start_phase(request, phase_id):
    """
    Set phase start date
    """
    phase = get_object_or_404(Phase, pk=int(phase_id))
    cameras = Video.objects.filter(phase=phase)

    ###########################################################################
    ##   BEANSTALK
    ###########################################################################
    # supposed beanstalk concurrency worker is 4
    # TODO: modify django_beanstalkd to set concurrency in settings

    num_workers = 4
    time_to_run = 86400

    not_finished_phases = Phase.objects.exclude(start_date=None).filter(finish_date=None)
    num_cameras_being_recorded = 0
    for not_finished_phase in not_finished_phases:
        num_cameras_being_recorded += Video.objects.filter(phase=not_finished_phase).count()

    free_workers = num_workers - num_cameras_being_recorded
    ## init conversion to a mp4 file
    if free_workers >= len(cameras):
        try:
            beanstalk_client = BeanstalkClient()
        except Exception as e:
            print e
        for camera in cameras:
            ##initCapture.delay(camera.slug, camera.url, settings.MEDIA_ROOT,int(phase_id))
            arg = phase_id +' '+settings.PATH_ORIGIN_VIDEOS +' '+camera.slug
            beanstalk_client.call('video.startvlcserver', arg=arg, ttr=time_to_run)
    else:
        response = HttpResponse("<h1>Phase not started</h1>")
        response.write("<p>Camera streams can't be recorded. There are too many cameras working</p>")
        return response
    ##############################################################################

    phase.start_date = datetime.datetime.now()
    phase.save()

此函数start_phase调用函数startvlcserver:

def startvlcserver(arg):
    """
    Capture video from an rtsp stream with mp4v codec
    arg format: "phase_id url static_root name"
    """
    phase_id, original_path, name = arg.split(" ")
    Popen("echo  se levanta el servidor: phase: %s %s >> /tmp/startvlcserver.log" % (phase_id, datetime.datetime.now().strftime("%B %d %H:%M:%S")), shell=True)
    split_command = ['cvlc']
    split_command.append('rtsp://user:password@192.168.2.21/img/media.sav')
    split_command.append("--sout") 
    split_command.append("#transcode{venc=x264{profile=baseline,preset=fast,tune=grain,keyint=25,min-keyint=25,fps=25,bitrate=500},fps=25}:std{mux=mp4,access=file,dst=/home/wtelecom/test.mp4}")
    print "#"*30
    print "comando: " 
    print split_command
    sp = Popen(split_command)
    video = Video.objects.get(phase__id=phase_id)
    video.pid = sp.pid
    video.save()

好的,这两个功能在我的应用中运行良好。我的想法是,当我开始阶段时,IP摄像头开始录制。视频流在函数startvlcserver中转码为mp4格式。但是停止记录需要停止vlcserver。这是停止阶段和记录的函数,以及抛出错误的函数:

def finish_phase(request, phase_id):
    """
    Set phase finish date
    """
    data = {'success':False}
    if request.method == 'POST' and request.is_ajax():
        phase = get_object_or_404(Phase, pk=int(phase_id))

    # This is the new code added that leaded me to the error:
        cameras = Video.objects.filter(phase=phase)
        #transcoding video
        ###########################################
        # beanstalk
        ###########################################
        for camera in cameras:
            # stop stream capturing
            os.kill(camera.pid, signal.SIGTERM)
    # End of the new code

        phase.finish_date = datetime.datetime.now()
        phase.save()
        data['success'] = True

    return HttpResponse(simplejson.dumps(data))

那么让我们看看这段代码是否有助于大家理解错误并帮助我解决问题。

0 个答案:

没有答案