def post(self, request):
if "HTTP_PAYPAL_TRANSMISSION_ID" not in request.META:
# Do not even attempt to process/store the event if there is
# no paypal transmission id so we avoid overfilling the db.
return HttpResponseBadRequest()
trigger = WebhookEventTrigger.from_request(request)
if trigger.exception:
# An exception happened, return 500
return HttpResponseServerError()
if not trigger.valid:
# Webhook Event did not validate, return 400
return HttpResponseBadRequest()
return HttpResponse(str(trigger.id))
python类HttpResponseServerError()的实例源码
def search(request):
q = request.GET.get('q')
if not q:
return HttpResponseBadRequest("GET['q'] not set!")
q = q.strip()
try:
document_ids = search_ids(q)
except SearchError as e:
return HttpResponseServerError(str(e))
documents = [get_document(id).parsed for id in document_ids]
data = {
'status': 'ok',
'query': q,
'document_ids': document_ids,
'documents': documents,
'results': len(document_ids),
}
r = JsonResponse(data)
r["Access-Control-Allow-Origin"] = '*'
return r
def task_tester(request):
if request.method == 'POST':
cache.set('marco', 'ping', 100)
sample_task.delay('marco', 'polo', 10)
return http.HttpResponse(
'Now make a GET request to this URL\n',
status=201,
)
else:
if not cache.get('marco'):
return http.HttpResponseBadRequest(
'Make a POST request to this URL first\n'
)
for i in range(3):
value = cache.get('marco')
if value == 'polo':
return http.HttpResponse('It works!\n')
time.sleep(1)
return http.HttpResponseServerError(
'Tried 4 times (4 seconds) and no luck :(\n'
)
def get(self, request):
try:
last_query_time = parse(request.query_params.get('last_query_time'))
except (TypeError, ValueError):
last_query_time = cache.get('isDirty_query_time', (timezone.now() - timedelta(days=7)))
url = settings.POND_URL + '/pond/pond/blocks/new/?since={}&using=default'.format(last_query_time.strftime('%Y-%m-%dT%H:%M:%S'))
now = timezone.now()
try:
response = requests.get(url)
response.raise_for_status()
except Exception as e:
return HttpResponseServerError({'error': repr(e)})
pond_blocks = response.json()
is_dirty = update_request_states_from_pond_blocks(pond_blocks)
cache.set('isDirty_query_time', now, None)
# also factor in if a change in requests (added, updated, cancelled) has occurred since we last checked
last_update_time = max(Request.objects.latest('modified').modified,
UserRequest.objects.latest('modified').modified)
is_dirty |= last_update_time >= last_query_time
return Response({'isDirty': is_dirty})
def apiCall(request):
access_token = request.session.get('accessToken',None)
if access_token is None:
return HttpResponse('Your Bearer token has expired, please initiate C2QB flow again')
realmId = request.session['realmId']
if realmId is None:
return HttpResponse('No realm ID. QBO calls only work if the accounting scope was passed!')
refresh_token = request.session['refreshToken']
company_info_response, status_code = getCompanyInfo(access_token,realmId)
if status_code >= 400:
# if call to QBO doesn't succeed then get a new bearer token from refresh token and try again
bearer = getBearerTokenFromRefreshToken(refresh_token)
updateSession(request,bearer.accessToken,bearer.refreshToken,realmId)
company_info_response, status_code = getCompanyInfo(bearer.accessToken,realmId)
if status_code >= 400:
return HttpResponseServerError()
company_name = company_info_response['CompanyInfo']['CompanyName']
address = company_info_response['CompanyInfo']['CompanyAddr']
return HttpResponse('Company Name: '+company_name+', Company Address: '+address['Line1']+', '+address['City'] + ', ' + ' ' + address['PostalCode'])
def readiness(self, request):
# Connect to each database and do a generic standard SQL query
# that doesn't write any data and doesn't depend on any tables
# being present.
try:
from django.db import connections
for name in connections:
cursor = connections[name].cursor()
cursor.execute("SELECT 1;")
row = cursor.fetchone()
if row is None:
return HttpResponseServerError("db: invalid response")
except Exception as e:
logger.exception(e)
return HttpResponseServerError("db: cannot connect to database.")
return HttpResponse("OK")
def server_error(request, template_name='500.html'):
if request.is_ajax() or request.META.get('HTTP_ACCEPT', 'text/plain') == 'application/json':
return JsonResponse({
'sentry': sentry_id_from_request(request),
'error': {
'title': _('Something went wrong'),
}
}, status=500)
try:
template = loader.get_template(template_name)
except TemplateDoesNotExist:
return HttpResponseServerError('<h1>Server Error (500)</h1>', content_type='text/html')
message = _('Something went wrong on our side... \n Please hold on while we fix it.').replace('\n', '<br>')
return HttpResponseServerError(template.render({
'sentry': sentry_id_from_request(request),
'error': {
'title': _('Something went wrong'),
'message': message,
'sentry': _('Fault code: #'),
}
}))
def server_error(request, template_name='500.html'):
if request.is_ajax() or request.META.get('HTTP_ACCEPT', 'text/plain') == 'application/json':
return JsonResponse({
'sentry': sentry_id_from_request(request),
'error': {
'title': _('Something went wrong'),
}
}, status=500)
try:
template = loader.get_template(template_name)
except TemplateDoesNotExist:
return HttpResponseServerError('<h1>Server Error (500)</h1>', content_type='text/html')
message = _('Something went wrong on our side... \n Please hold on while we fix it.').replace('\n', '<br>')
return HttpResponseServerError(template.render({
'sentry': sentry_id_from_request(request),
'error': {
'title': _('Something went wrong'),
'message': message,
'sentry': _('Fault code: #'),
}
}))
def server_error(request, template_name=ERROR_500_TEMPLATE_NAME):
"""
500 error handler.
:template: :file:`500.html`
"""
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(request=request))
# This can be called when CsrfViewMiddleware.process_view has not run,
# therefore need @requires_csrf_token in case the template needs
# {% csrf_token %}.
def search(request):
q = request.GET.get('q')
if not q:
return HttpResponseBadRequest("GET['q'] not set!")
q = q.strip()
try:
document_ids = search_ids(q)
except SearchError as e:
return HttpResponseServerError(str(e))
documents = [get_document(id).parsed for id in document_ids]
data = {
'status': 'ok',
'query': q,
'document_ids': document_ids,
'documents': documents,
'results': len(document_ids),
}
r = JsonResponse(data)
r["Access-Control-Allow-Origin"] = '*'
return r
def server_error(request, template_name='500.html'):
if request.is_ajax() or request.META.get('HTTP_ACCEPT', 'text/plain') == 'application/json':
return JsonResponse({
'sentry': sentry_id_from_request(request),
'error': {
'title': _('Something went wrong'),
}
}, status=500)
try:
template = loader.get_template(template_name)
except TemplateDoesNotExist:
return HttpResponseServerError('<h1>Server Error (500)</h1>', content_type='text/html')
return HttpResponseServerError(template.render({
'sentry': sentry_id_from_request(request),
'error': {
'title': _('Something went wrong'),
'message': ('%s' %
_('Something went wrong on our side... \n Please hold on while we fix it.')).replace('\n',
'<br>'),
'sentry': _('Fault code: #'),
}
}))
def edit_profile(request):
try:
if request.method == 'GET':
account_form = forms.EditAccountForm(instance=request.user.account)
if request.user.account.account_type == 'Individual':
del account_form.fields['business_name']
elif request.method == 'POST':
account_form = forms.EditAccountForm(request.POST, instance=request.user.account)
if account_form.is_valid():
account_form.save()
return HttpResponseRedirect(reverse('account:view-profile'))
except ObjectDoesNotExist:
logger.error('No account profile found for user {}'.format(request.user))
return HttpResponseServerError()
return render(request, 'account/edit_profile.html', {'account_form': account_form})
def ADValidate(request):
getd = unquote(request.GET.get('token'))
tokenverify = signer.unsign(getd, max_age=int(settings.PYADSELFSERVICE_STOUT))
if request.method == 'POST':
form = renderform(request.POST)
if form.is_valid():
output = do_validate(form.cleaned_data['username'], form.cleaned_data['attr3'], form.cleaned_data['attr4'], form.cleaned_data['attr5'])
if output == 'YGFRafd827343wdhgFDHGFDSFGHVFSNC':
cipher_text = encrypt_val(form.cleaned_data['username'])
data = signer.sign(cipher_text)
return HttpResponseRedirect('/otp?key=' + quote(data))
else:
# value = "You have entered invalid details. Please go back and try again %s" %str(output)
value = str(output)
return HttpResponseServerError(template.render(Context({'exception_value': value,})))
return render(request, 'index.html', {'form': renderform()})
def resetpass(request):
getd = unquote(request.GET.get('key'))
crypted_data = signer.unsign(getd, max_age=int(settings.PYADSELFSERVICE_STOUT))
prim_key = {'username' : getd}
if request.method == 'POST':
form = passreset(request.POST)
if form.is_valid():
base32 = calc_base32(crypted_data)
newpassword = form.cleaned_data['newpassword']
confirmpassword = form.cleaned_data['confirmpassword']
if newpassword and newpassword != confirmpassword:
value = "Your New Password and Confirm Password did not match. Please go back and try again."
return HttpResponseServerError(template.render(Context({'exception_value': value,})))
else:
output = do_reset(crypted_data, form.cleaned_data['confirmpassword'])
if 'success' in output:
value = str(output)
return HttpResponseServerError(loader.get_template('success.html').render(Context({'exception_value': value,})))
else:
value = str(output)
return HttpResponseServerError(template.render(Context({'exception_value': value,})))
else:
value = "Your new password does not comply with password policy. Please go back and try again."
return HttpResponseServerError(template.render(Context({'exception_value': value,})))
return render(request, 'resetpass.html', {'form': passreset(initial=prim_key)})
def dispatch(self, request):
"""
500 error handler.
Templates: `500.html`
Context: None
"""
context = {
'request': request,
}
embed_config = self.get_embed_config(request)
if embed_config:
context['embed_config'] = mark_safe(json.dumps(embed_config))
t = loader.get_template('sentry/500.html')
return HttpResponseServerError(t.render(Context(context)))
def get_image(request, id):
try:
db_image = DBImage.objects.get(id=id)
try:
server = ImageServer.objects.get(id=db_image.server)
if server.server_name != settings.SERVER_NAME:
return HttpResponseBadRequest("Image Not On This Server")
except ImageServer.DoesNotExist:
return HttpResponseServerError("Image Server Does Not Exist!")
image_data = open(db_image.path, 'rb').read()
mime_type = db_image.mime_type
return HttpResponse(image_data, content_type=mime_type)
except DBImage.DoesNotExist:
raise Http404("Image Not Found")
except IOError:
return HttpResponseGone("Image Moved")
def get_image(request, id):
try:
db_image = DBImage.objects.get(id=id)
mime_type = db_image.mime_type
try:
server = ImageServer.objects.get(id=db_image.server)
ip = server.server_ip
port = request.META['SERVER_PORT']
url_ext = reverse('image_server:get_image', args=(str(id) ,))
remote_url = 'http://' + ip + ':' + str(port) + url_ext
image_data = urllib.request.urlopen(remote_url).read()
return HttpResponse(image_data, content_type=mime_type)
except ImageServer.DoesNotExist:
return HttpResponseServerError("Image Server Does Not Exist!")
except DBImage.DoesNotExist:
raise Http404("Image Not Found")
except:
return HttpResponseGone("Image Moved")
def get_thumbnail(request, id):
try:
db_image = DBImage.objects.get(id=id)
mime_type = db_image.mime_type
try:
server = ImageServer.objects.get(id=db_image.server)
ip = server.server_ip
port = request.META['SERVER_PORT']
url_ext = reverse('image_server:get_thumbnail', args=(str(id) ,))
remote_url = 'http://' + ip + ':' + str(port) + url_ext
print(remote_url)
image_data = urllib.request.urlopen(remote_url).read()
return HttpResponse(image_data, content_type=mime_type)
except ImageServer.DoesNotExist:
return HttpResponseServerError("Image Server Does Not Exist!")
except DBImage.DoesNotExist:
raise Http404("Image Not Found")
except Exception as e:
print(e)
return HttpResponseGone("Image Moved")
def apiCall(request):
access_token = request.session.get('accessToken',None)
if access_token is None:
return HttpResponse('Your Bearer token has expired, please initiate C2QB flow again')
realmId = request.session['realmId']
if realmId is None:
return HttpResponse('No realm ID. QBO calls only work if the payment scope was passed!')
refresh_token = request.session['refreshToken']
create_charge_response, status_code = createCharge(access_token)
print(create_charge_response)
print(status_code)
if status_code >= 400:
# if call to QBO doesn't succeed then get a new bearer token from refresh token and try again
bearer = getBearerTokenFromRefreshToken(refresh_token)
updateSession(request,bearer.accessToken,bearer.refreshToken,realmId)
create_charge_response, status_code = createCharge(bearer.accessToken)
if status_code >= 400:
return HttpResponseServerError()
return HttpResponse('Charge create response: '+str(create_charge_response))
def metadata(request):
saml_settings = OneLogin_Saml2_Settings(get_saml_settings(), sp_validation_only=True)
metadata = saml_settings.get_sp_metadata()
errors = saml_settings.validate_metadata(metadata)
if errors:
return HttpResponseServerError(content=', '.join(errors))
return HttpResponse(content=metadata, content_type='text/xml')
def custom_error_page(request):
return HttpResponseServerError(
render_to_string('500.html', request=request))
def dashboard(request):
from .models import RegisteredUser
u = RegisteredUser.objects.get(username=request.user.username)
if request.method == 'POST' or not u.api_key:
api_key = request.POST.get('apikey')
if api_key == 'None': api_key = None
try:
u.api_key = api_key if api_key else generate_key(16)
u.save()
except Exception, e:
return HttpResponseServerError(str(e))
ctx = RequestContext(request)
return render_to_response("dashboard.html", locals(), ctx)
def test_really_bad_decode(self):
self.old_method = remoting.decode
remoting.decode = lambda *args, **kwargs: self._raiseException(
Exception, *args, **kwargs
)
http_request = make_http_request('POST', '')
gw = django.DjangoGateway()
try:
http_response = gw(http_request)
except:
remoting.decode = self.old_method
raise
remoting.decode = self.old_method
self.assertTrue(
isinstance(http_response, http.HttpResponseServerError)
)
self.assertEqual(http_response.status_code, 500)
self.assertEqual(
http_response.content,
'500 Internal Server Error\n\nAn unexpected error occurred.'
)
def submit(request):
"""Endpoint for submitting new crawls.
Expects POST['data'] to be populated with data for a single document group."""
# TODO authentication? Secret keys?
# TODO stop processing the documents when submitted; use processing queues
input_raw = request.POST.get('data')
if not input_raw:
return HttpResponseBadRequest('POST["data"] is not set!')
try:
input = json.loads(input_raw)
except json.JSONDecodeError:
return HttpResponseBadRequest('POST["data"] is not valid json')
input_hash = hash.dict_sha1(input)
submitted, created = models.SubmittedData.objects.update_or_create(
sha1=input_hash,
data=input
)
try:
doc, new = process(submitted)
index_data(doc)
except ProcessingInputError as e:
print(e)
return HttpResponseServerError('error: ' + str(e))
response = {
'status': 'ok',
'new': new,
}
return JsonResponse(response)
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())
def handle_exception(request, exception, template_name):
# XXX: remove this? exceptions are already displayed in debug mode
tb = traceback.format_exc()
print >> sys.stderr, tb
if settings.DEBUG:
return None
try:
log_exception(request, exception, tb)
msg = force_unicode(exception)
if request.is_ajax():
return JsonResponseServerError({'msg': msg})
ctx = {
'exception': msg,
}
if hasattr(exception, 'filename'):
msg_args = {
'filename': exception.filename,
'errormsg': exception.strerror,
}
msg = _('Error accessing %(filename)s, Filesystem '
'sent error: %(errormsg)s', msg_args)
ctx['fserror'] = msg
return HttpResponseServerError(
render_to_string(template_name, context=ctx, request=request)
)
except:
# Let's not confuse things by throwing an exception here
pass
def connected(request):
access_token = request.session.get('accessToken',None)
if access_token is None:
return HttpResponse('Your Bearer token has expired, please initiate Sign In With Intuit flow again')
refresh_token = request.session.get('refreshToken',None)
realmId = request.session['realmId']
if realmId is None:
user_profile_response, status_code = getUserProfile(access_token)
if status_code >= 400:
# if call to User Profile Service doesn't succeed then get a new bearer token from refresh token and try again
bearer = getBearerTokenFromRefreshToken(refresh_token)
user_profile_response, status_code = getUserProfile(bearer.accessToken)
updateSession(request,bearer.accessToken,bearer.refreshToken,request.session.get('realmId',None),name=user_profile_response.get('givenName',None))
if status_code >= 400:
return HttpResponseServerError()
c = {
'first_name': user_profile_response.get('givenName',' '),
}
else:
if request.session.get('name') is None:
name = ''
else:
name = request.session.get('name')
c = {
'first_name': name,
}
return render(request, 'connected.html', context=c)
def volunteer_email_preview(request):
form = PreviewVolunteerMailForm(request.POST or None)
if not form.is_valid():
return HttpResponseServerError()
volunteer = get_object_or_404(Volunteer, site=request.conference.site, pk=form.cleaned_data['volunteer'])
preview = volunteer_email_render_preview(volunteer, form.cleaned_data['subject'], form.cleaned_data['body'])
return HttpResponse(preview)
def talk_email_preview(request):
form = PreviewTalkMailForm(request.POST or None)
if not form.is_valid():
return HttpResponseServerError()
speaker = get_object_or_404(Participant, site=request.conference.site, pk=form.cleaned_data['speaker'])
talk = get_object_or_404(Talk, site=request.conference.site, pk=form.cleaned_data['talk'])
preview = talk_email_render_preview(talk, speaker, form.cleaned_data['subject'], form.cleaned_data['body'])
return HttpResponse(preview)
def speaker_email_preview(request):
form = PreviewSpeakerMailForm(request.POST or None)
if not form.is_valid():
return HttpResponseServerError()
speaker = get_object_or_404(Participant, site=request.conference.site, pk=form.cleaned_data['speaker'])
preview = speaker_email_render_preview(speaker, form.cleaned_data['subject'], form.cleaned_data['body'])
return HttpResponse(preview)