How to use request method in Best

Best JavaScript code snippet using best

product_request_views.py

Source:product_request_views.py Github

copy

Full Screen

1from django.contrib import messages2from django.http import HttpResponse, HttpResponseForbidden, HttpResponseBadRequest, HttpResponseNotFound3from django.shortcuts import redirect4from django.shortcuts import render5from django.urls import reverse6from django.views.decorators.csrf import csrf_exempt7from app import settings8from app.models import Operators, Notifications, NotificationsTimeline9from app.models import Product_Requests, Product_Request_Items10from app.utils import Utils11from backend.forms.product_request_forms import ProductRequestSearchIndexForm, ProductRequestCreateForm, \12 ProductRequestUpdateForm13from backend.forms.product_request_item_forms import ProductRequestItemSearchIndexForm14from backend.tables.product_request_item_tables import ProductRequestItemsTable15from backend.tables.product_request_tables import ProductRequestsTable16# noinspection PyUnusedLocal17def index(request):18 template_url = 'product-requests/index.html'19 operator = Operators.login_required(request)20 if operator is None:21 Operators.set_redirect_field_name(request, request.path)22 return redirect(reverse("operators_signin"))23 else:24 auth_permissions = Operators.get_auth_permissions(operator)25 if settings.ACCESS_PERMISSION_ORDER_VIEW in auth_permissions.values():26 search_form = ProductRequestSearchIndexForm(request.POST or None)27 objects = None28 objects = Product_Requests.get_filtered_product_requests(operator)29 if request.method == 'POST' and search_form.is_valid():30 display_search = True31 table = ProductRequestsTable(objects)32 else:33 display_search = False34 table = ProductRequestsTable(objects)35 table.set_auth_permissions(auth_permissions)36 return render(37 request, template_url,38 {39 'section': settings.BACKEND_SECTION_STOCK_ALL_REQUESTS,40 'title': Product_Requests.TITLE,41 'name': Product_Requests.NAME,42 'operator': operator,43 'auth_permissions': auth_permissions,44 'table': table,45 'search_form': search_form,46 'display_search': display_search,47 'index_url': reverse("product_requests_index"),48 'select_multiple_url': reverse("product_requests_select_multiple"),49 }50 )51 else:52 return HttpResponseForbidden('Forbidden', content_type='text/plain')53@csrf_exempt54# noinspection PyUnusedLocal55def select_single(request):56 if request.is_ajax():57 operator = Operators.login_required(request)58 if operator is None:59 # Operators.set_redirect_field_name(request, request.path)60 # return redirect(reverse("operators_signin"))61 return HttpResponse('signin', content_type='text/plain')62 else:63 auth_permissions = Operators.get_auth_permissions(operator)64 action = request.POST['action']65 id = request.POST['id']66 if action != '' and id is not None:67 if action == 'order-request':68 if settings.ACCESS_PERMISSION_ORDER_UPDATE in auth_permissions.values():69 try:70 model = Product_Requests.objects.get(product_request_id=id)71 if model.product_request_created_id == str(operator.operator_id):72 model.product_request_requested_at = Utils.get_current_datetime_utc()73 model.product_request_requested_id = operator.operator_id74 model.product_request_requested_by = operator.operator_name75 model.product_request_requested_department = operator.operator_department76 model.product_request_requested_role = operator.operator_role77 model.product_request_status = Product_Requests.STATUS_REQUESTED78 model.save()79 # sending notification to COP80 operators = Operators.objects.filter(operator_role=Operators.ROLE_STOCK_ADMIN)81 for item in operators:82 Notifications.add_notification(83 Notifications.TYPE_OPERATOR,84 operator.operator_id,85 Notifications.TYPE_OPERATOR,86 item.operator_id,87 Notifications.TYPE_PRODUCT_REQUEST,88 model.product_request_id,89 "A stock request has been sent for approval.",90 "/backend/product-requests/view/" + str(91 model.product_request_id) + "/"92 )93 messages.success(request, 'Stock requested successfully.')94 else:95 messages.success(request, 'Forbidden')96 except(TypeError, ValueError, OverflowError, Product_Requests.DoesNotExist):97 return HttpResponseBadRequest('Bad Request', content_type='text/plain')98 else:99 return HttpResponseForbidden('Forbidden', content_type='text/plain')100 if action == 'order-review':101 if settings.ACCESS_PERMISSION_ORDER_UPDATE in auth_permissions.values():102 try:103 model = Product_Requests.objects.get(product_request_id=id)104 model.product_request_reviewed_at = Utils.get_current_datetime_utc()105 model.product_request_reviewed_id = operator.operator_id106 model.product_request_reviewed_by = operator.operator_name107 model.product_request_reviewed_department = operator.operator_department108 model.product_request_reviewed_role = operator.operator_role109 model.product_request_status = Product_Requests.STATUS_REVIEWED110 model.save()111 # sending notification112 operators = Operators.objects.filter(operator_id=model.product_request_requested_id)113 for item in operators:114 Notifications.add_notification(115 Notifications.TYPE_OPERATOR,116 operator.operator_id,117 Notifications.TYPE_OPERATOR,118 item.operator_id,119 Notifications.TYPE_PRODUCT_REQUEST,120 model.product_request_id,121 "Your stock request has been reviewed.",122 "/backend/product-requests/view/" + str(123 model.product_request_id) + "/"124 )125 messages.success(request, 'Stock reviewed successfully.')126 except(TypeError, ValueError, OverflowError, Product_Requests.DoesNotExist):127 return HttpResponseBadRequest('Bad Request', content_type='text/plain')128 else:129 return HttpResponseForbidden('Forbidden', content_type='text/plain')130 if action == 'order-approve':131 if settings.ACCESS_PERMISSION_ORDER_UPDATE in auth_permissions.values():132 try:133 model = Product_Requests.objects.get(product_request_id=id)134 model.product_request_approved_updated_at = Utils.get_current_datetime_utc()135 model.product_request_approved_updated_id = operator.operator_id136 model.product_request_approved_updated_by = operator.operator_name137 model.product_request_approved_updated_department = operator.operator_department138 model.product_request_approved_updated_role = operator.operator_role139 model.product_request_status = Product_Requests.STATUS_APPROVED140 model.save()141 # sending notification142 operators = Operators.objects.filter(operator_id=model.product_request_requested_id)143 for item in operators:144 Notifications.add_notification(145 Notifications.TYPE_OPERATOR,146 operator.operator_id,147 Notifications.TYPE_OPERATOR,148 item.operator_id,149 Notifications.TYPE_PRODUCT_REQUEST,150 model.product_request_id,151 "Your stock request has been approved.",152 "/backend/product-requests/view/" + str(153 model.product_request_id) + "/"154 )155 messages.success(request, 'Stock approved successfully.')156 except(TypeError, ValueError, OverflowError, Product_Requests.DoesNotExist):157 return HttpResponseBadRequest('Bad Request', content_type='text/plain')158 else:159 return HttpResponseForbidden('Forbidden', content_type='text/plain')160 if action == 'order-reject':161 if settings.ACCESS_PERMISSION_ORDER_UPDATE in auth_permissions.values():162 try:163 model = Product_Requests.objects.get(product_request_id=id)164 model.product_request_approved_updated_at = Utils.get_current_datetime_utc()165 model.product_request_approved_updated_id = operator.operator_id166 model.product_request_approved_updated_by = operator.operator_name167 model.product_request_approved_updated_department = operator.operator_department168 model.product_request_approved_updated_role = operator.operator_role169 model.product_request_status = Product_Requests.STATUS_REVIEWED170 model.save()171 # sending notification172 operators = Operators.objects.filter(operator_id=model.product_request_requested_id)173 for item in operators:174 Notifications.add_notification(175 Notifications.TYPE_OPERATOR,176 operator.operator_id,177 Notifications.TYPE_OPERATOR,178 item.operator_id,179 Notifications.TYPE_PRODUCT_REQUEST,180 model.product_request_id,181 "Your stock request has been rejected.",182 "/backend/product-requests/view/" + str(183 model.product_request_id) + "/"184 )185 messages.success(request, 'Stock rejected successfully.')186 except(TypeError, ValueError, OverflowError, Product_Requests.DoesNotExist):187 return HttpResponseBadRequest('Bad Request', content_type='text/plain')188 else:189 return HttpResponseForbidden('Forbidden', content_type='text/plain')190 return HttpResponse('success', content_type='text/plain')191 else:192 return HttpResponseBadRequest('Bad Request', content_type='text/plain')193 else:194 return HttpResponseForbidden('Forbidden', content_type='text/plain')195@csrf_exempt196# noinspection PyUnusedLocal197def select_multiple(request):198 if request.is_ajax():199 operator = Operators.login_required(request)200 if operator is None:201 # Operators.set_redirect_field_name(request, request.path)202 # return redirect(reverse("operators_signin"))203 return HttpResponse('signin', content_type='text/plain')204 else:205 auth_permissions = Operators.get_auth_permissions(operator)206 action = request.POST['action']207 ids = request.POST['ids']208 try:209 ids = ids.split(",")210 except(TypeError, ValueError, OverflowError):211 ids = None212 if action != '' and ids is not None:213 return HttpResponse('success', content_type='text/plain')214 else:215 return HttpResponseBadRequest('Bad Request', content_type='text/plain')216 else:217 return HttpResponseForbidden('Forbidden', content_type='text/plain')218# noinspection PyUnusedLocal, PyShadowingBuiltins219def create(request):220 template_url = 'product-requests/create.html'221 operator = Operators.login_required(request)222 if operator is None:223 Operators.set_redirect_field_name(request, request.path)224 return redirect(reverse("operators_signin"))225 else:226 auth_permissions = Operators.get_auth_permissions(operator)227 if settings.ACCESS_PERMISSION_ORDER_CREATE in auth_permissions.values():228 if request.method == 'POST':229 form = ProductRequestCreateForm(request.POST)230 # noinspection PyArgumentList231 if form.is_valid():232 model = Product_Requests()233 model.product_request_code = Product_Requests.generate_random_number('product_request_code', 8)234 model.product_request_project = form.cleaned_data['product_request_project']235 model.product_request_details = form.cleaned_data['product_request_details']236 model.product_request_no_of_items = 0237 model.product_request_created_at = Utils.get_current_datetime_utc()238 model.product_request_created_id = operator.operator_id239 model.product_request_created_by = operator.operator_name240 model.product_request_created_department = operator.operator_department241 model.product_request_created_role = operator.operator_role242 model.product_request_updated_at = Utils.get_current_datetime_utc()243 model.product_request_updated_id = operator.operator_id244 model.product_request_updated_by = operator.operator_name245 model.product_request_updated_department = operator.operator_department246 model.product_request_updated_role = operator.operator_role247 model.product_request_requested_at = settings.APP_CONSTANT_DEFAULT_DATETIME_VALUE248 model.product_request_requested_id = ''249 model.product_request_requested_by = ''250 model.product_request_requested_department = ''251 model.product_request_requested_role = ''252 model.product_request_reviewed_at = settings.APP_CONSTANT_DEFAULT_DATETIME_VALUE253 model.product_request_reviewed_id = ''254 model.product_request_reviewed_by = ''255 model.product_request_reviewed_department = ''256 model.product_request_reviewed_role = ''257 model.product_request_approved_updated_at = settings.APP_CONSTANT_DEFAULT_DATETIME_VALUE258 model.product_request_approved_updated_id = ''259 model.product_request_approved_updated_by = ''260 model.product_request_approved_updated_department = ''261 model.product_request_approved_updated_role = ''262 model.product_request_closed_at = settings.APP_CONSTANT_DEFAULT_DATETIME_VALUE263 model.product_request_closed_id = ''264 model.product_request_closed_by = ''265 model.product_request_closed_department = ''266 model.product_request_closed_role = ''267 model.product_request_cancelled_at = settings.APP_CONSTANT_DEFAULT_DATETIME_VALUE268 model.product_request_cancelled_id = ''269 model.product_request_cancelled_by = ''270 model.product_request_cancelled_department = ''271 model.product_request_cancelled_role = ''272 model.product_request_status = Product_Requests.STATUS_PENDING273 # noinspection PyCallByClass,PyTypeChecker274 model.save('Created')275 messages.info(request,276 'Your stock request has been created successfully.')277 return redirect(reverse("product_requests_view", args=[model.product_request_id]))278 else:279 return render(280 request, template_url,281 {282 'section': settings.BACKEND_SECTION_STOCK_ALL_REQUESTS,283 'title': Product_Requests.TITLE,284 'name': Product_Requests.NAME,285 'operator': operator,286 'auth_permissions': auth_permissions,287 'form': form,288 'index_url': reverse("product_requests_index"),289 }290 )291 else:292 form = ProductRequestCreateForm()293 return render(294 request, template_url,295 {296 'section': settings.BACKEND_SECTION_STOCK_ALL_REQUESTS,297 'title': Product_Requests.TITLE,298 'name': Product_Requests.NAME,299 'operator': operator,300 'auth_permissions': auth_permissions,301 'form': form,302 'index_url': reverse("product_requests_index"),303 }304 )305 else:306 return HttpResponseForbidden('Forbidden', content_type='text/plain')307# noinspection PyUnusedLocal, PyShadowingBuiltins308def update(request, pk):309 template_url = 'product-requests/update.html'310 operator = Operators.login_required(request)311 if operator is None:312 Operators.set_redirect_field_name(request, request.path)313 return redirect(reverse("operators_signin"))314 else:315 auth_permissions = Operators.get_auth_permissions(operator)316 if settings.ACCESS_PERMISSION_ORDER_UPDATE in auth_permissions.values():317 try:318 model = Product_Requests.objects.get(product_request_id=pk)319 if request.method == 'POST':320 form = ProductRequestUpdateForm(request.POST)321 # noinspection PyArgumentList322 if form.is_valid():323 model.product_request_project = form.cleaned_data['product_request_project']324 model.product_request_details = form.cleaned_data['product_request_details']325 model.product_request_updated_at = Utils.get_current_datetime_utc()326 model.product_request_updated_id = operator.operator_id327 model.product_request_updated_by = operator.operator_name328 model.product_request_updated_department = operator.operator_department329 model.product_request_updated_role = operator.operator_role330 model.save()331 messages.success(request, 'Updated successfully.')332 return redirect(reverse("product_requests_view", args=[model.product_request_id]))333 else:334 return render(335 request, template_url,336 {337 'section': settings.BACKEND_SECTION_STOCK_ALL_REQUESTS,338 'title': Product_Requests.TITLE,339 'name': Product_Requests.NAME,340 'operator': operator,341 'auth_permissions': auth_permissions,342 'form': form,343 'model': model,344 'index_url': reverse("product_requests_index"),345 }346 )347 else:348 form = ProductRequestUpdateForm(349 initial={350 'product_request_project': model.product_request_project,351 'product_request_details': model.product_request_details,352 }353 )354 return render(355 request, template_url,356 {357 'section': settings.BACKEND_SECTION_STOCK_ALL_REQUESTS,358 'title': Product_Requests.TITLE,359 'name': Product_Requests.NAME,360 'operator': operator,361 'auth_permissions': auth_permissions,362 'form': form,363 'model': model,364 'index_url': reverse("product_requests_index"),365 }366 )367 except(TypeError, ValueError, OverflowError, Product_Requests.DoesNotExist):368 return HttpResponseNotFound('Not Found', content_type='text/plain')369 else:370 return HttpResponseForbidden('Forbidden', content_type='text/plain')371# noinspection PyUnusedLocal, PyShadowingBuiltins372def view(request, pk):373 template_url = 'product-requests/view.html'374 operator = Operators.login_required(request)375 if operator is None:376 Operators.set_redirect_field_name(request, request.path)377 return redirect(reverse("operators_signin"))378 else:379 auth_permissions = Operators.get_auth_permissions(operator)380 if settings.ACCESS_PERMISSION_ORDER_VIEW in auth_permissions.values():381 try:382 model = Product_Requests.objects.get(product_request_id=pk)383 product_request_items = Product_Request_Items.objects.filter(384 product_requests_product_request_id=pk).all()385 if model.product_request_created_id == str(386 operator.operator_id) and model.product_request_status == Product_Requests.STATUS_PENDING:387 template_url = 'product-requests/view-edit.html'388 display_level_approval = False389 timeline_notifications = []390 counter = -1391 if model.product_request_requested_id != '':392 notification_timeline = NotificationsTimeline()393 notification_timeline.message = 'Requested <small>by ' + model.product_request_requested_role + '</small>'394 notification_timeline.datetime = Utils.get_convert_datetime(model.product_request_requested_at,395 settings.TIME_ZONE,396 settings.APP_CONSTANT_DISPLAY_TIME_ZONE) + ' ' + settings.APP_CONSTANT_DISPLAY_TIME_ZONE_INFO397 timeline_notifications.append(notification_timeline)398 if model.product_request_reviewed_id != '':399 notification_timeline = NotificationsTimeline()400 notification_timeline.message = 'Reviewed <small>by ' + model.product_request_reviewed_role + '</small>'401 notification_timeline.datetime = Utils.get_convert_datetime(model.product_request_reviewed_at,402 settings.TIME_ZONE,403 settings.APP_CONSTANT_DISPLAY_TIME_ZONE) + ' ' + settings.APP_CONSTANT_DISPLAY_TIME_ZONE_INFO404 timeline_notifications.append(notification_timeline)405 if model.product_request_approved_updated_id != '':406 notification_timeline = NotificationsTimeline()407 notification_timeline.message = 'Approved <small>by ' + model.product_request_approved_updated_role + '</small>'408 if model.product_request_status == Product_Requests.STATUS_REJECTED:409 notification_timeline.message = 'Rejected <small>by ' + model.product_request_approved_updated_role + '</small>'410 notification_timeline.datetime = Utils.get_convert_datetime(411 model.product_request_approved_updated_at,412 settings.TIME_ZONE,413 settings.APP_CONSTANT_DISPLAY_TIME_ZONE) + ' ' + settings.APP_CONSTANT_DISPLAY_TIME_ZONE_INFO414 timeline_notifications.append(notification_timeline)415 if model.product_request_status == Product_Requests.STATUS_REQUESTED:416 notification_timeline = NotificationsTimeline()417 model.product_request_readable_status = notification_timeline.message = "<b class='text-red'>Review pending from Stock Admin</b>"418 notification_timeline.datetime = ''419 timeline_notifications.append(notification_timeline)420 if model.product_request_status == Product_Requests.STATUS_REVIEWED:421 notification_timeline = NotificationsTimeline()422 model.product_request_readable_status = notification_timeline.message = "<b class='text-red'>Approval pending from Stock Admin</b>"423 notification_timeline.datetime = ''424 timeline_notifications.append(notification_timeline)425 if model.product_request_status == Product_Requests.STATUS_APPROVED:426 notification_timeline = NotificationsTimeline()427 model.product_request_readable_status = notification_timeline.message = "<b class='text-red'>Approved</b>"428 notification_timeline.datetime = ''429 timeline_notifications.append(notification_timeline)430 if model.product_request_status == Product_Requests.STATUS_REJECTED:431 notification_timeline = NotificationsTimeline()432 model.product_request_readable_status = notification_timeline.message = "<b class='text-red'>Rejected</b>"433 notification_timeline.datetime = ''434 timeline_notifications.append(notification_timeline)435 return render(436 request, template_url,437 {438 'section': settings.BACKEND_SECTION_STOCK_ALL_REQUESTS,439 'title': Product_Requests.TITLE,440 'name': Product_Requests.NAME,441 'operator': operator,442 'auth_permissions': auth_permissions,443 'model': model,444 'index_url': reverse("product_requests_index"),445 'select_single_url': reverse("product_requests_select_single"),446 'product_request_items': product_request_items,447 'product_request_items_size': product_request_items,448 'item_index_url': reverse("product_requests_view", kwargs={'pk': pk}),449 'item_select_single_url': reverse("product_request_items_select_single"),450 'status_html_tag': Product_Requests.get_status_html_tag(model),451 'display_level_approval': display_level_approval,452 'timeline_notifications': timeline_notifications,453 }454 )455 except(TypeError, ValueError, OverflowError, Product_Requests.DoesNotExist):456 return HttpResponseNotFound('Not Found', content_type='text/plain')457 else:458 return HttpResponseForbidden('Forbidden', content_type='text/plain')459# noinspection PyUnusedLocal, PyShadowingBuiltins460def view_product_request_items(request, pk):461 template_url = 'product-request-items/index.html'462 operator = Operators.login_required(request)463 if operator is None:464 Operators.set_redirect_field_name(request, request.path)465 return redirect(reverse("operators_signin"))466 else:467 auth_permissions = Operators.get_auth_permissions(operator)468 if settings.ACCESS_PERMISSION_ORDER_VIEW in auth_permissions.values():469 try:470 model = Product_Requests.objects.get(product_request_id=pk)471 search_form = ProductRequestItemSearchIndexForm(request.POST or None)472 objects = Product_Request_Items.objects.filter(473 product_requests_product_request_id=model.product_request_id)474 if request.method == 'POST' and search_form.is_valid():475 display_search = True476 table = ProductRequestItemsTable(objects)477 else:478 display_search = False479 table = ProductRequestItemsTable(objects)480 table.set_auth_permissions(auth_permissions)481 return render(482 request, template_url,483 {484 'section': settings.BACKEND_SECTION_STOCK_ALL_REQUESTS,485 'title': Product_Requests.TITLE,486 'name': Product_Requests.NAME,487 'operator': operator,488 'auth_permissions': auth_permissions,489 'table': table,490 'search_form': search_form,491 'display_search': display_search,492 'index_url': reverse("product_request_items_index", kwargs={'pk': pk}),493 'select_multiple_url': reverse("product_request_items_select_multiple"),494 'model': model,495 'item_index_url': reverse("product_requests_view", kwargs={'pk': pk}),496 }497 )498 except(TypeError, ValueError, OverflowError, Product_Requests.DoesNotExist):499 return HttpResponseNotFound('Not Found', content_type='text/plain')500 else:...

Full Screen

Full Screen

product_request_item_views.py

Source:product_request_item_views.py Github

copy

Full Screen

1from django.contrib import messages2from django.http import HttpResponse, HttpResponseForbidden, HttpResponseNotFound3from django.shortcuts import redirect4from django.shortcuts import render5from django.urls import reverse6from django.views.decorators.csrf import csrf_exempt7from app import settings8from app.models import Operators, Product_Requests, Product_Request_Items, Products9from app.utils import Utils10from backend.forms.product_request_item_forms import ProductRequestItemCreateForm, ProductRequestItemUpdateForm11# noinspection PyUnusedLocal, PyShadowingBuiltins12def create(request, id):13 template_url = 'product-request-items/create.html'14 operator = Operators.login_required(request)15 if operator is None:16 Operators.set_redirect_field_name(request, request.path)17 return redirect(reverse("operators_signin"))18 else:19 auth_permissions = Operators.get_auth_permissions(operator)20 if settings.ACCESS_PERMISSION_ORDER_CREATE in auth_permissions.values():21 try:22 product_request = Product_Requests.objects.get(product_request_id=id)23 if request.method == 'POST':24 form = ProductRequestItemCreateForm(request.POST)25 # noinspection PyArgumentList26 if form.is_valid():27 model = Product_Request_Items()28 model.product_requests_product_request_id = product_request.product_request_id29 model.products_product_id = form.cleaned_data['products_product_id']30 product = Products.objects.get(product_id=model.products_product_id)31 model.product_request_item_product_type = product.product_type32 model.product_request_item_product_code = product.product_code33 model.product_request_item_product_tag = product.product_tag34 model.product_request_item_product_category = product.product_category35 model.product_request_item_product_title = product.product_title36 model.product_request_item_product_sub_title = product.product_sub_title37 model.product_request_item_product_quantity_initial = 038 model.product_request_item_product_quantity_ordered = form.cleaned_data[39 'product_request_item_product_quantity_ordered']40 model.product_request_item_product_quantity_balance = 041 model.product_request_item_product_quantity_unit = product.product_quantity_unit42 model.product_request_item_created_at = Utils.get_current_datetime_utc()43 model.product_request_item_created_id = operator.operator_id44 model.product_request_item_created_by = operator.operator_name45 model.product_request_item_created_department = operator.operator_department46 model.product_request_item_created_role = operator.operator_role47 model.product_request_item_updated_at = Utils.get_current_datetime_utc()48 model.product_request_item_updated_id = operator.operator_id49 model.product_request_item_updated_by = operator.operator_name50 model.product_request_item_updated_department = operator.operator_department51 model.product_request_item_updated_role = operator.operator_role52 model.product_request_item_received_at = settings.APP_CONSTANT_DEFAULT_DATETIME_VALUE53 model.product_request_item_received_id = ''54 model.product_request_item_received_by = ''55 model.product_request_item_received_department = ''56 model.product_request_item_received_role = ''57 model.product_request_item_status = Product_Requests.STATUS_PENDING58 # noinspection PyCallByClass,PyTypeChecker59 model.save('Created')60 Product_Requests.update_grand_total(request, product_request, operator)61 messages.success(request, 'Item added successfully.')62 return redirect(reverse("product_requests_view", args=[product_request.product_request_id]))63 else:64 error_string = ' '.join([' '.join(x for x in l) for l in list(form.errors.values())])65 messages.error(request, '' + error_string)66 return redirect(reverse("product_requests_view", args=[product_request.product_request_id]))67 else:68 form = ProductRequestItemCreateForm(69 initial={70 'product_request_id': product_request.product_request_code,71 'products_product_id': '',72 'product_request_item_product_quantity_ordered': 0,73 })74 return render(75 request, template_url,76 {77 'section': settings.BACKEND_SECTION_STOCK_ALL_REQUESTS,78 'title': Product_Request_Items.TITLE,79 'name': Product_Request_Items.NAME,80 'operator': operator,81 'auth_permissions': auth_permissions,82 'form': form,83 }84 )85 except(TypeError, ValueError, OverflowError,86 Product_Requests.DoesNotExist, Product_Request_Items.DoesNotExist):87 return HttpResponseNotFound('Not Found', content_type='text/plain')88 else:89 return HttpResponseForbidden('Forbidden', content_type='text/plain')90# noinspection PyUnusedLocal, PyShadowingBuiltins91def update(request, pk):92 template_url = 'product-request-items/update.html'93 operator = Operators.login_required(request)94 if operator is None:95 Operators.set_redirect_field_name(request, request.path)96 return redirect(reverse("operators_signin"))97 else:98 auth_permissions = Operators.get_auth_permissions(operator)99 if settings.ACCESS_PERMISSION_ORDER_UPDATE in auth_permissions.values():100 try:101 model = Product_Request_Items.objects.get(product_request_item_id=pk)102 product_request = Product_Requests.objects.get(103 product_request_id=model.product_requests_product_request_id)104 if request.method == 'POST':105 form = ProductRequestItemUpdateForm(request.POST)106 # noinspection PyArgumentList107 if form.is_valid():108 model.products_product_id = form.cleaned_data['products_product_id']109 product = Products.objects.get(product_id=model.products_product_id)110 model.product_request_item_product_type = product.product_type111 model.product_request_item_product_code = product.product_code112 model.product_request_item_product_tag = product.product_tag113 model.product_request_item_product_category = product.product_category114 model.product_request_item_product_title = product.product_title115 model.product_request_item_product_sub_title = product.product_sub_title116 model.product_request_item_product_quantity_initial = 0117 model.product_request_item_product_quantity_ordered = form.cleaned_data[118 'product_request_item_product_quantity_ordered']119 model.product_request_item_product_quantity_balance = 0120 model.product_request_item_product_quantity_unit = product.product_quantity_unit121 model.product_request_item_updated_at = Utils.get_current_datetime_utc()122 model.product_request_item_updated_id = operator.operator_id123 model.product_request_item_updated_by = operator.operator_name124 model.product_request_item_updated_department = operator.operator_department125 model.product_request_item_updated_role = operator.operator_role126 model.save()127 Product_Requests.update_grand_total(request, product_request, operator)128 messages.success(request, 'Item updated successfully.')129 return redirect(reverse("product_requests_view", args=[product_request.product_request_id]))130 else:131 error_string = ' '.join([' '.join(x for x in l) for l in list(form.errors.values())])132 messages.error(request, '' + error_string)133 return redirect(reverse("product_requests_view", args=[product_request.product_request_id]))134 else:135 form = ProductRequestItemUpdateForm(136 initial={137 'product_request_id': product_request.product_request_code,138 'products_product_id': model.products_product_id,139 'product_request_item_product_quantity_ordered': model.product_request_item_product_quantity_ordered,140 }141 )142 return render(143 request, template_url,144 {145 'section': settings.BACKEND_SECTION_STOCK_ALL_REQUESTS,146 'title': Product_Request_Items.TITLE,147 'name': Product_Request_Items.NAME,148 'operator': operator,149 'auth_permissions': auth_permissions,150 'form': form,151 'model': model,152 }153 )154 except(155 TypeError, ValueError, OverflowError, Product_Requests.DoesNotExist,156 Product_Request_Items.DoesNotExist):157 return HttpResponseNotFound('Not Found', content_type='text/plain')158 else:159 return HttpResponseForbidden('Forbidden', content_type='text/plain')160@csrf_exempt161# noinspection PyUnusedLocal162def select_single(request):163 if request.is_ajax():164 operator = Operators.login_required(request)165 if operator is None:166 # Operators.set_redirect_field_name(request, request.path)167 # return redirect(reverse("operators_signin"))168 return HttpResponse('signin', content_type='text/plain')169 else:170 auth_permissions = Operators.get_auth_permissions(operator)171 action = request.POST['action']172 id = request.POST['id']173 if action != '' and id is not None:174 if action == 'delete':175 if settings.ACCESS_PERMISSION_ORDER_UPDATE in auth_permissions.values():176 try:177 model = Product_Request_Items.objects.get(product_request_item_id=id)178 product_request = Product_Requests.objects.get(179 product_request_id=model.product_requests_product_request_id)180 Product_Request_Items.delete_product_request_item(request, model, operator)181 Product_Requests.update_grand_total(request, product_request, operator)182 messages.success(request, 'Item removed successfully.')183 except(TypeError, ValueError, OverflowError, Product_Request_Items.DoesNotExist):184 return HttpResponseBadRequest('Bad Request', content_type='text/plain')185 else:186 return HttpResponseForbidden('Forbidden', content_type='text/plain')187 return HttpResponse('success', content_type='text/plain')188 else:189 return HttpResponseBadRequest('Bad Request', content_type='text/plain')190 else:191 return HttpResponseForbidden('Forbidden', content_type='text/plain')192@csrf_exempt193# noinspection PyUnusedLocal194def select_multiple(request):195 if request.is_ajax():196 operator = Operators.login_required(request)197 if operator is None:198 # Operators.set_redirect_field_name(request, request.path)199 # return redirect(reverse("operators_signin"))200 return HttpResponse('signin', content_type='text/plain')201 else:202 auth_permissions = Operators.get_auth_permissions(operator)203 action = request.POST['action']204 ids = request.POST['ids']205 try:206 ids = ids.split(",")207 except(TypeError, ValueError, OverflowError):208 ids = None209 if action != '' and ids is not None:210 if action == 'order-item-received':211 if settings.ACCESS_PERMISSION_ORDER_UPDATE in auth_permissions.values():212 for id in ids:213 try:214 model = Product_Request_Items.objects.get(product_request_item_id=id)215 if model.product_request_item_status == Product_Request_Items.STATUS_PENDING:216 try:217 product = Products.objects.get(product_id=model.products_product_id)218 model.product_request_item_product_quantity_initial = product.product_quantity_available219 product.product_quantity_available = product.product_quantity_available - model.product_request_item_product_quantity_ordered220 model.product_request_item_product_quantity_balance = product.product_quantity_available221 product.product_updated_at = Utils.get_current_datetime_utc()222 product.product_updated_id = operator.operator_id223 product.product_updated_by = operator.operator_name224 product.product_updated_department = operator.operator_department225 product.product_updated_role = operator.operator_role226 product.save()227 except (Product_Requests.DoesNotExist, Products.DoesNotExist):228 print('Product Request does not exist.')229 model.product_request_item_received_at = Utils.get_current_datetime_utc()230 model.product_request_item_received_id = operator.operator_id231 model.product_request_item_received_by = operator.operator_name232 model.product_request_item_received_department = operator.operator_department233 model.product_request_item_received_role = operator.operator_role234 model.product_request_item_status = Product_Request_Items.STATUS_RECEIVED235 model.save()236 except(TypeError, ValueError, OverflowError, Product_Request_Items.DoesNotExist):237 continue238 messages.success(request, 'Updated successfully.')239 else:240 return HttpResponseForbidden('Forbidden', content_type='text/plain')241 if action == 'order-item-pending':242 if settings.ACCESS_PERMISSION_ORDER_UPDATE in auth_permissions.values():243 for id in ids:244 try:245 model = Product_Request_Items.objects.get(product_request_item_id=id)246 if model.product_request_item_status == Product_Request_Items.STATUS_RECEIVED:247 try:248 product = Products.objects.get(product_id=model.products_product_id)249 model.product_request_item_product_quantity_initial = 0250 product.product_quantity_available = product.product_quantity_available + model.product_request_item_product_quantity_ordered251 model.product_request_item_product_quantity_balance = 0252 product.product_updated_at = Utils.get_current_datetime_utc()253 product.product_updated_id = operator.operator_id254 product.product_updated_by = operator.operator_name255 product.product_updated_department = operator.operator_department256 product.product_updated_role = operator.operator_role257 product.save()258 except (Product_Requests.DoesNotExist, Products.DoesNotExist):259 print('Product Request not exist.')260 model.product_request_item_received_at = settings.APP_CONSTANT_DEFAULT_DATETIME_VALUE261 model.product_request_item_received_id = ''262 model.product_request_item_received_by = ''263 model.product_request_item_received_department = ''264 model.product_request_item_received_role = ''265 model.product_request_item_status = Product_Request_Items.STATUS_PENDING266 model.save()267 except(TypeError, ValueError, OverflowError, Product_Request_Items.DoesNotExist):268 continue269 messages.success(request, 'Updated successfully.')270 else:271 return HttpResponseForbidden('Forbidden', content_type='text/plain')272 return HttpResponse('success', content_type='text/plain')273 else:274 return HttpResponseBadRequest('Bad Request', content_type='text/plain')275 else:...

Full Screen

Full Screen

twisted.py

Source:twisted.py Github

copy

Full Screen

1# Copyright (c) 2007-2009 The PyAMF Project.2# See LICENSE for details.3"""4Twisted server implementation.5This gateway allows you to expose functions in Twisted to AMF6clients and servers.7@see: U{Twisted homepage (external)<http://twistedmatrix.com>}8@since: 0.1.09"""10import sys, os.path11try:12 sys.path.remove('')13except ValueError:14 pass15try:16 sys.path.remove(os.path.dirname(os.path.abspath(__file__)))17except ValueError:18 pass19twisted = __import__('twisted')20__import__('twisted.internet.defer')21__import__('twisted.internet.threads')22__import__('twisted.web.resource')23__import__('twisted.web.server')24defer = twisted.internet.defer25threads = twisted.internet.threads26resource = twisted.web.resource27server = twisted.web.server28import pyamf29from pyamf import remoting30from pyamf.remoting import gateway, amf0, amf331__all__ = ['TwistedGateway']32class AMF0RequestProcessor(amf0.RequestProcessor):33 """34 A Twisted friendly implementation of35 L{amf0.RequestProcessor<pyamf.remoting.amf0.RequestProcessor>}36 """37 def __call__(self, request, *args, **kwargs):38 """39 Calls the underlying service method.40 @return: A C{Deferred} that will contain the AMF L{Response}.41 @rtype: C{twisted.internet.defer.Deferred}42 """43 try:44 service_request = self.gateway.getServiceRequest(request,45 request.target)46 except gateway.UnknownServiceError, e:47 return defer.succeed(self.buildErrorResponse(request))48 response = remoting.Response(None)49 deferred_response = defer.Deferred()50 def eb(failure):51 errMesg = "%s: %s" % (failure.type, failure.getErrorMessage())52 self.gateway.logger.error(errMesg)53 self.gateway.logger.info(failure.getTraceback())54 deferred_response.callback(self.buildErrorResponse(55 request, (failure.type, failure.value, failure.tb)))56 def response_cb(result):57 self.gateway.logger.debug("AMF Response: %s" % (result,))58 response.body = result59 deferred_response.callback(response)60 def preprocess_cb(result):61 d = defer.maybeDeferred(self._getBody, request, response,62 service_request, **kwargs)63 d.addCallback(response_cb).addErrback(eb)64 def auth_cb(result):65 if result is not True:66 response.status = remoting.STATUS_ERROR67 response.body = remoting.ErrorFault(code='AuthenticationError',68 description='Authentication failed')69 deferred_response.callback(response)70 return71 d = defer.maybeDeferred(self.gateway.preprocessRequest,72 service_request, *args, **kwargs)73 d.addCallback(preprocess_cb).addErrback(eb)74 # we have a valid service, now attempt authentication75 d = defer.maybeDeferred(self.authenticateRequest, request,76 service_request, **kwargs)77 d.addCallback(auth_cb).addErrback(eb)78 return deferred_response79class AMF3RequestProcessor(amf3.RequestProcessor):80 """81 A Twisted friendly implementation of82 L{amf3.RequestProcessor<pyamf.remoting.amf3.RequestProcessor>}83 """84 def _processRemotingMessage(self, amf_request, ro_request, **kwargs):85 ro_response = amf3.generate_acknowledgement(ro_request)86 amf_response = remoting.Response(ro_response, status=remoting.STATUS_OK)87 try:88 service_name = ro_request.operation89 if hasattr(ro_request, 'destination') and ro_request.destination:90 service_name = '%s.%s' % (ro_request.destination, service_name)91 service_request = self.gateway.getServiceRequest(amf_request,92 service_name)93 except gateway.UnknownServiceError, e:94 return defer.succeed(remoting.Response(95 self.buildErrorResponse(ro_request),96 status=remoting.STATUS_ERROR))97 deferred_response = defer.Deferred()98 def eb(failure):99 errMesg = "%s: %s" % (failure.type, failure.getErrorMessage())100 self.gateway.logger.error(errMesg)101 self.gateway.logger.info(failure.getTraceback())102 ro_response = self.buildErrorResponse(ro_request, (failure.type,103 failure.value, failure.tb))104 deferred_response.callback(remoting.Response(ro_response,105 status=remoting.STATUS_ERROR))106 def response_cb(result):107 ro_response.body = result108 res = remoting.Response(ro_response)109 self.gateway.logger.debug("AMF Response: %r" % (res,))110 deferred_response.callback(res)111 def process_cb(result):112 d = defer.maybeDeferred(self.gateway.callServiceRequest,113 service_request, *ro_request.body, **kwargs)114 d.addCallback(response_cb).addErrback(eb)115 d = defer.maybeDeferred(self.gateway.preprocessRequest, service_request,116 *ro_request.body, **kwargs)117 d.addCallback(process_cb).addErrback(eb)118 return deferred_response119 def __call__(self, amf_request, **kwargs):120 """121 Calls the underlying service method.122 @return: A C{deferred} that will contain the AMF L{Response}.123 @rtype: C{Deferred<twisted.internet.defer.Deferred>}124 """125 deferred_response = defer.Deferred()126 ro_request = amf_request.body[0]127 def cb(amf_response):128 deferred_response.callback(amf_response)129 def eb(failure):130 errMesg = "%s: %s" % (failure.type, failure.getErrorMessage())131 self.gateway.logger.error(errMesg)132 self.gateway.logger.info(failure.getTraceback())133 deferred_response.callback(self.buildErrorResponse(ro_request,134 (failure.type, failure.value, failure.tb)))135 d = defer.maybeDeferred(self._getBody, amf_request, ro_request, **kwargs)136 d.addCallback(cb).addErrback(eb)137 return deferred_response138class TwistedGateway(gateway.BaseGateway, resource.Resource):139 """140 Twisted Remoting gateway for C{twisted.web}.141 @ivar expose_request: Forces the underlying HTTP request to be the first142 argument to any service call.143 @type expose_request: C{bool}144 """145 allowedMethods = ('POST',)146 def __init__(self, *args, **kwargs):147 if 'expose_request' not in kwargs:148 kwargs['expose_request'] = True149 gateway.BaseGateway.__init__(self, *args, **kwargs)150 resource.Resource.__init__(self)151 def _finaliseRequest(self, request, status, content, mimetype='text/plain'):152 """153 Finalises the request.154 @param request: The HTTP Request.155 @type request: C{http.Request}156 @param status: The HTTP status code.157 @type status: C{int}158 @param content: The content of the response.159 @type content: C{str}160 @param mimetype: The MIME type of the request.161 @type mimetype: C{str}162 """163 request.setResponseCode(status)164 request.setHeader("Content-Type", mimetype)165 request.setHeader("Content-Length", str(len(content)))166 request.setHeader("Server", gateway.SERVER_NAME)167 request.write(content)168 request.finish()169 def render_POST(self, request):170 """171 Read remoting request from the client.172 @type request: The HTTP Request.173 @param request: C{twisted.web.http.Request}174 """175 def handleDecodeError(failure):176 """177 Return HTTP 400 Bad Request.178 """179 errMesg = "%s: %s" % (failure.type, failure.getErrorMessage())180 self.logger.error(errMesg)181 self.logger.info(failure.getTraceback())182 183 body = "400 Bad Request\n\nThe request body was unable to " \184 "be successfully decoded."185 if self.debug:186 body += "\n\nTraceback:\n\n%s" % failure.getTraceback()187 self._finaliseRequest(request, 400, body)188 request.content.seek(0, 0)189 context = pyamf.get_context(pyamf.AMF0)190 d = threads.deferToThread(remoting.decode, request.content.read(),191 context, strict=self.strict)192 def cb(amf_request):193 self.logger.debug("AMF Request: %r" % amf_request)194 x = self.getResponse(request, amf_request)195 x.addCallback(self.sendResponse, request, context)196 # Process the request197 d.addCallback(cb).addErrback(handleDecodeError)198 return server.NOT_DONE_YET199 def sendResponse(self, amf_response, request, context):200 def cb(result):201 self._finaliseRequest(request, 200, result.getvalue(),202 remoting.CONTENT_TYPE)203 def eb(failure):204 """205 Return 500 Internal Server Error.206 """207 errMesg = "%s: %s" % (failure.type, failure.getErrorMessage())208 self.logger.error(errMesg)209 self.logger.info(failure.getTraceback())210 body = "500 Internal Server Error\n\nThere was an error encoding" \211 " the response."212 if self.debug:213 body += "\n\nTraceback:\n\n%s" % failure.getTraceback()214 self._finaliseRequest(request, 500, body)215 d = threads.deferToThread(remoting.encode, amf_response, context, strict=self.strict)216 d.addCallback(cb).addErrback(eb)217 def getProcessor(self, request):218 """219 Determines the request processor, based on the request.220 @param request: The AMF message.221 @type request: L{Request<pyamf.remoting.Request>}222 """223 if request.target == 'null':224 return AMF3RequestProcessor(self)225 return AMF0RequestProcessor(self)226 def getResponse(self, http_request, amf_request):227 """228 Processes the AMF request, returning an AMF L{Response}.229 @param http_request: The underlying HTTP Request230 @type http_request: C{twisted.web.http.Request}231 @param amf_request: The AMF Request.232 @type amf_request: L{Envelope<pyamf.remoting.Envelope>}233 """234 response = remoting.Envelope(amf_request.amfVersion,235 amf_request.clientType)236 dl = []237 def cb(body, name):238 response[name] = body239 for name, message in amf_request:240 processor = self.getProcessor(message)241 d = defer.maybeDeferred(processor, message,242 http_request=http_request)243 d.addCallback(cb, name)244 dl.append(d)245 def cb2(result):246 return response247 def eb(failure):248 """249 Return 500 Internal Server Error.250 """251 errMesg = "%s: %s" % (failure.type, failure.getErrorMessage())252 self.logger.error(errMesg)253 self.logger.info(failure.getTraceback())254 body = "500 Internal Server Error\n\nThe request was unable to " \255 "be successfully processed."256 if self.debug:257 body += "\n\nTraceback:\n\n%s" % failure.getTraceback()258 self._finaliseRequest(http_request, 500, body)259 d = defer.DeferredList(dl)260 return d.addCallback(cb2).addErrback(eb)261 def authenticateRequest(self, service_request, username, password, **kwargs):262 """263 Processes an authentication request. If no authenticator is supplied,264 then authentication succeeds.265 @return: C{Deferred}.266 @rtype: C{twisted.internet.defer.Deferred}267 """268 authenticator = self.getAuthenticator(service_request)269 self.logger.debug('Authenticator expands to: %r' % authenticator)270 if authenticator is None:271 return defer.succeed(True)272 args = (username, password)273 if hasattr(authenticator, '_pyamf_expose_request'):274 http_request = kwargs.get('http_request', None)275 args = (http_request,) + args276 return defer.maybeDeferred(authenticator, *args)277 def preprocessRequest(self, service_request, *args, **kwargs):278 """279 Preprocesses a request.280 """281 processor = self.getPreprocessor(service_request)282 self.logger.debug('Preprocessor expands to: %r' % processor)283 if processor is None:284 return285 args = (service_request,) + args286 if hasattr(processor, '_pyamf_expose_request'):287 http_request = kwargs.get('http_request', None)288 args = (http_request,) + args...

Full Screen

Full Screen

student.py

Source:student.py Github

copy

Full Screen

1from django.shortcuts import render, HttpResponse, redirect2from .models import Account, Admission, Student3from django.db import IntegrityError4from .decorator import allowed_users5from django.contrib.auth.decorators import login_required6import datetime7import secrets, random8import string9import datetime10year_s = datetime.datetime.today().year11YEARS = list(range(year_s, year_s - 6, -1))12def gen():13 N = 714 res = ''.join(secrets.choice(string.ascii_uppercase + string.digits) for i in range(N))15 res = 'PCMT' + str(datetime.datetime.today().year) + res16 return res17@login_required(login_url='college:login')18def studentsRegistration(request):19 if request.POST:20 # try:21 if request.POST.get('email'):22 try:23 enrollment_no = gen()24 add_user = Account()25 add_user.email = request.POST.get('email')26 request.session['student_email'] = request.POST.get('email')27 print(request.session['student_email'])28 add_user.enrollment_no = enrollment_no29 add_user.set_password(enrollment_no)30 add_user.is_student = True31 add_user.is_approved = True32 add_user.save()33 print('hello')34 user = Student()35 user.semester = request.POST.get('semester')36 user.year = str(datetime.datetime.today().year)37 user.student_data = add_user38 user.enrollment_no = enrollment_no39 user.email = request.POST.get('email')40 user.contact_no = request.POST.get('contact_no')41 user.first_name = request.POST.get('first_name')42 user.last_name = request.POST.get('last_name')43 user.dob = request.POST.get('dob')44 user.gender = request.POST.get('gender')45 user.address = request.POST.get('address')46 user.city = request.POST.get('city')47 user.state = request.POST.get('state')48 user.country = request.POST.get('country')49 user.fathers_name = request.POST.get('fathers_name')50 user.mothers_name = request.POST.get('mothers_name')51 user.blood_group = request.POST.get('blood_group')52 user.mothers_tongue = request.POST.get('mothers_tongue')53 user.fathers_contact_no = request.POST.get('fathers_contact_no')54 user.guardian_name = request.POST.get('guardian_name')55 user.guardian_contact_no = request.POST.get('guardian_contact_no')56 user.relation_with_guardian = request.POST.get('relation_with_guardian')57 user.nationality = request.POST.get('nationality')58 user.cast = request.POST.get('cast')59 user.religion = request.POST.get('religion')60 user.physically_challenge = request.POST.get('physically_challenge')61 user.department = request.POST.get('department')62 user.aadhar_card_no = request.POST.get('aadhar_card_no')63 user.save()64 user.physically_certificate = request.FILES.get('physically_certificate')65 user.cast_certificate = request.FILES.get('cast_certificate')66 user.photo = request.FILES.get('photo')67 user.aadhar_card = request.FILES.get('aadhar_card')68 user.saveQrCode(enrollment_no=enrollment_no)69 user.save()70 msg = "Saved successfully"71 color = 'success'72 return render(request, 'registration.html', {'msg': msg, 'color': color})73 except:74 if Student.objects.filter(email=request.session['student_email']).count():75 msg = "Fill Entrance Examination field"76 color = 'danger'77 print('hello', Student.objects.filter(email=request.session['student_email']).count)78 return render(request, 'registration.html', {'msg': msg, 'color': color})79 else:80 msg = "Try fill all the filed"81 color = 'danger'82 return render(request, 'registration.html', {'msg': msg, 'color': color})83 elif request.POST.get('admission_cat'):84 try:85 user = Student.objects.get(email=request.session['student_email'])86 user.admission_cat = request.POST.get('admission_cat')87 user.conducted_by = request.POST.get('conducted_by')88 user.rank = request.POST.get('rank')89 user.roll_no = request.POST.get('roll_no')90 user.allotment = request.POST.get('allotment')91 user.admit_card = request.FILES.get('admit_card')92 user.rank_card = request.FILES.get('rank_card')93 user.roll_no = request.POST.get('roll_no')94 user.save()95 msg = "Saved successfully And Fill Education information 10th"96 color = 'success'97 return render(request, 'registration.html', {'msg': msg, 'color': color})98 except:99 msg = "Entrance examination fill all field"100 color = 'danger'101 return render(request, 'registration.html', {'msg': msg, 'color': color})102 elif request.POST.get('school_name_10'):103 try:104 user = Student.objects.get(email=request.session['student_email'])105 user.school_name_10 = request.POST.get('school_name_10')106 user.board_10 = request.POST.get('board_10')107 user.medium_10 = request.POST.get('medium_10')108 user.address10 = request.POST.get('address10')109 user.city10 = request.POST.get('city10')110 user.state10 = request.POST.get('state10')111 user.country10 = request.POST.get('country10')112 user.passing_year_10 = request.POST.get('passing_year_10')113 user.sub1 = request.POST.get('sub1')114 user.sub2 = request.POST.get('sub2')115 user.sub3 = request.POST.get('sub3')116 user.sub4 = request.POST.get('sub4')117 user.sub5 = request.POST.get('sub5')118 user.aggregate10 = request.POST.get('aggregate10')119 user.mark10 = request.FILES.get('mark10')120 user.admit10 = request.FILES.get('admit10')121 user.certificate10 = request.FILES.get('certificate10')122 user.save()123 msg = "Saved successfully And Fill 12th or Diploma form"124 color = 'success'125 return render(request, 'new_enrollment.html', {'msg': msg, 'color': color})126 except:127 msg = "Fill Education information 10th all field correctly"128 color = 'danger'129 return render(request, 'registration.html', {'msg': msg, 'color': color})130 elif request.POST.get('diploma_or_12') == '12th':131 try:132 user = Student.objects.get(email=request.session['student_email'])133 user.school_name_12 = request.POST.get('school_name_12')134 user.board_12 = request.POST.get('board_12')135 user.medium_12 = request.POST.get('medium_12')136 user.address12 = request.POST.get('address12')137 user.city12 = request.POST.get('city12')138 user.state12 = request.POST.get('state12')139 user.country12 = request.POST.get('country12')140 user.passing_year_12 = request.POST.get('passing_year_12')141 user.english = request.POST.get('english')142 user.chemistry = request.POST.get('chemistry')143 user.physics = request.POST.get('physics')144 user.math = request.POST.get('math')145 user.optional = request.POST.get('optional')146 user.aggregate12 = request.POST.get('aggregate12')147 user.mark12 = request.FILES.get('mark12')148 user.admit12 = request.FILES.get('admit12')149 user.certificate12 = request.FILES.get('certificate12')150 user.save()151 msg = "Saved successfully And Fill others form"152 color = 'success'153 return render(request, 'registration.html', {'msg': msg, 'color': color})154 except:155 msg = "Fill Education 12th or Diploma"156 color = 'danger'157 return render(request, 'registration.html', {'msg': msg, 'color': color})158 elif request.POST.get('diploma_or_12') == 'diploma':159 try:160 user = Student.objects.get(email=request.session['student_email'])161 user.school_name_diploma = request.POST.get('school_name_diploma')162 user.board_diploma = request.POST.get('board_diploma')163 user.medium_diploma = request.POST.get('medium_diploma')164 user.addressDiploma = request.POST.get('addressDiploma')165 user.cityDiploma = request.POST.get('cityDiploma')166 user.stateDiploma = request.POST.get('stateDiploma')167 user.countryDiploma = request.POST.get('countryDiploma')168 user.passing_year_Diploma = request.POST.get('passing_year_Diploma')169 user.marksDiploma = request.POST.get('marksDiploma')170 user.aggregateDiploma = request.POST.get('aggregateDiploma')171 user.division = request.POST.get('division')172 user.markDiploma = request.FILES.get('markDiploma')173 user.certificateDiploma = request.FILES.get('certificateDiploma')174 user.save()175 msg = "Saved successfully And Fill others form"176 color = 'success'177 return render(request, 'registration.html', {'msg': msg, 'color': color})178 except:179 msg = "Fill Education 12th or Diploma"180 color = 'danger'181 return render(request, 'registration.html', {'msg': msg, 'color': color})182 elif request.POST.get('loan'):183 try:184 user = Student.objects.get(email=request.session['student_email'])185 user.loan = request.POST.get('loan')186 user.gap = request.POST.get('gap')187 user.reason = request.POST.get('reason')188 user.hostel = request.POST.get('hostel')189 user.save()190 msg = "Saved successfully"191 color = 'success'192 return render(request, 'registration.html', {'msg': msg, 'color': color})193 except:194 msg = "Try fill all fields"195 color = 'danger'196 return render(request, 'registration.html', {'msg': msg, 'color': color})197 return render(request, 'registration.html', )198@login_required(login_url='college:login')199def student_data_view(request):200 if request.POST and not request.user.is_student:201 if request.POST.get('university_roll') and not request.user.is_student:202 university_roll = request.POST.get('university_roll')203 User = Student.objects.get(university_roll=university_roll)204 return render(request, "student_data_view.html", context={'user': User, 'YEARS': YEARS})205 else:206 year = request.POST.get('go_year')207 semester = request.POST.get('go_semester')208 User = Student.objects.filter(semester=semester, year=year)209 return render(request, "student_data_view.html", context={'user': User, 'YEARS': YEARS})210 elif request.user.is_HOD:211 user = {}212 return render(request, "student_data_view.html", context={'user': user, 'YEARS': YEARS})213 elif request.user.is_admin:214 user = {}215 return render(request, "student_data_view.html", context={'user': user, 'YEARS': YEARS})216 elif request.user.is_student:217 user = Student.objects.filter(email=request.session['email'])218 return render(request, "student_data_view.html", context={'user': user, 'YEARS': YEARS})219 elif request.user.is_BOC:220 # user = Student.objects.filter(is_student=True, year=request.user.year, semester=request.user.semester)221 user = {}222 return render(request, "student_data_view.html", context={'user': user, 'YEARS': YEARS})...

Full Screen

Full Screen

authorization_code.py

Source:authorization_code.py Github

copy

Full Screen

...20 # request.scopes is only mandated in post auth and both pre and21 # post auth use validate_authorization_request22 # if not request.scopes:23 # raise ValueError('Scopes must be set on post auth.')24 # self.validate_authorization_request(request)25 log.debug('Pre resource owner authorization validation ok for %r.',26 request)27 # If the request fails due to a missing, invalid, or mismatching28 # redirection URI, or if the client identifier is missing or invalid,29 # the authorization server SHOULD inform the resource owner of the30 # error and MUST NOT automatically redirect the user-agent to the31 # invalid redirection URI.32 except FatalClientError as e:33 log.debug('Fatal client error during validation of %r. %r.',34 request, e)35 raise36 # If the resource owner denies the access request or if the request37 # fails for reasons other than a missing or invalid redirection URI,38 # the authorization server informs the client by adding the following39 # parameters to the query component of the redirection URI using the40 # "application/x-www-form-urlencoded" format, per Appendix B:41 # http://tools.ietf.org/html/rfc6749#appendix-B42 except OAuth2Error as e:43 log.debug('Client error during validation of %r. %r.', request, e)44 request.redirect_uri = request.redirect_uri or self.error_uri45 return {'Location': common.add_params_to_uri(request.redirect_uri, e.twotuples)}, None, 30246 grant = self.create_authorization_code(request)47 log.debug('Saving grant %r for %r.', grant, request)48 request_validator.save_authorization_code(request.client_id, grant, request)49 return {'Location': common.add_params_to_uri(request.redirect_uri, grant.items())}, None, 30250 def validate_authorization_request(self, request):51 """Check the authorization request for normal and fatal errors.52 A normal error could be a missing response_type parameter or the client53 attempting to access scope it is not allowed to ask authorization for.54 Normal errors can safely be included in the redirection URI and55 sent back to the client.56 Fatal errors occur when the client_id or redirect_uri is invalid or57 missing. These must be caught by the provider and handled, how this58 is done is outside of the scope of OAuthLib but showing an error59 page describing the issue is a good idea.60 """61 # First check for fatal errors62 # If the request fails due to a missing, invalid, or mismatching63 # redirection URI, or if the client identifier is missing or invalid,64 # the authorization server SHOULD inform the resource owner of the...

Full Screen

Full Screen

wsgi_request_info_test.py

Source:wsgi_request_info_test.py Github

copy

Full Screen

...41 config.major_version = version_id42 config.module_name = module_name43 return config44 def test_get_request_url(self):45 with self.request_info.request(46 self._create_environ('https', 'machine:8080',47 '/foo', 'bar=baz'),48 self._create_module_configuration('default', '1')) as request_id:49 self._assert_request_id(request_id)50 self.assertEqual('https://machine:8080/foo?bar=baz',51 self.request_info.get_request_url(request_id))52 def test_get_request_environ(self):53 environ = object()54 with self.request_info.request(55 environ,56 self._create_module_configuration('default', '1')) as request_id:57 self._assert_request_id(request_id)58 self.assertIs(environ, self.request_info.get_request_environ(request_id))59 def test_get_dispatcher(self):60 with self.request_info.request(61 self._create_environ('https', 'machine:8080',62 '/foo', 'bar=baz'),63 self._create_module_configuration('default', '1')) as request_id:64 self._assert_request_id(request_id)65 self.assertEqual(self.dispatcher,66 self.request_info.get_dispatcher())67 def test_get_module(self):68 with self.request_info.request(69 self._create_environ('https', 'machine:8080',70 '/foo', 'bar=baz'),71 self._create_module_configuration('default', '1')) as request_id:72 self._assert_request_id(request_id)73 self.assertEqual('default', self.request_info.get_module(request_id))74 def test_get_version(self):75 with self.request_info.request(76 self._create_environ('https', 'machine:8080',77 '/foo', 'bar=baz'),78 self._create_module_configuration('default', '1')) as request_id:79 self._assert_request_id(request_id)80 self.assertEqual('1', self.request_info.get_version(request_id))81 def test_get_instance_unset(self):82 with self.request_info.request(83 self._create_environ('https', 'machine:8080',84 '/foo', 'bar=baz'),85 self._create_module_configuration('default', '1')) as request_id:86 self._assert_request_id(request_id)87 self.assertIsNone(self.request_info.get_instance(request_id))88 def test_get_instance(self):89 with self.request_info.request(90 self._create_environ('https', 'machine:8080',91 '/foo', 'bar=baz'),92 self._create_module_configuration('default', '1')) as request_id:93 instance = object()94 self.request_info.set_request_instance(request_id, instance)95 self._assert_request_id(request_id)96 self.assertEqual(instance, self.request_info.get_instance(request_id))97 def test_concurrent_requests(self):98 request_id1 = self.request_info.start_request(99 self._create_environ('http', 'machine:8081'),100 self._create_module_configuration('default', '1'))101 request_id2 = self.request_info.start_request(102 self._create_environ('http', 'machine:8082'),103 self._create_module_configuration('default', '2'))104 request_id3 = self.request_info.start_request(105 self._create_environ('http', 'machine:8083'),106 self._create_module_configuration('other', '1'))107 self._assert_request_id(request_id1)108 self._assert_request_id(request_id2)109 self._assert_request_id(request_id3)110 self.assertTrue(request_id1 != request_id2 != request_id3)111 self.assertEqual('http://machine:8081/',112 self.request_info.get_request_url(request_id1))113 self.assertEqual(self.dispatcher,114 self.request_info.get_dispatcher())115 self.assertEqual('default', self.request_info.get_module(request_id1))116 self.assertEqual('1', self.request_info.get_version(request_id1))117 self.assertEqual('http://machine:8082/',118 self.request_info.get_request_url(request_id2))119 self.assertEqual(self.dispatcher,120 self.request_info.get_dispatcher())121 self.assertEqual('default', self.request_info.get_module(request_id2))122 self.assertEqual('2', self.request_info.get_version(request_id2))123 self.request_info.end_request(request_id1)124 self.request_info.end_request(request_id2)125 self.assertEqual('http://machine:8083/',126 self.request_info.get_request_url(request_id3))127 self.assertEqual(self.dispatcher,128 self.request_info.get_dispatcher())129 self.assertEqual('other', self.request_info.get_module(request_id3))130 self.assertEqual('1', self.request_info.get_version(request_id3))131if __name__ == '__main__':...

Full Screen

Full Screen

api_request_test.py

Source:api_request_test.py Github

copy

Full Screen

...21from google.appengine.tools.devappserver2.endpoints import api_request22from google.appengine.tools.devappserver2.endpoints import test_utils23class RequestTest(unittest.TestCase):24 def test_parse_no_body(self):25 request = test_utils.build_request('/_ah/api/foo?bar=baz')26 self.assertEqual('foo', request.path)27 self.assertEqual('bar=baz', request.query)28 self.assertEqual({'bar': ['baz']}, request.parameters)29 self.assertEqual('', request.body)30 self.assertEqual({}, request.body_json)31 self.assertEqual([('CONTENT-TYPE', 'application/json')],32 request.headers.items())33 self.assertEqual(None, request.request_id)34 def test_parse_with_body(self):35 request = test_utils.build_request('/_ah/api/foo?bar=baz',36 '{"test": "body"}')37 self.assertEqual('foo', request.path)38 self.assertEqual('bar=baz', request.query)39 self.assertEqual({'bar': ['baz']}, request.parameters)40 self.assertEqual('{"test": "body"}', request.body)41 self.assertEqual({'test': 'body'}, request.body_json)42 self.assertEqual([('CONTENT-TYPE', 'application/json')],43 request.headers.items())44 self.assertEqual(None, request.request_id)45 def test_parse_empty_values(self):46 request = test_utils.build_request('/_ah/api/foo?bar')47 self.assertEqual('foo', request.path)48 self.assertEqual('bar', request.query)49 self.assertEqual({'bar': ['']}, request.parameters)50 self.assertEqual('', request.body)51 self.assertEqual({}, request.body_json)52 self.assertEqual([('CONTENT-TYPE', 'application/json')],53 request.headers.items())54 self.assertEqual(None, request.request_id)55 def test_parse_multiple_values(self):56 request = test_utils.build_request('/_ah/api/foo?bar=baz&foo=bar&bar=foo')57 self.assertEqual('foo', request.path)58 self.assertEqual('bar=baz&foo=bar&bar=foo', request.query)59 self.assertEqual({'bar': ['baz', 'foo'], 'foo': ['bar']},60 request.parameters)61 self.assertEqual('', request.body)62 self.assertEqual({}, request.body_json)63 self.assertEqual([('CONTENT-TYPE', 'application/json')],64 request.headers.items())65 self.assertEqual(None, request.request_id)66 def test_is_rpc(self):67 request = test_utils.build_request('/_ah/api/rpc')68 self.assertEqual('rpc', request.path)69 self.assertEqual(None, request.query)70 self.assertTrue(request.is_rpc())71 def test_is_not_rpc(self):72 request = test_utils.build_request('/_ah/api/guestbook/v1/greetings/7')73 self.assertEqual('guestbook/v1/greetings/7', request.path)74 self.assertEqual(None, request.query)75 self.assertFalse(request.is_rpc())76 def teset_is_not_rpc_prefix(self):77 request = test_utils.build_request('/_ah/api/rpcthing')78 self.assertEqual('rpcthing', request.path)79 self.assertEqual(None, request.query)80 self.assertFalse(request.is_rpc())81 def test_batch(self):82 request = test_utils.build_request(83 '/_ah/api/rpc', '[{"method": "foo", "apiVersion": "v1"}]')84 self.assertTrue(request.is_batch())85 self.assertFalse(isinstance(request.body_json, list))86 def test_batch_too_large(self):87 """Verify that additional items are dropped if the batch size is > 1."""88 request = test_utils.build_request('/_ah/api/rpc',89 '[{"method": "foo", "apiVersion": "v1"},'90 '{"method": "bar", "apiversion": "v1"}]')91 self.assertTrue(request.is_batch())92 self.assertEqual(json.loads('{"method": "foo", "apiVersion": "v1"}'),93 request.body_json)94 def test_source_ip(self):95 body = '{}'96 path = '/_ah/api/guestbook/v1/greetings'97 env = {'SERVER_PORT': 42, 'REQUEST_METHOD': 'GET',98 'SERVER_NAME': 'localhost', 'HTTP_CONTENT_TYPE': 'application/json',99 'PATH_INFO': path, 'wsgi.input': cStringIO.StringIO(body)}100 request = api_request.ApiRequest(env)101 self.assertEqual(request.source_ip, None)102 env['REMOTE_ADDR'] = '1.2.3.4'103 request = api_request.ApiRequest(env)104 self.assertEqual(request.source_ip, '1.2.3.4')105 def test_copy(self):106 request = test_utils.build_request('/_ah/api/foo?bar=baz',107 '{"test": "body"}')108 copied = request.copy()109 self.assertEqual(request.headers.items(), copied.headers.items())110 self.assertEqual(request.body, copied.body)111 self.assertEqual(request.body_json, copied.body_json)112 self.assertEqual(request.path, copied.path)113 copied.headers['Content-Type'] = 'text/plain'114 copied.body = 'Got a whole new body!'115 copied.body_json = {'new': 'body'}116 copied.path = 'And/a/new/path/'117 self.assertNotEqual(request.headers.items(), copied.headers.items())118 self.assertNotEqual(request.body, copied.body)119 self.assertNotEqual(request.body_json, copied.body_json)120 self.assertNotEqual(request.path, copied.path)...

Full Screen

Full Screen

wsgi_request_info.py

Source:wsgi_request_info.py Github

copy

Full Screen

...36 self._request_id_to_instance = {}37 self._lock = threading.Lock()38 self._dispatcher = dispatcher39 @contextlib.contextmanager40 def request(self, environ, module_configuration):41 """A context manager that consumes a WSGI environ and returns a request id.42 with request_information.request(environ, app_info_external) as request_id:43 # Stubs will have access to the state associated with request_id only in44 # this context.45 send_request_to_runtime(request_id, ...)46 Args:47 environ: An environ dict for the request as defined in PEP-333.48 module_configuration: An application_configuration.ModuleConfiguration49 instance respresenting the current module configuration.50 Returns:51 A unique string id that will be associated with the request.52 """53 request_id = self.start_request(environ, module_configuration)54 yield request_id55 self.end_request(request_id)56 def start_request(self, environ, module_configuration):57 """Adds the WSGI to the state of the class and returns a request id.58 Args:59 environ: An environ dict for the request as defined in PEP-333.60 module_configuration: An application_configuration.ModuleConfiguration61 instance respresenting the current module configuration.62 Returns:63 A unique string id that will be associated with the request.64 """65 with self._lock:66 request_id = _choose_request_id()67 self._request_wsgi_environ[request_id] = environ68 self._request_id_to_module_configuration[69 request_id] = module_configuration70 return request_id71 def end_request(self, request_id):72 """Removes the information associated with given request_id."""73 with self._lock:74 del self._request_wsgi_environ[request_id]75 del self._request_id_to_module_configuration[request_id]76 if request_id in self._request_id_to_instance:77 del self._request_id_to_instance[request_id]78 def set_request_instance(self, request_id, instance):79 with self._lock:80 self._request_id_to_instance[request_id] = instance81 def get_request_url(self, request_id):82 """Returns the URL the request e.g. 'http://localhost:8080/foo?bar=baz'.83 Args:84 request_id: The string id of the request making the API call.85 Returns:...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1var request = require('request');2request(url, function (error, response, body) {3 if (!error && response.statusCode == 200) {4 }5})6var request = require('request');7request(url, function (error, response, body) {8 if (!error && response.statusCode == 200) {9 }10})11var request = require('request');12request(url, function (error, response, body) {13 if (!error && response.statusCode == 200) {14 }15})16var request = require('request');17request(url, function (error, response, body) {18 if (!error && response.statusCode == 200) {19 }20})

Full Screen

Using AI Code Generation

copy

Full Screen

1var request = require('request');2var express = require('express');3var app = express();4var router = express.Router();5var bodyParser = require('body-parser');6app.use(bodyParser.urlencoded({ extended: true }));7app.use(bodyParser.json());8var port = process.env.PORT || 8080;9var router = express.Router();10router.get('/', function(req, res) {11 res.json({ message: 'API Initialized!'});12});13app.use('/api', router);14app.listen(port, function() {15 console.log(`api running on port ${port}`);16});17app.use('/api', router);18app.listen(port, function() {19 console.log(`api running on port ${port}`);20});21var request = require('request');22var express = require('express');23var app = express();24var router = express.Router();25var bodyParser = require('body-parser');26app.use(bodyParser.urlencoded({ extended: true }));27app.use(bodyParser.json());28var port = process.env.PORT || 8080;29var router = express.Router();30router.get('/', function(req, res) {31 res.json({ message: 'API Initialized!'});32});33app.use('/api', router);34app.listen(port, function() {35 console.log(`api running on port ${port}`);36});37app.use('/api', router);38app.listen(port, function() {39 console.log(`api running on port ${port}`);40});41var request = require('request');42var express = require('express');

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 Best 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