def quote_list(request, limit=263):
"""
API endpoint that lists all quotes or a specific number of
quotes
limit -- the number of quotes to be returned
"""
quotes = Quote.objects.all()[:int(limit)]
serializer = QuoteSerializer(quotes, many=True)
response = HttpResponse(JSONRenderer().render(serializer.data),
content_type='application/json')
response["Access-Control-Allow-Origin"] = "*"
return response
python类JSONRenderer()的实例源码
def random_quote_detail(request):
"""
API endpoint that generates a random quote
"""
quote = Quote.objects.get(id=randrange(1, 264))
serializer = QuoteSerializer(quote)
response = HttpResponse(JSONRenderer().render(serializer.data),
content_type='application/json')
response["Access-Control-Allow-Origin"] = "*"
return response
def render(self, data, media_type=None, renderer_context=None):
# Return data, squeezing time dimension as this only works with 3D data
if not data["time_request"]:
self.render_style = 'binary'
data["data"].data = np.squeeze(data["data"].data, axis=(0,))
else:
# This appears to contain time data. Error out
renderer_context["response"].status_code = 400
renderer_context["accepted_media_type"] = 'application/json'
self.media_type = 'application/json'
self.format = 'json'
err_msg = {"status": 400, "message": "The cutout service JPEG interface does not support 4D cutouts",
"code": 2005}
jr = JSONRenderer()
return jr.render(err_msg, 'application/json', renderer_context)
if renderer_context['view'].bit_depth != 8:
# This renderer only works on uint8 data
renderer_context["response"].status_code = 400
renderer_context["accepted_media_type"] = 'application/json'
self.media_type = 'application/json'
self.format = 'json'
err_msg = {"status": 400, "message": "The cutout service JPEG interface only supports uint8 image data",
"code": 2001}
jr = JSONRenderer()
return jr.render(err_msg, 'application/json', renderer_context)
# Reshape matrix
d_shape = data["data"].data.shape
data["data"].data = np.reshape(data["data"].data, (d_shape[0] * d_shape[1], d_shape[2]), order="C")
# Save to Image
jpeg_image = Image.fromarray(data["data"].data)
img_file = io.BytesIO()
jpeg_image.save(img_file, "JPEG", quality=85)
# Send file
img_file.seek(0)
return img_file.read()
def __init__(self, data, **kwargs):
content = JSONRenderer().render(
data, renderer_context={'indent': 2, 'ensure_asci': False})
kwargs['content_type'] = 'application/json'
super(JSONResponse, self).__init__(content, **kwargs)
def react_polls(context, question):
question_serializer = serializers.QuestionSerializer(
question,
context={'request': context['request']}
)
return format_html(
'<div data-mb-widget="polls" data-question="{question}"></div>',
question=JSONRenderer().render(question_serializer.data)
)
def react_poll_form(poll, reload_on_success=False):
serializer = serializers.PollSerializer(poll)
data_poll = JSONRenderer().render(serializer.data)
reload_on_success = json.dumps(reload_on_success)
return format_html(
(
'<div data-mb-widget="poll-management" data-module="{module}" '
' data-poll="{poll}" data-reloadOnSuccess="{reload_on_success}">'
'</div>'
),
module=poll.module.pk,
poll=data_poll,
reload_on_success=reload_on_success,
)
def post(self, request, *args, **kwargs):
"""
Take the user object from the request and call the 'save' method on it to persist to the DB. If this succeeds
then we can report a success.
:param request:
:param args:
:param kwargs:
:return: Serialised JSON Response Object to indicate the resource has been created
"""
stdlogger.debug("Hitting HTTP POST account view")
# Try and persist the user to the DB. Remember this could fail a data integrity check if some other system has
# saved this user before we run this line of code!
try:
request.user.save()
except (IntegrityError, InternalError, DataError, DatabaseError):
# The chances of this happening are slim to none! And this line of code should never happen. So we really
# need to tell the other system we are not capable of creating the resource.
raise DatabaseFailureException
context = {'account': request.user.email, 'created': 'success'}
json_context = JSONRenderer().render(context)
return Response(data=json_context, status=status.HTTP_201_CREATED,)
def put(self, request):
"""
Take the user object from the request and updates user info if it exists in the DB. If the email (which is
unique) is to be updated this will be in a new attribute within the PUT message called new_username.
If this succeeds then we can report a success.
:param request:
:param args:
:param kwargs:
:return: Serialised JSON Response Object to indicate the resource has been created
"""
stdlogger.debug("Hitting HTTP PUT account view")
# Try and persist the user to the DB. Remember this could fail a data integrity check if some other system has
# saved this user before we run this line of code!
try:
# Check to see if this PUT is changing the user ID. If it is, then keep the same user object with Primary
# Key and change the email to the new one.
if request.new_username:
stdlogger.info("Admin is updating a user ID to a new value")
request.user.email = request.new_username
request.user.save()
except (IntegrityError, InternalError, DataError, DatabaseError):
# The chances of this happening are slim to none! And this line of code should never happen. So we really
# need to tell the other system we are not capable of creating the resource.
raise DatabaseFailureException
context = {'account': request.user.email, 'updated': 'success'}
json_context = JSONRenderer().render(context)
return Response(data=json_context, status=status.HTTP_201_CREATED,)
def __init__(self, data, **kwargs):
content = JSONRenderer().render(data)
kwargs['content_type'] = 'application/json'
super(JSONResponse, self).__init__(content, **kwargs)
def course_table(request):
if not http_basic_auth(request):
return HttpResponse('Unauthorized.', status=401)
if request.method == 'GET':
auth_number = request.user.authority.auth
if has_auth(auth_number, AuthorityName.Student):
courses = models.Course.objects.filter(as_student_set=request.user.as_student)
elif has_auth(auth_number, AuthorityName.Teacher):
courses = models.Course.objects.filter(teacher=request.user.as_teacher)
else:
return HttpResponse('Permission Denied.', status=403)
params = request.GET # ????
if 'year' in params:
courses = courses.filter(year=params['year'])
if 'term' in params:
courses = courses.filter(term=params['term'])
ser = serializer.CourseTableSerializer(courses, many=True)
course_table_json = json.loads(JSONRenderer().render(ser.data))
# ??????????????????(?????????????/????)
(now_year, now_month, now_day, now_hour, now_minute, now_second, _, _, _) = time.localtime(time.time())
date_now = utils.date_to_str(now_year, now_month, now_day)
schedules = models.SystemSchedule.objects.filter(begin__lte=date_now).filter(end__gte=date_now)
if schedules:
schedule = schedules.first()
items = models.SystemScheduleItem.objects.filter(system_schedule=schedule).order_by('no')
schedule_data = {
'count': items.count(),
'items': [
{
'begin': utils.time_to_str(item.begin.hour, item.begin.minute, item.begin.second),
'end': utils.time_to_str(item.end.hour, item.end.minute, item.end.second),
'no': item.no,
} for item in items
]
}
else:
schedule_data = {
'count': 0,
'items': []
}
# ??????json???
data = {
'count': schedule_data['count'],
'schedule_items': schedule_data['items'],
'course_items': course_table_json,
}
return HttpResponse(json.dumps(data), status=200)
else:
return HttpResponse('Method Not Allowed', status=405)