How to use is_json_request method in localstack

Best Python code snippet using localstack_python

views.py

Source:views.py Github

copy

Full Screen

...11 EMAIL_NOTIFICATION_SUBJECT)12from newsletters.forms import NewsletterForm, get_newsletters_with_subs13from newsletters.jsonresponse import JSONResponse14from newsletters.signals import subscription, unsubscription15def is_json_request(request):16 """17 Provide True/False for if the request wants the result in json18 19 with format=json in the request20 """21 return ('format' in request.REQUEST and 22 request.REQUEST['format'].lower() == 'json')23 24def sync_subscriptions(sub_form):25 """26 Do all the work of (un)subscribing newsletters for an account27 """28 old_subs = Subscription.objects.filter(email=sub_form.cleaned_data['email'])29 old_subs_nl = [item.newsletter for item in old_subs]30 new_subs = Newsletter.objects.filter(name__in=sub_form.get_subscriptions())31 32 unsubs = [sub for sub in old_subs if sub.newsletter not in new_subs]33 unsub_nl = [sub.newsletter for sub in unsubs]34 subs = [nl for nl in new_subs if nl not in old_subs_nl]35 36 for item in unsubs:37 unsubscription.send(38 sender=item.newsletter, 39 email=sub_form.cleaned_data['email'],40 newsletter=item.newsletter)41 item.delete()42 for item in subs:43 sub = Subscription.objects.create(44 email=sub_form.cleaned_data['email'],45 newsletter=item,46 confirmed=AUTO_CONFIRM,47 )48 subscription.send(49 sender=item,50 email=sub_form.cleaned_data['email'],51 newsletter=item,52 )53 send_notification(unsub_nl, subs, sub_form.cleaned_data['email'])54 return unsub_nl, subs55def send_notification(unsub_newsletters, sub_newsletters, email):56 """57 Send an email notifying the ``email`` recipient they have been58 subscribed to the newsletters in sub_newsletters, and/or unsubscribed59 from the newsletters in unsub_newsletters.60 """61 current_site = Site.objects.get_current()62 63 t = loader.get_template('newsletters/notification_email.txt')64 c = Context({65 'unsubscriptions': unsub_newsletters, 66 'subscriptions': sub_newsletters,67 'site': current_site,68 'email': email,69 })70 send_mail(EMAIL_NOTIFICATION_SUBJECT, t.render(c), FROM_EMAIL, [email], 71 fail_silently=False)72def detail(request, newsletter_slug):73 """74 Provide a rendered HTML version of the newsletter75 """76 newsletter = get_object_or_404(Newsletter, slug=newsletter_slug)77 78 templates = [79 'newsletters/%s.html' % newsletter_slug,80 'newsletters/%s.html' % newsletter.category.slug,81 DEFAULT_TEMPLATE82 ]83 if newsletter.template:84 templates.insert(newsletter.template, 0)85 86 return render_to_response(templates, {87 'newsletter': newsletter,88 'category': newsletter.category,89 'ads': Advertisement.objects.current_set(newsletter)90 }, RequestContext(request))91def manage(request, email=None):92 """93 Provide a way to manage all subscriptions for a user94 """95 message = []96 if request.method == 'GET' and email:97 if is_json_request(request):98 return JSONResponse({99 'newsletters': get_newsletters_with_subs(email)})100 form = NewsletterForm(initial={'email': email})101 elif request.method == 'GET' and email is None:102 return HttpResponseRedirect(103 reverse('newsletters_list'))104 elif request.method == 'POST':105 form = NewsletterForm(request.POST)106 if form.is_valid():107 unsubs, subs = sync_subscriptions(form)108 if unsubs:109 message.append(110 "Successfully unsubscribed from %s" % 111 ', '.join(map(unicode, unsubs)))112 if subs:113 message.append(114 "Successfully subscribed to %s" % 115 ', '.join(map(unicode,subs)))116 if is_json_request(request):117 return JSONResponse({118 'newsletters': get_newsletters_with_subs(email),119 'messages': message})120 return render_to_response('newsletters/manage.html', {121 'newsletters': Newsletter.objects.all(),122 'form': form,123 'messages': message124 }, RequestContext(request))125def newsletter_list(request):126 """127 Return a list of newsletters128 """129 if request.method == 'GET' and 'u' in request.GET:130 return HttpResponseRedirect(131 reverse('newsletters_manage', kwargs={'email': request.GET['u']}))132 if is_json_request(request):133 if 'category__id' in request.REQUEST:134 cat = request.REQUEST['category__id']135 newsletters = Newsletter.objects.filter(category__id=cat).values()136 elif 'category__slug' in request.REQUEST:137 cat = request.REQUEST['category__slug']138 newsletters = Newsletter.objects.filter(category__slug=cat).values()139 else:140 newsletters = Newsletter.objects.values()141 return JSONResponse(142 {'newsletters': newsletters, 143 'signup_url': reverse('newsletters_bulk_subscribe')})144 return render_to_response('newsletters/list.html', {145 'newsletters': Newsletter.objects.all(),146 'form': NewsletterForm(),147 }, RequestContext(request))148def is_subscribed(request, newsletter_slug):149 """150 Is the user subscribed to the newsletter. Requires GET params of151 email152 """153 if 'email' in request.REQUEST and 'id' in request.REQUEST:154 try:155 Subscription.objects.get(156 email=request.REQUEST['email'], 157 newsletter__slug=newsletter_slug)158 return JSONResponse({'is_subscribed': True})159 except Subscription.ObjectDoesNotExist:160 return JSONResponse({'is_subscribed': False})161def bulk_subscribe(request):162 """163 Subscribe to many newsletters at once. Only for use with JSON and POST164 """165 from django.core.validators import validate_email166 from django.core.exceptions import ValidationError167 try:168 if request.method != 'POST':169 return JSONResponse({170 'success': False,171 'message': 'Form must be submitted using POST.'})172 173 values = dict(request.POST.items())174 175 if 'csrfmiddlewaretoken' in values:176 del values['csrfmiddlewaretoken']177 178 try:179 validate_email(values['email'])180 email = values['email']181 newsletters = [key for key in values.keys() if key != 'email']182 if not newsletters:183 return JSONResponse({184 'success': False, 185 'message': "Please select at least one newsletter."})186 nletters = Newsletter.objects.filter(slug__in=newsletters)187 for newsletter in nletters:188 try:189 sub = Subscription.objects.get(email=email,190 newsletter=newsletter)191 except Subscription.DoesNotExist:192 # The user wasn't subscribed, so we'll create it.193 sub = Subscription.objects.create(email=email,194 newsletter=newsletter)195 subscription.send(196 sender=newsletter,197 email=email,198 newsletter=newsletter,199 )200 send_notification([], nletters, email)201 202 return JSONResponse({203 'success': True,204 'message': 'You signed up for ' + ", ".join([x.name for x in nletters])})205 except ValidationError, e:206 return JSONResponse({207 'success': False,208 'message': " ".join(e.messages)})209 except Exception, e:210 return JSONResponse({211 'success': False,212 'message': "We're sorry but a strange error occurred. (%s)" % str(e)})213def subscribe(request, newsletter_slug):214 """215 Subscribe a user to the newsletter216 217 Requires a POST with an email218 """219 newsletter = get_object_or_404(Newsletter, slug=newsletter_slug)220 if request.method != 'POST':221 if is_json_request:222 return JSONResponse({223 'success': False, 224 'message': 'Only POST methods are allowed.'})225 return HttpResponseNotAllowed(['POST',])226 if 'email' not in request.POST:227 if is_json_request:228 return JSONResponse({229 'success': False, 230 'message': 'No email field was included.'})231 raise Http404("email not included in POST")232 try:233 sub = Subscription.objects.get(email=request.POST['email'],234 newsletter=newsletter)235 except Subscription.DoesNotExist:236 # The user wasn't subscribed, so we'll create it.237 sub = Subscription.objects.create(email=request.POST['email'],238 newsletter=newsletter)239 send_notification([], [newsletter], request.POST['email'])240 subscription.send(sender=newsletter, email=request.POST['email'],241 newsletter=newsletter)242 if is_json_request(request):243 return JSONResponse({'success': True, 'message': ''})244 return render_to_response('newsletters/subscribe.html', {245 'newsletter': newsletter246 }, RequestContext(request))247def unsubscribe(request, newsletter_slug):248 """249 Unsubscribe a user from the newsletter.250 251 Requires a POST with an email252 """253 newsletter = get_object_or_404(Newsletter, slug=newsletter_slug)254 if request.method != 'POST':255 if is_json_request:256 return JSONResponse({257 'success': False, 258 'message': 'Only POST methods are allowed.'})259 return HttpResponseNotAllowed(['POST',])260 if 'email' not in request.POST:261 if is_json_request:262 return JSONResponse({263 'success': False, 264 'message': 'No email field was included.'})265 raise Http404("email not included in POST")266 try:267 sub = Subscription.objects.get(email=request.POST['email'],268 newsletter=newsletter)269 sub.delete()270 unsubscription.send(sender=newsletter, email=request.POST['email'],271 newsletter=newsletter)272 send_notification([newsletter], [], request.POST['email'])273 except Subscription.DoesNotExist:274 pass # The user wasn't subscribed, so just fail gracefully.275 276 if is_json_request(request):277 return JSONResponse({'success': True, 'message': ''})278 return render_to_response('newsletters/unsubscribe.html', {279 'newsletter': newsletter...

Full Screen

Full Screen

xform_submission_api.py

Source:xform_submission_api.py Github

copy

Full Screen

1import re2import StringIO3import sys4from django.conf import settings5from django.contrib.auth.models import User6from django.shortcuts import get_object_or_4047from django.utils.translation import ugettext as _8from rest_framework import permissions9from rest_framework import status10from rest_framework import viewsets11from rest_framework import mixins12from rest_framework.authentication import (13 BasicAuthentication,14 TokenAuthentication)15from rest_framework.response import Response16from rest_framework.renderers import BrowsableAPIRenderer, JSONRenderer17from onadata.apps.logger.models import Instance18from onadata.apps.main.models.user_profile import UserProfile19from onadata.libs import filters20from onadata.libs.authentication import DigestAuthentication21from onadata.libs.mixins.openrosa_headers_mixin import OpenRosaHeadersMixin22from onadata.libs.renderers.renderers import TemplateXMLRenderer23from onadata.libs.serializers.data_serializer import SubmissionSerializer24from onadata.libs.utils.logger_tools import dict2xform, safe_create_instance25from rest_framework import authentication26import logging27from django.contrib.auth import authenticate28# 10,000,000 bytes29DEFAULT_CONTENT_LENGTH = getattr(settings, 'DEFAULT_CONTENT_LENGTH', 10000000)30xml_error_re = re.compile('>(.*)<')31def is_json(request):32 #print "Submission fail #######################################-1"33 return 'application/json' in request.content_type.lower()34def dict_lists2strings(d):35 """Convert lists in a dict to joined strings.36 :param d: The dict to convert.37 :returns: The converted dict."""38 ##print "Submission fail #######################################-2"39 for k, v in d.items():40 if isinstance(v, list) and all([isinstance(e, basestring) for e in v]):41 d[k] = ' '.join(v)42 elif isinstance(v, dict):43 d[k] = dict_lists2strings(v)44 return d45def create_instance_from_xml(username, request):46 #print "Submission fail #######################################-3"47 xml_file_list = request.FILES.pop('xml_submission_file', [])48 xml_file = xml_file_list[0] if len(xml_file_list) else None49 media_files = request.FILES.values()50 #print "Submission fail #######################################-3-1"51 return safe_create_instance(username, xml_file, media_files, None, request)52def create_instance_from_json(username, request):53 #print "Submission fail #######################################-4"54 request.accepted_renderer = JSONRenderer()55 request.accepted_media_type = JSONRenderer.media_type56 dict_form = request.DATA57 submission = dict_form.get('submission')58 if submission is None:59 # return an error60 return [_(u"No submission key provided."), None]61 # convert lists in submission dict to joined strings62 submission_joined = dict_lists2strings(submission)63 xml_string = dict2xform(submission_joined, dict_form.get('id'))64 xml_file = StringIO.StringIO(xml_string)65 return safe_create_instance(username, xml_file, [], None, request)66class XFormSubmissionApi(OpenRosaHeadersMixin,67 mixins.CreateModelMixin, viewsets.GenericViewSet):68 """69Implements OpenRosa Api [FormSubmissionAPI](\70 https://bitbucket.org/javarosa/javarosa/wiki/FormSubmissionAPI)71## Submit an XML XForm submission72<pre class="prettyprint">73<b>POST</b> /api/v1/submissions</pre>74> Example75>76> curl -X POST -F xml_submission_file=@/path/to/submission.xml \77https://example.com/api/v1/submissions78## Submit an JSON XForm submission79<pre class="prettyprint">80<b>POST</b> /api/v1/submissions</pre>81> Example82>83> curl -X POST -d '{"id": "[form ID]", "submission": [the JSON]} \84http://localhost:8000/api/v1/submissions -u user:pass -H "Content-Type: \85application/json"86Here is some example JSON, it would replace `[the JSON]` above:87> {88> "transport": {89> "available_transportation_types_to_referral_facility": \90["ambulance", "bicycle"],91> "loop_over_transport_types_frequency": {92> "ambulance": {93> "frequency_to_referral_facility": "daily"94> },95> "bicycle": {96> "frequency_to_referral_facility": "weekly"97> },98> "boat_canoe": null,99> "bus": null,100> "donkey_mule_cart": null,101> "keke_pepe": null,102> "lorry": null,103> "motorbike": null,104> "taxi": null,105> "other": null106> }107> }108> "meta": {109> "instanceID": "uuid:f3d8dc65-91a6-4d0f-9e97-802128083390"110> }111> }112"""113 #print "Submission fail #######################################-5"114 authentication_classes = (DigestAuthentication,115 BasicAuthentication,116 TokenAuthentication)117 filter_backends = (filters.AnonDjangoObjectPermissionFilter,)118 model = Instance119 permission_classes = (permissions.AllowAny,)120 renderer_classes = (TemplateXMLRenderer,121 JSONRenderer,122 BrowsableAPIRenderer)123 serializer_class = SubmissionSerializer124 template_name = 'submission.xml'125 def old_create(self, request, *args, **kwargs):126 logging.basicConfig(filename='ex.log', level=logging.DEBUG)127 username = self.kwargs.get('username')128 password = request.GET.get('password', '')129 logging.info('mpower:password = ' + password)130 mobileuser = authenticate(username=username, password=password) 131 if self.request.user.is_anonymous():132 if username is None or mobileuser is None:133 # raises a permission denied exception, forces authentication134 self.permission_denied(self.request)135 else:136 user = get_object_or_404(User, username=username.lower())137 profile, created = UserProfile.objects.get_or_create(user=user)138 if profile.require_auth:139 # raises a permission denied exception,140 # forces authentication141 self.permission_denied(self.request)142 elif mobileuser is None:143 self.permission_denied(self.request)144 elif not username:145 # get the username from the user if not set146 username = (request.user and request.user.username)147 if request.method.upper() == 'HEAD':148 return Response(status=status.HTTP_204_NO_CONTENT,149 headers=self.get_openrosa_headers(request),150 template_name=self.template_name)151 is_json_request = is_json(request)152 error, instance = (create_instance_from_json if is_json_request else153 create_instance_from_xml)(username, request)154 if error or not instance:155 return self.error_response(error, is_json_request, request)156 context = self.get_serializer_context()157 serializer = SubmissionSerializer(instance, context=context)158 return Response(serializer.data,159 headers=self.get_openrosa_headers(request),160 status=status.HTTP_201_CREATED,161 template_name=self.template_name)162 def create(self, request, *args, **kwargs):163 print "Submission #######################################-6"164 username = self.kwargs.get('username')165 password = self.request.GET.get('password')166 #print username167 if self.request.user.is_anonymous():168 #print "Submission fail #######################################-6-1"169 if username is None and password is None:170 # raises a permission denied exception, forces authentication171 self.permission_denied(self.request)172 else:173 #print "Submission fail #######################################-6-2"174 user = get_object_or_404(User, username=username.lower())175 profile, created = UserProfile.objects.get_or_create(user=user)176 if profile.require_auth:177 # raises a permission denied exception,178 # forces authentication179 self.permission_denied(self.request)180 elif not username:181 # get the username from the user if not set182 username = (request.user and request.user.username)183 if request.method.upper() == 'HEAD':184 #print "Submission fail #######################################-7"185 return Response(status=status.HTTP_204_NO_CONTENT,186 headers=self.get_openrosa_headers(request),187 template_name=self.template_name)188 is_json_request = is_json(request)189 error, instance = (create_instance_from_json if is_json_request else190 create_instance_from_xml)(username, request)191 #print "Submission fail #######################################-8"192 if error or not instance:193 return self.error_response(error, is_json_request, request)194 print(user.has_perm('report_xform', instance.xform))195 if not user.has_perm('report_xform', instance.xform):196 return Response('User has not submission permission for this form',197 headers=self.get_openrosa_headers(request),198 status=status.HTTP_204_NO_CONTENT,199 template_name=self.template_name)200 context = self.get_serializer_context()201 serializer = SubmissionSerializer(instance, context=context)202 #print "Submission fail #######################################-9"203 return Response(serializer.data,204 headers=self.get_openrosa_headers(request),205 status=status.HTTP_201_CREATED,206 template_name=self.template_name)207 def error_response(self, error, is_json_request, request):208 if not error:209 error_msg = _(u"Unable to create submission.")210 status_code = status.HTTP_400_BAD_REQUEST211 elif isinstance(error, basestring):212 error_msg = error213 status_code = status.HTTP_400_BAD_REQUEST214 elif not is_json_request:215 return error216 else:217 error_msg = xml_error_re.search(error.content).groups()[0]218 status_code = error.status_code219 return Response({'error': error_msg},220 headers=self.get_openrosa_headers(request),...

Full Screen

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run localstack automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful