Here are the examples of the python api django.http.response.JsonResponse taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
146 Examples
3
Source : views.py
with GNU Affero General Public License v3.0
from botshot
with GNU Affero General Public License v3.0
from botshot
def post(self, request, *args, **kwargs):
from botshot.core.interfaces.google import GoogleActionsInterface
body = json.loads(self.request.body.decode('utf-8'))
logging.info(body)
resp = GoogleActionsInterface.accept_request(body)
return JsonResponse(resp)
class SkypeView(generic.View):
3
Source : views.py
with GNU Affero General Public License v3.0
from botshot
with GNU Affero General Public License v3.0
from botshot
def run_test(request, name):
benchmark = request.GET.get('benchmark', False)
return JsonResponse(data=_run_test_module(name, benchmark=benchmark))
@login_required(login_url=reverse_lazy('login'))
3
Source : views.py
with MIT License
from buserbrasil
with MIT License
from buserbrasil
def login(request):
username = request.POST['username']
password = request.POST['password']
user = auth.authenticate(username=username, password=password)
user_dict = None
if user is not None:
if user.is_active:
auth.login(request, user)
log_svc.log_login(request.user)
user_dict = _user2dict(user)
return JsonResponse(user_dict, safe=False)
def logout(request):
3
Source : views.py
with MIT License
from buserbrasil
with MIT License
from buserbrasil
def whoami(request):
i_am = {
'user': _user2dict(request.user),
'authenticated': True,
} if request.user.is_authenticated else {'authenticated': False}
return JsonResponse(i_am)
def settings(request):
3
Source : views.py
with MIT License
from buserbrasil
with MIT License
from buserbrasil
def settings(request):
le_settings = globalsettings_svc.list_settings()
return JsonResponse(le_settings)
@ajax_login_required
3
Source : views.py
with MIT License
from buserbrasil
with MIT License
from buserbrasil
def add_todo(request):
todo = todo_svc.add_todo(request.POST['new_task'])
return JsonResponse(todo)
@ajax_login_required
3
Source : views.py
with MIT License
from buserbrasil
with MIT License
from buserbrasil
def list_todos(request):
todos = todo_svc.list_todos()
return JsonResponse({'todos': todos})
def _user2dict(user):
3
Source : views.py
with MIT License
from buserbrasil
with MIT License
from buserbrasil
def list_tweets(request):
return JsonResponse(
[
tweet.to_dict() for tweet in Tweet.objects.order_by('-id').all()
],
safe=False
)
3
Source : views.py
with MIT License
from DivineITLimited
with MIT License
from DivineITLimited
def get(self, request, chooser_type, *args, **kwargs):
chooser_cls = get_chooser_for(chooser_type)
q = request.GET.get('q')
page = request.GET.get('page', 1)
if chooser_cls:
chooser = chooser_cls()
result = chooser.paginate(request, q, page=page)
return JsonResponse(result, status=200)
else:
return JsonResponse({'message': 'Invalid chooser'}, status=400)
3
Source : views.py
with MIT License
from duplxey
with MIT License
from duplxey
def stripe_config(request):
if request.method == 'GET':
stripe_config = {'publicKey': settings.STRIPE_PUBLISHABLE_KEY}
return JsonResponse(stripe_config, safe=False)
@csrf_exempt
3
Source : api.py
with BSD 3-Clause "New" or "Revised" License
from foxmask
with BSD 3-Clause "New" or "Revised" License
from foxmask
def get_folders(request):
"""
all the folders
:param request
:return: json
"""
res = joplin.get_folders()
json_data = sorted(res.json(), key=lambda k: k['title'])
data = nb_notes_by_folder(json_data)
logger.debug(data)
return JsonResponse(data, safe=False)
def get_tags(request):
3
Source : views.py
with Apache License 2.0
from google
with Apache License 2.0
from google
def app_settings(request):
app_settings = AppSettings.load()
return JsonResponse({'appSettings': {
'gaServiceAccount': app_settings.ga_service_account,
'authorizedEmails': app_settings.authorized_emails,
}})
@csrf_exempt
3
Source : views.py
with Apache License 2.0
from google
with Apache License 2.0
from google
def cache(request):
cache = ApiCache.load()
return JsonResponse({'cache': {
'gaAccounts': cache.ga_accounts
}})
@csrf_exempt
3
Source : views.py
with Apache License 2.0
from google
with Apache License 2.0
from google
def checks_list(request):
"""Endpoint that returns a list of all checks available
"""
result = Check.get_checks_metadata()
return JsonResponse({'checksMetadata': result}, encoder=DqmApiEncoder)
def create_suite(request):
3
Source : views.py
with Apache License 2.0
from google
with Apache License 2.0
from google
def create_suite(request):
payload = json.loads(request.body)
suite = Suite.objects.create(name=payload['name'])
GaParams.objects.create(suite=suite, scope_json='')
# If user asked for a suite template, we also create all the checks related to
# this template, linked to the suite.
if payload['templateId']:
checks = [c for c in Check.get_checks_metadata()
if c['theme'] == payload['templateId']]
for c in checks:
Check.objects.create(suite=suite, name=c['name'])
return JsonResponse({'id': suite.id}, encoder=DqmApiEncoder)
def get_suite(request, suite_id):
3
Source : views.py
with Apache License 2.0
from google
with Apache License 2.0
from google
def delete_suite(request, suite_id):
Suite.objects.filter(pk=suite_id).delete()
return JsonResponse({'status': 'OK'}, encoder=DqmApiEncoder)
def suites_list(request):
3
Source : views.py
with Apache License 2.0
from google
with Apache License 2.0
from google
def update_check(request, suite_id, check_id):
payload = json.loads(request.body)
payload['params_json'] = json.dumps(payload.pop('paramValues'))
try:
del payload['resultFields']
except:
pass
try:
del payload['checkMetadata']
except:
pass
Check.objects.filter(id=check_id).update(**payload)
return JsonResponse({'check': None}, encoder=DqmApiEncoder)
def delete_check(request, suite_id, check_id):
3
Source : views.py
with Apache License 2.0
from google
with Apache License 2.0
from google
def delete_check(request, suite_id, check_id):
Check.objects.filter(pk=check_id).delete()
return JsonResponse({'status': 'OK'}, encoder=DqmApiEncoder)
@csrf_exempt
3
Source : views.py
with Apache License 2.0
from google
with Apache License 2.0
from google
def stats_suites_executions(request):
return JsonResponse({
'result': SuiteExecution.get_stats()}, encoder=DqmApiEncoder)
def stats_checks_executions(request):
3
Source : views.py
with MIT License
from hvitis
with MIT License
from hvitis
def show_user_ip(request):
client_ip, is_routable = get_client_ip(request)
res = {
'client_ip': client_ip,
'is_routable': is_routable
}
return JsonResponse(res)
# Serve Vue Application
index_view = never_cache(TemplateView.as_view(template_name='index.html'))
3
Source : views_custom.py
with Apache License 2.0
from IBM-Blockchain-Identity
with Apache License 2.0
from IBM-Blockchain-Identity
def get(self, request):
"""
Returns record count information.
"""
response = {
'counts': self.get_recordCounts()
}
return JsonResponse(response)
3
Source : app.py
with GNU Lesser General Public License v3.0
from longguikeji
with GNU Lesser General Public License v3.0
from longguikeji
def update(self, request, *args, **kwargs):
data = request.data.get('data', '')
if data:
redirect_uris = data.get('redirect_uris', '')
if redirect_uris:
if redirect_uris.startswith('http') or redirect_uris.startswith(
'https'
):
pass
else:
return JsonResponse(
data={
'error': Code.URI_FROMAT_ERROR.value,
'message': _('redirect_uris format error'),
}
)
return super().update(request, *args, **kwargs)
@extend_schema(
3
Source : app.py
with GNU Lesser General Public License v3.0
from longguikeji
with GNU Lesser General Public License v3.0
from longguikeji
def create(self, request, *args, **kwargs):
data = request.data.get('data', '')
if data:
redirect_uris = data.get('redirect_uris', '')
if redirect_uris:
if redirect_uris.startswith('http') or redirect_uris.startswith(
'https'
):
pass
else:
return JsonResponse(
data={
'error': Code.URI_FROMAT_ERROR.value,
'message': _('redirect_uris format error'),
}
)
return super().create(request, *args, **kwargs)
@extend_schema(
3
Source : arkstore.py
with GNU Lesser General Public License v3.0
from longguikeji
with GNU Lesser General Public License v3.0
from longguikeji
def post(self, request, tenant_uuid, *args, **kwargs):
extension_uuid = request.data['extension_uuid']
token = request.user.token
tenant = Tenant.objects.get(uuid=tenant_uuid)
access_token = get_arkstore_access_token(tenant, token)
resp = purcharse_arkstore_extension(access_token, extension_uuid)
return JsonResponse(resp)
@extend_schema(roles=['global admin'], tags=['arkstore-extension'])
3
Source : arkstore.py
with GNU Lesser General Public License v3.0
from longguikeji
with GNU Lesser General Public License v3.0
from longguikeji
def get(self, request, tenant_uuid, *args, **kwargs):
extension_uuid = kwargs['pk']
token = request.user.token
tenant = Tenant.objects.get(uuid=tenant_uuid)
access_token = get_arkstore_access_token(tenant, token)
result = download_arkstore_extension(access_token, extension_uuid)
return JsonResponse(result)
def get_saas_token(tenant, token):
3
Source : authcode.py
with GNU Lesser General Public License v3.0
from longguikeji
with GNU Lesser General Public License v3.0
from longguikeji
def post(self, request):
key = request.data.get('file_name')
check_code = request.data.get('code')
code = self.runtime.cache_provider.get(key)
if code and str(code).upper() == str(check_code).upper():
return JsonResponse(data={'is_succeed': 0})
else:
return JsonResponse(data={'is_succeed': 1})
class AuthPageInfo(generics.RetrieveAPIView):
3
Source : config.py
with GNU Lesser General Public License v3.0
from longguikeji
with GNU Lesser General Public License v3.0
from longguikeji
def put(self, request, *args, **kwargs):
provider = self.get_provider()
if not provider:
return JsonResponse(
data={
'error': Code.PROVIDER_NOT_EXISTS_ERROR.value,
'message': _('configure privacy_notice extension first'),
},
status=status.HTTP_400_BAD_REQUEST,
)
instance = provider.load_privacy(request)
serializer = PrivacyNoticeSerializer(instance, data=request.data)
serializer.is_valid()
serializer.save()
return Response(serializer.data)
def get(self, request, *args, **kwargs):
3
Source : extension.py
with GNU Lesser General Public License v3.0
from longguikeji
with GNU Lesser General Public License v3.0
from longguikeji
def update(self, request, *args, **kwargs):
data = request.data.get('data', {})
data_path = data.get('data_path', '')
if data_path:
if '../' in data_path or './' in data_path:
return JsonResponse(data={
'error': Code.DATA_PATH_ERROR.value,
'message': _('data_path format error'),
})
return super().update(request, *args, **kwargs)
@extend_schema(
3
Source : marketplace.py
with GNU Lesser General Public License v3.0
from longguikeji
with GNU Lesser General Public License v3.0
from longguikeji
def get(self, request):
extensions = find_available_extensions()
tags = []
for extension in extensions:
tags.append(extension.tags)
tags = list(set(tags))
return JsonResponse({"data": tags})
3
Source : tenant.py
with GNU Lesser General Public License v3.0
from longguikeji
with GNU Lesser General Public License v3.0
from longguikeji
def update(self, request, *args, **kwargs):
slug = request.data.get('slug')
tenant_exists = (
Tenant.active_objects.exclude(uuid=kwargs.get('pk'))
.filter(slug=slug)
.exists()
)
if tenant_exists:
return JsonResponse(
data={
'error': Code.SLUG_EXISTS_ERROR.value,
'message': _('slug already exists'),
}
)
return super().update(request, *args, **kwargs)
@extend_schema(
3
Source : tenant.py
with GNU Lesser General Public License v3.0
from longguikeji
with GNU Lesser General Public License v3.0
from longguikeji
def create(self, request):
slug = request.data.get('slug')
tenant_exists = Tenant.active_objects.filter(slug=slug).exists()
if tenant_exists:
return JsonResponse(
data={
'error': Code.SLUG_EXISTS_ERROR.value,
'message': _('slug already exists'),
}
)
return super().create(request)
def get_queryset(self):
3
Source : SubscribedAppListView.py
with GNU Lesser General Public License v3.0
from longguikeji
with GNU Lesser General Public License v3.0
from longguikeji
def get(self, request, tenant_uuid, user_id):
tenant = Tenant.active_objects.get(uuid=tenant_uuid)
user = User.objects.get(uuid=user_id)
print(user)
data = []
if hasattr(user, "app_subscribed_records"):
apps = [record.app for record in user.app_subscribed_records.filter(app__tenant=tenant).all() if (
not record.app.is_del and record.app.is_active)]
data = AppBaseInfoSerializer(apps, many=True).data
return JsonResponse(
data={
"status": 200,
"data": data
}
)
3
Source : views.py
with GNU Lesser General Public License v3.0
from longguikeji
with GNU Lesser General Public License v3.0
from longguikeji
def get(self, request):
data = []
data.append({'value': 'username', 'label': '用户名'})
data.append({'value': 'email', 'label': '邮箱账号'})
tenant = None
tenant_uuid = request.query_params.get('tenant', None)
if tenant_uuid:
tenant = Tenant.active_objects.filter(uuid=tenant_uuid).first()
custom_fields = CustomField.valid_objects.filter(subject='user', tenant=tenant)
for field in custom_fields:
data.append({'value': field.name, 'label': field.name})
return JsonResponse(data=data, safe=False)
@extend_schema(
3
Source : views.py
with GNU Lesser General Public License v3.0
from longguikeji
with GNU Lesser General Public License v3.0
from longguikeji
def get(self, request):
data = []
data.append({'value': 'username', 'label': '用户名'})
tenant = None
tenant_uuid = request.query_params.get('tenant', None)
if tenant_uuid:
tenant = Tenant.active_objects.filter(uuid=tenant_uuid).first()
custom_fields = CustomField.valid_objects.filter(subject='user', tenant=tenant)
for field in custom_fields:
data.append({'value': field.name, 'label': field.name})
return JsonResponse(data=data, safe=False)
3
Source : ArticleController.py
with MIT License
from lysh
with MIT License
from lysh
def list(req):
pageIndex=req.POST["pageIndex"] if req.POST["pageIndex"] else 0
pageNum=req.POST["pageNum"] if req.POST["pageNum"] else 20
articles=list(map(lambda x:x.__data,Article.objects[pageIndex*pageNum:(pageIndex+1)*pageNum]))
words=WordBag.objects(eid__in=list(map(lambda x:x["eid"],articles)))
for i in range(len(articles)):
articles[i]["keyWord"]=words[i].wordList
return JsonResponse({
"success":True,
"data":articles
})
@require_http_methods(["GET"])
3
Source : ArticleController.py
with MIT License
from lysh
with MIT License
from lysh
def detail(req,articleId):
article=Article.objects(eid=articleId).first()
article=article.__data
article["keyWord"]=WordBag.objects(eid=articleId).first().wordList
return JsonResponse({
"success":True,
"data":article
})
3
Source : UserController.py
with MIT License
from lysh
with MIT License
from lysh
def recommend(req):
recs=list(map(lambda x:getattr(x, "articleId"),Recommendation.objects(userId=req.POST["uid"])))
articles=Article.objects(eid__in=recs).exclude("content")
articles=list(map(lambda x:x.__data,articles))
count=0
for word in WordBag.objects(eid__in=recs):
articles[count]["keyWord"]=word.wordList
count+=1
return JsonResponse({
"success":True,
"data":articles
})
@require_http_methods(["GET"])
3
Source : UserController.py
with MIT License
from lysh
with MIT License
from lysh
def history(req):
aids=Record.getArticleForUser(req.POST["uid"])
articles=list(lambda x:x.__data,Article.objects(eid__in=aids).exclude("content"))
count=0
for word in WordBag.objects(eid__in=aids):
articles[count]["keyWord"]=word.wordList
count+=1
return JsonResponse({
"success":True,
"data":articles
})
@require_http_methods(["POST"])
3
Source : api.py
with Apache License 2.0
from MaltoseEditor
with Apache License 2.0
from MaltoseEditor
def restful(message="", error=None, data=None, status=200, **kwargs):
"""
:param message: 交付与前端, 给用户看的信息
:param error: 用于调试时阅读的错误信息
:param data: 被请求的数据
:param status: HTTP状态码, 详见 https://developer.mozilla.org/zh-CN/docs/Web/HTTP/Status
:param kwargs: JsonResponse的其他参数
:return:
"""
return JsonResponse({"message": message, "error": error, "data": data}, status=status, **kwargs)
class LoginRequiredView(View):
3
Source : auth.py
with BSD 3-Clause "New" or "Revised" License
from myide
with BSD 3-Clause "New" or "Revised" License
from myide
def process_request(self, request):
data = request.META.get('HTTP_AUTHORIZATION')
if not data:
return JsonResponse(data={
"msg": 'Not Provide Authorization',
'status': status.HTTP_401_UNAUTHORIZED,
'data': {'detail': 'Not Provide Authorization'}},
status=status.HTTP_401_UNAUTHORIZED)
auth = RequestAuth(data)
if not auth.query():
return JsonResponse(data=auth.response, status=status.HTTP_403_FORBIDDEN)
request.user = HandleUser.get_or_create_user(auth.user)
class RequestAuth:
3
Source : views.py
with MIT License
from pmeta
with MIT License
from pmeta
def post(self, request, pk):
"""
点赞, 异步任务来做
"""
obj = m.Blog.objects.filter(pk=pk).first()
response = JsonResponse({'code': 0, 'msg': obj.like + 1})
# 7天内不允许重复点赞
response.set_cookie(pk, 'true', expires=60 * 60 * 24 * 7)
# 异步更新数据库
update_art_like.delay(pk)
return response
def get_art_like_status(self, pk):
3
Source : views.py
with MIT License
from pmeta
with MIT License
from pmeta
def get(self, request, *args, **kwargs):
html = render_to_string('db/linkform.html', {}, request)
response = JsonResponse({'code': 0, 'text': html})
return response
def post(self, request, *args, **kwargs):
3
Source : views.py
with MIT License
from pylixm
with MIT License
from pylixm
def post(self, request):
book_id = request.POST.get('id')
ret = {
'status': 0
}
if book_id:
book = Book.objects.get(id=book_id)
book.view_count += 1
book.save()
ret.update({
'status': 1
})
return JsonResponse(ret)
@csrf_exempt
3
Source : base.py
with GNU Lesser General Public License v3.0
from raveberry
with GNU Lesser General Public License v3.0
from raveberry
def upgrade_available(_request: WSGIRequest) -> HttpResponse:
"""Checks whether newer Raveberry version is available."""
latest_version = system.fetch_latest_version()
current_version = conf.VERSION
if latest_version and latest_version != current_version:
return JsonResponse(True, safe=False)
return JsonResponse(False, safe=False)
def update_state() -> None:
3
Source : suggestions.py
with GNU Lesser General Public License v3.0
from raveberry
with GNU Lesser General Public License v3.0
from raveberry
def offline_suggestions(request: WSGIRequest) -> JsonResponse:
"""Returns offline suggestions for a given query."""
query = request.GET["term"]
suggest_playlist = request.GET["playlist"] == "true"
if storage.get("new_music_only"):
return JsonResponse([], safe=False)
if suggest_playlist:
results = _offline_playlist_suggestions(query)
else:
results = _offline_song_suggestions(query)
return JsonResponse(results, safe=False)
3
Source : base.py
with MIT License
from ustclug
with MIT License
from ustclug
def post(self, request):
identity = json.loads(request.body).get('identity')
try:
self.validate_identity(identity)
except ValidationError as e:
return JsonResponse({'error': e.message}, status=400)
try:
code = Code.generate(self.provider, identity, self.duration)
except Code.TooMany:
return JsonResponse({'error': '校验码发送过于频繁'}, status=429)
# noinspection PyBroadException
try:
self.send(identity, code)
except Exception:
return JsonResponse({'error': '校验码发送失败'}, status=400)
return JsonResponse({})
def validate_identity(self, identity):
3
Source : views.py
with MIT License
from valentinvarbanov
with MIT License
from valentinvarbanov
def trending_json(request):
trending = Currency.objects.order_by('-price')[0]
serializer = CurrencySerializer(trending)
return JsonResponse(serializer.data)
def lucky_one(request):
3
Source : views.py
with MIT License
from valentinvarbanov
with MIT License
from valentinvarbanov
def trending_json(request):
trending = Currency.objects.order_by('-price')[0]
serializer = CurrencySerializer(trending)
return JsonResponse(serializer.data)
def feeling_lucky(request):
3
Source : views.py
with MIT License
from valentinvarbanov
with MIT License
from valentinvarbanov
def feeling_lucky_api(request):
lucky_choice = Currency.objects.all().annotate(cap=F('price') * F('supply')).order_by('cap-')[0]
serializer = CurrencySerializer(lucky_choice)
return JsonResponse(serializer.data)
3
Source : views.py
with MIT License
from valentinvarbanov
with MIT License
from valentinvarbanov
def trending_json(request):
trending = Currency.objects.order_by('-price')[0]
serializer = CurrencySerializer(trending)
return JsonResponse(serializer.data)
def addCoin(request):
See More Examples