本文整理汇总了Python中django.http.JsonResponse方法的典型用法代码示例。如果您正苦于以下问题:Python http.JsonResponse方法的具体用法?Python http.JsonResponse怎么用?Python http.JsonResponse使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类django.http
的用法示例。
在下文中一共展示了http.JsonResponse方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: contact_detail
# 需要导入模块: from django import http [as 别名]
# 或者: from django.http import JsonResponse [as 别名]
def contact_detail(request, pk):
if request.method == 'POST':
data = (request.POST.get(key) for key in ('name', 'fone', 'email'))
contact = Contact.objects.get(pk=pk)
contact.name, contact.fone, contact.email = data
contact.save()
else:
contact = get_object_or_404(Contact, pk=pk)
response = dict(
name=contact.name,
avatar=contact.avatar(),
email=contact.email,
phone=contact.fone,
url=resolve_url('contact-details', pk=contact.pk)
)
return JsonResponse(response)
示例2: contacts_new
# 需要导入模块: from django import http [as 别名]
# 或者: from django.http import JsonResponse [as 别名]
def contacts_new(request):
if request.method != 'POST':
return HttpResponseNotAllowed(('POST',))
data = {
key: value for key, value in request.POST.items()
if key in ('name', 'fone', 'email')
}
contact = Contact.objects.create(**data)
response = dict(
name=contact.name,
avatar=contact.avatar(),
email=contact.email,
phone=contact.fone
)
return JsonResponse(response, status=201)
示例3: healthcheck_view
# 需要导入模块: from django import http [as 别名]
# 或者: from django.http import JsonResponse [as 别名]
def healthcheck_view(request):
content_type = 'application/health+json'
database_accessible = True
try:
connections['default'].cursor()
except ImproperlyConfigured:
# Database is not configured (DATABASE_URL may not be set)
database_accessible = False
except OperationalError:
# Database is not accessible
database_accessible = False
if database_accessible:
return JsonResponse({ 'status': 'ok' }, content_type=content_type)
return JsonResponse({ 'status': 'fail' }, status=503, content_type=content_type)
示例4: list_subdirectories
# 需要导入模块: from django import http [as 别名]
# 或者: from django.http import JsonResponse [as 别名]
def list_subdirectories(self, request: WSGIRequest) -> HttpResponse:
"""Returns a list of all subdirectories for the given path."""
path = request.GET.get("path")
if path is None:
return HttpResponseBadRequest("path was not supplied.")
basedir, subdirpart = os.path.split(path)
if path == "":
suggestions = ["/"]
elif os.path.isdir(basedir):
suggestions = [
os.path.join(basedir, subdir + "/")
for subdir in next(os.walk(basedir))[1]
if subdir.lower().startswith(subdirpart.lower())
]
suggestions.sort()
else:
suggestions = ["not a valid directory"]
if not suggestions:
suggestions = ["not a valid directory"]
return JsonResponse(suggestions, safe=False)
示例5: create_result_response
# 需要导入模块: from django import http [as 别名]
# 或者: from django.http import JsonResponse [as 别名]
def create_result_response(self, service, result, service_path):
for nested in service_path:
result = result.get(nested, None)
if result is None:
break
if result is None:
raise Http404()
if result in (True, False):
status_code = 200 if result else _get_err_status_code()
return HttpResponse(str(result).lower(), status=status_code)
elif isinstance(result, six.string_types) or isinstance(result, bytes):
return HttpResponse(result)
else:
# Django requires safe=False for non-dict values.
return JsonResponse(result, safe=False)
示例6: index
# 需要导入模块: from django import http [as 别名]
# 或者: from django.http import JsonResponse [as 别名]
def index(request):
if request.path.startswith("/api"):
# If you ended up here, your URL pattern didn't match anything and if your path
# starts with anything "api" you're going to expect JSON.
return JsonResponse({"path": request.path}, status=404)
hostname = request.get_host()
delivery_console_url = DELIVERY_CONSOLE_URLS["prod"]
match = re.search(
r"(\w+)-admin\.normandy\.(?:non)?prod\.cloudops\.mozgcp\.net", hostname, re.I
)
if match:
env = match.group(1)
if env in DELIVERY_CONSOLE_URLS:
delivery_console_url = DELIVERY_CONSOLE_URLS[env]
# Add any path at the end of the delivery console URL, to hopefully
# redirect the user to the right page.
delivery_console_url += request.get_full_path()
return render(request, "base/index.html", {"DELIVERY_CONSOLE_URL": delivery_console_url})
示例7: create_json_response
# 需要导入模块: from django import http [as 别名]
# 或者: from django.http import JsonResponse [as 别名]
def create_json_response(obj, **kwargs):
"""Encodes the give object into json and create a django JsonResponse object with it.
Args:
obj (object): json response object
**kwargs: any addition args to pass to the JsonResponse constructor
Returns:
JsonResponse
"""
dumps_params = {
'sort_keys': True,
'indent': 4,
'default': DjangoJSONEncoderWithSets().default
}
return JsonResponse(
obj, json_dumps_params=dumps_params, encoder=DjangoJSONEncoderWithSets, **kwargs)
示例8: get
# 需要导入模块: from django import http [as 别名]
# 或者: from django.http import JsonResponse [as 别名]
def get(self, request):
page_size = 100
if hasattr(settings, "ACTIVITY_STREAM_PAGE_SIZE"):
page_size = int(setting.ACTIVITY_STREAM_PAGE_SIZE)
totalItems = models.EditLog.objects.all().exclude(resourceclassid=settings.SYSTEM_SETTINGS_RESOURCE_MODEL_ID).count()
uris = {
"root": request.build_absolute_uri(reverse("as_stream_collection")),
"first": request.build_absolute_uri(reverse("as_stream_page", kwargs={"page": 1})),
"last": request.build_absolute_uri(reverse("as_stream_page", kwargs={"page": 1})),
}
if totalItems > page_size:
uris["last"] = request.build_absolute_uri(reverse("as_stream_page", kwargs={"page": int(totalItems / page_size) + 1}))
collection = ActivityStreamCollection(uris, totalItems, base_uri_for_arches=request.build_absolute_uri("/").rsplit("/", 1))
return JsonResponse(collection.to_obj())
示例9: get_roster
# 需要导入模块: from django import http [as 别名]
# 或者: from django.http import JsonResponse [as 别名]
def get_roster(request):
try:
league_tag = request.GET.get('league', None)
season_tag = request.GET.get('season', None)
except ValueError:
return HttpResponse('Bad request', status=400)
try:
seasons = Season.objects.order_by('-start_date', '-id')
if league_tag is not None:
seasons = seasons.filter(league__tag=league_tag)
if season_tag is not None:
seasons = seasons.filter(tag=season_tag)
else:
seasons = seasons.filter(is_active=True)
season = seasons[0]
except IndexError:
return JsonResponse(
{'season_tag': None, 'players': None, 'teams': None, 'error': 'no_matching_rounds'})
if season.league.competitor_type == 'team':
return _team_roster(season)
else:
return _lone_roster(season)
示例10: _lone_roster
# 需要导入模块: from django import http [as 别名]
# 或者: from django.http import JsonResponse [as 别名]
def _lone_roster(season):
season_players = season.seasonplayer_set.select_related('player').nocache()
player_board = {}
current_round = season.round_set.filter(publish_pairings=True, is_completed=False).first()
if current_round is not None:
for p in current_round.loneplayerpairing_set.all():
player_board[p.white] = p.pairing_order
player_board[p.black] = p.pairing_order
return JsonResponse({
'league': season.league.tag,
'season': season.tag,
'players': [{
'username': season_player.player.lichess_username,
'rating': season_player.player.rating_for(season.league),
'board': player_board.get(season_player.player, None)
} for season_player in season_players]
})
示例11: league_document
# 需要导入模块: from django import http [as 别名]
# 或者: from django.http import JsonResponse [as 别名]
def league_document(request):
try:
league_tag = request.GET.get('league', None)
type_ = request.GET.get('type', None)
strip_html = request.GET.get('strip_html', None) == 'true'
except ValueError:
return HttpResponse('Bad request', status=400)
if not league_tag or not type_:
return HttpResponse('Bad request', status=400)
league_doc = LeagueDocument.objects.filter(league__tag=league_tag, type=type_).first()
if league_doc is None:
return JsonResponse({'name': None, 'content': None, 'error': 'not_found'})
document = league_doc.document
content = document.content
if strip_html:
content = strip_tags(content)
return JsonResponse({
'name': document.name,
'content': content
})
示例12: link_slack
# 需要导入模块: from django import http [as 别名]
# 或者: from django.http import JsonResponse [as 别名]
def link_slack(request):
try:
user_id = request.GET.get('user_id', None)
display_name = request.GET.get('display_name', None)
except ValueError:
return HttpResponse('Bad request', status=400)
if not user_id:
return HttpResponse('Bad request', status=400)
token = LoginToken.objects.create(slack_user_id=user_id, username_hint=display_name,
expires=timezone.now() + timedelta(days=30))
league = League.objects.filter(is_default=True).first()
sp = SeasonPlayer.objects.filter(player__lichess_username__iexact=display_name).order_by(
'-season__start_date').first()
if sp:
league = sp.season.league
url = reverse('by_league:login_with_token', args=[league.tag, token.secret_token])
url = request.build_absolute_uri(url)
already_linked = [p.lichess_username for p in Player.objects.filter(slack_user_id=user_id)]
return JsonResponse({'url': url, 'already_linked': already_linked, 'expires': token.expires})
示例13: random_img
# 需要导入模块: from django import http [as 别名]
# 或者: from django.http import JsonResponse [as 别名]
def random_img():
"""
Returns a dictionary of info about a random non-annotated image
"""
imgs = Image.objects.filter(annotation__isnull=True).order_by('?')
if not imgs:
return JsonResponse({
'status': 'error',
'error': 'No images remain to annotate'
})
i = imgs[0]
return {
'status': 'ok',
'image_id': i.id,
'image_url': i.url()
}
示例14: form_valid
# 需要导入模块: from django import http [as 别名]
# 或者: from django.http import JsonResponse [as 别名]
def form_valid(self, form):
form.instance.creator = self.request.user
if 'onidc' not in form.cleaned_data:
form.instance.onidc = self.request.user.onidc
response = super(NewModelView, self).form_valid(form)
log_action(
user_id=self.request.user.pk,
content_type_id=get_content_type_for_model(self.object, True).pk,
object_id=self.object.pk,
action_flag="新增"
)
if self.model_name == 'online':
verify = Thread(target=device_post_save, args=(self.object.pk,))
verify.start()
if self.request.is_ajax():
data = {
'message': "Successfully submitted form data.",
'data': form.cleaned_data
}
return JsonResponse(data)
else:
return response
示例15: post
# 需要导入模块: from django import http [as 别名]
# 或者: from django.http import JsonResponse [as 别名]
def post(self, request, *a, **kw):
data = request.POST.dict()
if data.get('opt', '') == 'grow':
num = int(data.get('num', '0'))
node_name = data.get('node_name', None)
if num and node_name:
ret = appCelery.control.pool_grow(n=num, reply=True, destination=[node_name])
print(ret)
return JsonResponse({'data': ret, 'msg': '%s: %s'% (node_name, ret[0][node_name])})
elif data.get('opt', '') == 'shrink':
num = int(data.get('num', '0'))
node_name = data.get('node_name', None)
if num and node_name:
ret = appCelery.control.pool_shrink(n=num, reply=True, destination=[node_name])
return JsonResponse({'data': ret, 'msg': '%s: %s'% (node_name, ret[0][node_name])})
return JsonResponse({'msg': 'ok'})