Here are the examples of the python api django.http.HttpResponseServerError taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
138 Examples
3
Example 1
@xframe_options_exempt
def error500(request):
try:
template = loader.get_template('500.html')
except TemplateDoesNotExist:
return HttpResponseServerError('<h1>Server Error (500)</h1>', content_type='text/html')
return HttpResponseServerError(template.render(Context({
'STATIC_URL': getattr(settings, 'STATIC_URL', '/static/'),
})))
3
Example 2
@requires_csrf_token
def server_error(request):
"""
500 error handler.
"""
template = get_template("djangobmf/500.html")
return HttpResponseServerError(
template.render(
Context({})
)
)
3
Example 3
@login_required
def disconnect(request, backend):
"""Disconnects given backend from current logged in user."""
backend = get_backend(backend, request, request.path)
if not backend:
return HttpResponseServerError('Incorrect authentication service')
backend.disconnect(request.user)
url = request.REQUEST.get(REDIRECT_FIELD_NAME, '') or DEFAULT_REDIRECT
return HttpResponseRedirect(url)
3
Example 4
def server_error(request, template_name='500.html'):
"""
500 error handler.
Templates: `500.html`
Context:
MEDIA_URL
Path of static media (e.g. "media.example.org")
"""
t = loader.get_template(template_name)
return http.HttpResponseServerError(t.render(RequestContext({
'MEDIA_URL': settings.MEDIA_URL
})))
3
Example 5
def server_error(request, template_name='500.html'):
template = loader.get_template(template_name)
context = Context({
'stacktrace' : traceback.format_exc()
})
return HttpResponseServerError( template.render(context) )
3
Example 6
Project: brigitte Source File: views.py
def server_error(request, template_name='500.html'):
""" needed for rendering 500 pages with style. """
t = loader.get_template(template_name)
return http.HttpResponseServerError(t.render(Context({
'request': request,
'STATIC_URL': settings.STATIC_URL,
})))
3
Example 7
def server_error(request, template_name='500.html'):
"""
500 error handler.
Templates: `500.html`
Context: None
"""
t = loader.get_template(template_name) # You need to create a 500.html template.
return http.HttpResponseServerError(t.render(RequestContext(request)))
3
Example 8
def __call__(self, environ, start_response):
request = self.request_class(environ)
self.debug('Request from %s' % request.get_host())
try:
response = self.backend.handle_request(request)
except Exception, e:
self.exception(e)
response = http.HttpResponseServerError()
try:
status_text = STATUS_CODE_TEXT[response.status_code]
except KeyError:
status_text = 'UNKNOWN STATUS CODE'
status = '%s %s' % (response.status_code, status_text)
response_headers = [(str(k), str(v)) for k, v in response.items()]
start_response(status, response_headers)
return response
3
Example 9
@csrf_exempt
def xmlrpc(request):
if request.method not in ['POST', 'GET']:
return HttpResponseRedirect(urlresolvers.reverse(
'patchwork.views.help', kwargs={'path': 'pwclient/'}))
response = HttpResponse()
if request.method == 'POST':
try:
ret = dispatcher._marshaled_dispatch(request)
except Exception:
return HttpResponseServerError()
else:
ret = dispatcher.generate_html_docuementation()
response.write(ret)
return response
3
Example 10
@requires_csrf_token
def server_error(request, template_name='500.html'):
"""
500 error handler.
Templates: :template:`500.html`
Context: None
"""
try:
template = loader.get_template(template_name)
except TemplateDoesNotExist:
return http.HttpResponseServerError('<h1>Server Error (500)</h1>', content_type='text/html')
return http.HttpResponseServerError(template.render())
3
Example 11
@requires_csrf_token
def server_error(request, template_name='500.html'):
"""
500 error handler.
Templates: `500.html`
Context: None
"""
t = loader.get_template(template_name) # You need to create a 500.html template.
return http.HttpResponseServerError(t.render(Context({})))
3
Example 12
def server_error(request, template_name='500.html'):
"""
500 error handler.
Templates: `500.html`
Context: None
"""
from django.template import RequestContext, loader
from django.http import HttpResponseServerError
t = loader.get_template(template_name)
return HttpResponseServerError(t.render(RequestContext(request)))
3
Example 13
Project: callisto-core Source File: views.py
@check_owner('edit', 'edit_id')
@ratelimit(group='decrypt', key='user', method=ratelimit.UNSAFE, rate=settings.DECRYPT_THROTTLE_RATE, block=True)
def edit_record_form_view(request, edit_id, wizard, step=None, url_name="edit_report"):
report = Report.objects.get(id=edit_id)
if PageBase.objects.count() > 0:
return wizard.wizard_factory(object_to_edit=report).as_view(url_name=url_name)(request, step=step)
else:
logger.error("no pages in record form")
return HttpResponseServerError()
3
Example 14
def file_upload_view(request):
"""
Check that a file upload can be updated into the POST dictionary without
going pear-shaped.
"""
form_data = request.POST.copy()
form_data.update(request.FILES)
if isinstance(form_data.get('file_field'), UploadedFile) and isinstance(form_data['name'], six.text_type):
# If a file is posted, the dummy client should only post the file name,
# not the full path.
if os.path.dirname(form_data['file_field'].name) != '':
return HttpResponseServerError()
return HttpResponse('')
else:
return HttpResponseServerError()
3
Example 15
Project: rapidpro Source File: support.py
def temba_exception_handler(exc, context):
"""
Custom exception handler which prevents responding to API requests that error with an HTML error page
"""
response = exception_handler(exc, context)
if response or not getattr(settings, 'REST_HANDLE_EXCEPTIONS', False):
return response
else:
# ensure exception still goes to Sentry
logger.error('Exception in API request: %s' % unicode(exc), exc_info=True)
# respond with simple message
return HttpResponseServerError("Server Error. Site administrators have been notified.")
3
Example 16
def file_upload_view(request):
"""
Check that a file upload can be updated into the POST dictionary without
going pear-shaped.
"""
form_data = request.POST.copy()
form_data.update(request.FILES)
if isinstance(form_data.get('file_field'), UploadedFile) and isinstance(form_data['name'], unicode):
# If a file is posted, the dummy client should only post the file name,
# not the full path.
if os.path.dirname(form_data['file_field'].name) != '':
return HttpResponseServerError()
return HttpResponse('')
else:
return HttpResponseServerError()
3
Example 17
Project: memopol2 Source File: views.py
@staff_member_required
def moderation_moderate_positions(request):
if not request.is_ajax():
return HttpResponseServerError()
results = {'success':False}
position = get_object_or_404(Position, pk=int(request.GET[u'pos_id']))
try:
position.moderated = True
position.visible = (request.GET[u'decision'] == "1")
position.save()
results = {'success':True}
except:
pass
return HttpResponse(simplejson.dumps(results), mimetype='application/json')
3
Example 18
def handle_uncaught_exception(self, request, resolver, exc_info):
"""
Propagates ResponseLater up into the higher handler method,
processes everything else
"""
# ResponseLater needs to be bubbled up the stack
if issubclass(exc_info[0], AsgiRequest.ResponseLater):
raise
# There's no WSGI server to catch the exception further up if this fails,
# so translate it into a plain text response.
try:
return super(AsgiHandler, self).handle_uncaught_exception(request, resolver, exc_info)
except:
return HttpResponseServerError(
traceback.format_exc() if settings.DEBUG else "Internal Server Error",
content_type="text/plain",
)
3
Example 19
@requires_csrf_token
def server_error(request, template_name='500.html'):
"""
500 error handler.
Templates: :template:`500.html`
Context: None
"""
try:
template = loader.get_template(template_name)
except TemplateDoesNotExist:
return http.HttpResponseServerError('<h1>Server Error (500)</h1>')
return http.HttpResponseServerError(template.render(Context({})))
3
Example 20
def server_error(request, template_name='500.html'):
"""
500 error handler.
Templates: `500.html`
Context:
request_path
The path of the requested URL (e.g., '/app/pages/bad_page/')
"""
# You need to create a 500.html template.
t = loader.get_template(template_name)
return http.HttpResponseServerError(
t.render(RequestContext(request, {'request_path': request.path})))
3
Example 21
Project: pyas2 Source File: views.py
def client_error(request, template_name='400.html'):
""" the 400 error handler.
Templates: `400.html`
Context: None
str().decode(): bytes->unicode
"""
exc_info = traceback.format_exc(None).decode('utf-8', 'ignore')
pyas2init.logger.error(_(u'Ran into client error: "%(error)s"'), {'error': str(exc_info)})
temp = template.loader.get_template(template_name) # You need to create a 500.html template.
return HttpResponseServerError(temp.render(template.Context({'exc_info': exc_info})))
3
Example 22
Project: graphite Source File: views.py
def renderLocalView(request):
try:
start = time()
reqParams = StringIO(request.raw_post_data)
graphType = reqParams.readline().strip()
optionsPickle = reqParams.read()
reqParams.close()
graphClass = GraphTypes[graphType]
options = pickle.loads(optionsPickle)
image = doImageRender(graphClass, options)
log.rendering("Delegated rendering request took %.6f seconds" % (time() - start))
return buildResponse(image)
except:
log.exception("Exception in graphite.render.views.rawrender")
return HttpResponseServerError()
3
Example 23
Project: djangae Source File: views.py
@csrf_exempt
@require_POST
def internalupload(request):
try:
return HttpResponse(str(request.FILES['file'].blobstore_info.key()))
except Exception:
logging.exception("DJANGAE UPLOAD FAILED: The internal upload handler couldn't retrieve the blob info key.")
return HttpResponseServerError()
3
Example 24
Project: transifex Source File: views.py
def server_error(request, template_name='500.html'):
"""Always include STATIC_URL into the 500 error"""
from django.http import HttpResponseServerError
t = loader.get_template(template_name)
return HttpResponseServerError(t.render(Context({
'STATIC_URL': settings.STATIC_URL})))
3
Example 25
Project: snowy Source File: views.py
def server_error(request, template_name='500.html'):
"""
500 error handler.
Templates: `500.html`
Context:
MEDIA_URL
Path of static media (e.g. "media.example.org")
"""
t = loader.get_template(template_name) # You need to create a 500.html template.
return http.HttpResponseServerError(t.render(Context({
'MEDIA_URL': settings.MEDIA_URL
})))
3
Example 26
def technical_500_response(request, exc_type, exc_value, tb):
"""
Create a technical server error response. The last three arguments are
the values returned from sys.exc_info() and friends.
"""
reporter = ExceptionReporter(request, exc_type, exc_value, tb)
html = reporter.get_traceback_html()
return HttpResponseServerError(html, mimetype='text/html')
3
Example 27
Project: cdr-stats Source File: urls.py
def custom_404_view(request, template_name='404.html'):
"""404 error handler which includes ``request`` in the context.
Templates: `404.html`
Context: None
"""
from django.template import Context, loader
from django.http import HttpResponseServerError
t = loader.get_template('404.html') # Need to create a 404.html template.
return HttpResponseServerError(t.render(Context({
'request': request,
})))
3
Example 28
Project: callisto-core Source File: views.py
def new_record_form_view(request, wizard, step=None, url_name="record_form"):
if PageBase.objects.count() > 0:
return wizard.wizard_factory().as_view(url_name=url_name)(request, step=step)
else:
logger.error("no pages in record form")
return HttpResponseServerError()
3
Example 29
def upload_progress(request):
"""Return JSON object with information about the progress of an upload."""
log.debug('Touch to upload_progress view.')
cache = get_cache('default')
progress_id = ''
if 'X-Progress-ID' in request.GET:
progress_id = request.GET['X-Progress-ID']
elif 'X-Progress-ID' in request.META:
progress_id = request.META['X-Progress-ID']
if progress_id:
cache_key = "%s" % progress_id
data = cache.get(cache_key)
log.debug("responded with cache_key: %s, data: %s" % (cache_key, data))
return HttpResponse(json.dumps(data))
else:
return HttpResponseServerError('Server Error: You must provide X-Progress-ID header' )
3
Example 30
@requires_csrf_token
def server_error(request, template_name='500.html'):
"""
500 error handler.
Templates: :template:`500.html`
Context: None
"""
try:
template = loader.get_template(template_name)
except TemplateDoesNotExist:
return http.HttpResponseServerError('<h1>Server Error (500)</h1>', content_type='text/html')
return http.HttpResponseServerError(template.render(Context({})))
3
Example 31
Project: Adlibre-TMS Source File: views.py
def server_error(request, template_name='500.html'):
"""
500 error handler.
Don't try to render full context. Just minimal.
"""
t = loader.get_template(template_name)
c = Context({
'MEDIA_URL': settings.MEDIA_URL,
'STATIC_URL': settings.STATIC_URL,
})
return http.HttpResponseServerError(t.render(c))
3
Example 32
Project: mezzanine Source File: views.py
@requires_csrf_token
def server_error(request, template_name="errors/500.html"):
"""
Mimics Django's error handler but adds ``STATIC_URL`` to the
context.
"""
context = {"STATIC_URL": settings.STATIC_URL}
t = get_template(template_name)
return HttpResponseServerError(t.render(context, request))
3
Example 33
@xframe_options_exempt
def error404(request):
try:
template = loader.get_template('404.html')
except TemplateDoesNotExist:
return HttpResponseServerError('<h1>Page not found (404)</h1>', content_type='text/html')
return HttpResponseNotFound(template.render(Context({
'STATIC_URL': getattr(settings, 'STATIC_URL', '/static/'),
})))
3
Example 34
def technical_500_response(request, exc_type, exc_value, tb):
"""
Create a technical server error response. The last three arguments are
the values returned from sys.exc_info() and friends.
"""
reporter = ExceptionReporter(request, exc_type, exc_value, tb)
if request.is_ajax():
text = reporter.get_traceback_text()
return HttpResponseServerError(text, content_type='text/plain')
else:
html = reporter.get_traceback_html()
return HttpResponseServerError(html, content_type='text/html')
3
Example 35
def technical_500_response(request, exc_type, exc_value, tb):
"""
Create a technical server error response. The last three arguments are
the values returned from sys.exc_info() and friends.
"""
reporter = ExceptionReporter(request, exc_type, exc_value, tb)
if request.is_ajax(): 如果是 ajax 的请求:
text = reporter.get_traceback_text()
return HttpResponseServerError(text, content_type='text/plain')
3
Example 36
Project: memopol2 Source File: views.py
@staff_member_required
def moderation_get_unmoderated_positions(request):
if not request.is_ajax():
return HttpResponseServerError()
last_id = request.GET[u'last_id']
positions = Position.objects.filter(moderated=False, id__gt=last_id)
return HttpResponse(serializers.serialize('json', positions), mimetype='application/json')
3
Example 37
def get(self, request, *args, **kwargs):
endpoint = self.get_endpoint()
try:
return self.proxy_request(endpoint, request)
except urllib2.URLError, e:
if hasattr(e, 'reason'):
if isinstance(e.reason, socket.timeout):
return HttpResponseServerError("Request to %s timed out" % (endpoint))
return HttpResponseServerError("Failed to retrieve %s. Reason: %s" % (endpoint, e.reason))
elif hasattr(e, 'code'):
return HttpResponseServerError("The server couldn't fulfill the request for %s. Reason: %s" % (endpoint, e.code))
else:
raise
3
Example 38
def handler500(request):
"""
500 error handler which includes ``request`` in the context.
Templates: `500.html`
Context: None
"""
from django.template import Context, loader
from django.http import HttpResponseServerError
t = loader.get_template('500.html')
return HttpResponseServerError(t.render(Context({
'request': request,
})))
3
Example 39
def process_exception(self, request, exception):
if settings.DEBUG:
if request.is_ajax():
import sys
import traceback
(exc_type, exc_info, tb) = sys.exc_info()
response = "%s\n" % exc_type.__name__
response += "%s\n\n" % exc_info
response += "TRACEBACK:\n"
for tb in traceback.format_tb(tb):
response += "%s\n" % tb
return HttpResponseServerError(response)
3
Example 40
Project: tendenci Source File: http.py
def render_to_missing_app(*args, **kwargs):
if not isinstance(args,list):
args = []
args.append('base/missing_app.html')
httpresponse_kwargs = {'content_type': kwargs.pop('mimetype', None)}
value = sys.exc_info()[1]
args.append({'exception_value': value})
response = HttpResponseServerError(loader.render_to_string(*args, **kwargs), **httpresponse_kwargs)
return response
3
Example 41
@requires_csrf_token
def server_error(request, template_name=ERROR_500_TEMPLATE_NAME):
"""
500 error handler.
Templates: :template:`500.html`
Context: None
"""
try:
template = loader.get_template(template_name)
except TemplateDoesNotExist:
if template_name != ERROR_500_TEMPLATE_NAME:
# Reraise if it's a missing custom template.
raise
return http.HttpResponseServerError('<h1>Server Error (500)</h1>', content_type='text/html')
return http.HttpResponseServerError(template.render())
3
Example 42
def server_error(request, template_name='500.html'):
"""
500 error handler.
Templates: `500.html`
Context: None
"""
t = loader.get_template(template_name) # You need to create a 500.html template.
return http.HttpResponseServerError(t.render(Context({})))
3
Example 43
@requires_csrf_token
def server_error(request, template_name='500.html'):
"""
500 error handler.
Templates: :template:`500.html`
Context: None
"""
response = render_in_page(request, template_name)
if response:
return response
try:
template = loader.get_template(template_name)
except TemplateDoesNotExist:
return http.HttpResponseServerError('<h1>Server Error (500)</h1>', content_type='text/html')
return http.HttpResponseServerError(template.render(Context({})))
3
Example 44
Project: pyas2 Source File: views.py
def server_error(request, template_name='500.html'):
""" the 500 error handler.
Templates: `500.html`
Context: None
str().decode(): bytes->unicode
"""
exc_info = traceback.format_exc(None).decode('utf-8', 'ignore')
pyas2init.logger.error(_(u'Ran into server error: "%(error)s"'), {'error': str(exc_info)})
temp = template.loader.get_template(template_name) # You need to create a 500.html template.
return HttpResponseServerError(temp.render(template.Context({'exc_info': exc_info})))
3
Example 45
Project: villagescc Source File: views.py
def server_error(request):
"Renders server error view for unhandled exceptions."
# Don't render this in regular base template, or using RequestContext,
# because we can't count on the database (or anything really) working.
#
# Can't use default server_error view because it doesn't pass help_email.
t = loader.get_template('500.html')
c = Context({'help_email': settings.HELP_EMAIL})
return http.HttpResponseServerError(t.render(c))
3
Example 46
def technical_500_response(request, exc_type, exc_value, tb):
"""
Create a technical server error response. The last three arguments are
the values returned from sys.exc_info() and friends.
"""
html = get_traceback_html(request, exc_type, exc_value, tb)
return HttpResponseServerError(html, mimetype='text/html')
3
Example 47
def process_exception (self, request, exception):
if isinstance(exception, ParameterRequired) or isinstance(exception, ApiException):
return http.HttpResponseServerError(exception.message, mimetype="text/plain")
return None
3
Example 48
Project: autotest Source File: views.py
def handler500(request):
t = loader.get_template('500.html')
trace = traceback.format_exc()
context = Context({
'type': sys.exc_type,
'value': sys.exc_value,
'traceback': cgi.escape(trace)
})
return HttpResponseServerError(t.render(context))
3
Example 49
def process_response(self, request, response):
if not self._should_validate(request, response):
return response
errors = self._validate(response)
if not errors:
return response
context = self._get_context(request, response, errors)
return HttpResponseServerError(self.template.render(context))
3
Example 50
Project: cdr-stats Source File: urls.py
def custom_500_view(request, template_name='500.html'):
"""500 error handler which includes ``request`` in the context.
Templates: `500.html`
Context: None
"""
from django.template import Context, loader
from django.http import HttpResponseServerError
t = loader.get_template('500.html') # Need to create a 500.html template.
return HttpResponseServerError(t.render(Context({
'request': request,
})))