def CreateFlightOrder(ctx, CustomerName, DepartureDate, FlightNumber, NumberOfTickets, FlightClass): new_order = flights_db.create_flight_order(CustomerName, DepartureDate, FlightNumber, NumberOfTickets, FlightClass) if (new_order==-1): raise Fault(faultcode='SeatsAvailable.Error', faultstring='No more seats available for flight ' + str(FlightNumber)) elif (new_order==-2): raise Fault(faultcode='FlightNumber.Error', faultstring='Aucun vol ' + str(FlightNumber)) elif (new_order==-3): raise Fault(faultcode='SeatsAvailable.Error', faultstring='Aucun dispo ' + str(FlightNumber)) else: return (new_order)
def fill_wallet(ctx, telephone, id_document, amount): try: user = User.objects.get(id_document=id_document) except user.DoesNotExist as e: raise Fault(faultstring=str(e)) wallet = Wallet.objects.filter(user=user) wallet = wallet.first() try: wallet.amount = amount + wallet.amount wallet.save() return "true" except IntegrityError as e: raise Fault(faultcode=str(e[0]), faultstring=str(e[1]))
def create_purchase_order(ctx, total_amount, id, purchase_token): wallet = Wallet.objects.filter(user__id=id) if not wallet: return "wallet doesn't exist" purchases = PurchaseOrder.objects.filter(wallet= wallet.\ first(),status__status=False) totals = purchases.aggregate(sum=Sum('total_amount')).get('sum') or 0 wallet = wallet.first() funds = wallet.amount - totals if funds < total_amount: return "insufficient funds" +\ "because the sum of preorders" status = Status.objects.get_or_create(status=False)[0] if len(purchase_token) != 6: return "Token must be 6 digit" try: purchase = PurchaseOrder.objects.create( total_amount=total_amount, purchase_token=purchase_token, wallet=wallet, status=status) return "true" except IntegrityError as e: raise Fault(faultcode=str(e[0]), faultstring=str(e[1]))
def add_recommendation(self, activity_id, recommendation): try: activity = Activity.objects.get(pk=activity_id) if type(activity.is_violated) == bytes: activity.is_violated = bool.from_bytes(activity.is_violated, "big") if type(activity.is_normal) == bytes: activity.is_normal = bool.from_bytes(activity.is_normal, "big") if activity.is_normal: raise Exception("Activity is labeled as normal") latest_activity = ActivityRecommendation.objects.latest('id') latest_id = latest_activity.id + 1 activity_recommendation = ActivityRecommendation() activity_recommendation.id = latest_id activity_recommendation.activity_id = activity.id activity_recommendation.recommendation = recommendation activity_recommendation.save(force_insert=True) except ObjectDoesNotExist as ex: raise ResourceNotFoundError('Activity %s not found' % activity_id) except Exception as ex: raise Fault(faultstring=str(ex))
def create_in_document(self, ctx, charset=None): if isinstance(ctx.transport, HttpTransportContext): http_verb = ctx.transport.get_request_method() if http_verb == "OPTIONS": ctx.transport.resp_headers['allow'] = "POST, OPTIONS" ctx.transport.respond(HTTP_200) raise Fault("") return Soap11.create_in_document(self, ctx, charset)
def get_user(ctx, email, password): try: user = User.objects.get(email=email) if check_password_hash(user.password, password): return "true" else: return "false" except User.DoesNotExist as e: raise Fault(faultstring=str(e))
def data_user(ctx, email): try: user = User.objects.get(email=email) return [ "true", str(user.id), str(user.id_document), str(user.name), str(user.lastname), str(user.email), str(user.password), str(user.telephone) ] except User.DoesNotExist as e: raise Fault(faultstring=str(e))
def test_raise_fault(self, mock_create_data): """ Test raised `Fault` to be communicated as a StUF fault message. """ mock_create_data.side_effect = Fault(faultstring='The error message', detail='Some details about the error.') xml = self._simple_request() self._validate_stuf_fault_xml( xml, BerichtcodeChoices.fo02, ServerFoutChoices.stuf058, 'server', ServerFoutChoices.values.get(ServerFoutChoices.stuf058), stuf_details='Some details about the error.' )
def register_user(ctx, name, lastname, telephone, password, id_document, email): try: user = User.objects.create( telephone=telephone, lastname=lastname, email=email, id_document=id_document, password=generate_password_hash(password), name=name) wallet = Wallet(user=user, amount=0) wallet.save() return "true" except IntegrityError as e: raise Fault(faultcode=str(e[0]), faultstring=str(e[1]))
def verify_token_and_purchase(ctx, token): try: # user = User.objects.filter(id=id) purchase = PurchaseOrder.objects.get(purchase_token=token, status__status=False) amount_to_discount = purchase.total_amount wallet = purchase.wallet wallet.amount = wallet.amount - amount_to_discount status = Status.objects.get_or_create(status=True) purchase.status = status[0] purchase.save() wallet.save() return "true" except PurchaseOrder.DoesNotExist as e: raise Fault(faultstring=str(e))
def client_fault(ctx): raise Fault("Client", "Client side fault example")
def server_fault(ctx): raise Fault("Server", "Server side fault example.")
def soap_exception(): raise Fault("Client.Plausible.issue", "A plausible fault", 'http://faultactor.example.com', detail={'some': 'extra info'})
def UpdateFlightOrder(ctx, OrderNumber, Class, CustomerName, NumberOfTickets): rows = flights_db.update_flight_order(OrderNumber, Class, CustomerName, NumberOfTickets) if (rows == -1): raise Fault(faultcode='Class.Error', faultstring='Class not found ' + Class) else: return (str(rows > 0))
def server_fault(ctx): raise Fault("Server", "boo and you know it!")
def handle_rpc(self, req_env, start_response): initial_ctx = WsgiMethodContext(self, req_env, self.app.out_protocol.mime_type) self.event_manager.fire_event('wsgi_call', initial_ctx) initial_ctx.in_string, in_string_charset = \ self.__reconstruct_wsgi_request(req_env) contexts = self.generate_contexts(initial_ctx, in_string_charset) p_ctx, others = contexts[0], contexts[1:] # TODO: rate limiting p_ctx.active = True if p_ctx.in_error: return self.handle_error(p_ctx, others, p_ctx.in_error, start_response) self.get_in_object(p_ctx) if p_ctx.in_error: logger.error(p_ctx.in_error) return self.handle_error(p_ctx, others, p_ctx.in_error, start_response) self.get_out_object(p_ctx) if p_ctx.out_error: return self.handle_error(p_ctx, others, p_ctx.out_error, start_response) assert p_ctx.out_object is not None g = next(iter(p_ctx.out_object)) is_generator = len(p_ctx.out_object) == 1 and isgenerator(g) # if the out_object is a generator function, this hack makes the user # code run until first yield, which lets it set response headers and # whatnot before calling start_response. It's important to run this # here before serialization as the user function can also set output # protocol. Is there a better way? if is_generator: first_obj = next(g) p_ctx.out_object = ( chain((first_obj,), g), ) if p_ctx.transport.resp_code is None: p_ctx.transport.resp_code = HTTP_200 try: self.get_out_string(p_ctx) except Exception as e: logger.exception(e) p_ctx.out_error = Fault('Server', get_fault_string_from_exception(e)) return self.handle_error(p_ctx, others, p_ctx.out_error, start_response) if isinstance(p_ctx.out_protocol, HttpRpc) and \ p_ctx.out_header_doc is not None: p_ctx.transport.resp_headers.update(p_ctx.out_header_doc) if p_ctx.descriptor and p_ctx.descriptor.mtom: # when there is more than one return type, the result is # encapsulated inside a list. when there's just one, the result # is returned in a non-encapsulated form. the apply_mtom always # expects the objects to be inside an iterable, hence the # following test. out_type_info = p_ctx.descriptor.out_message._type_info if len(out_type_info) == 1: p_ctx.out_object = [p_ctx.out_object] p_ctx.transport.resp_headers, p_ctx.out_string = apply_mtom( p_ctx.transport.resp_headers, p_ctx.out_string, p_ctx.descriptor.out_message._type_info.values(), p_ctx.out_object, ) self.event_manager.fire_event('wsgi_return', p_ctx) if self.chunked: # the user has not set a content-length, so we delete it as the # input is just an iterable. if 'Content-Length' in p_ctx.transport.resp_headers: del p_ctx.transport.resp_headers['Content-Length'] else: p_ctx.out_string = [''.join(p_ctx.out_string)] try: len(p_ctx.out_string) p_ctx.transport.resp_headers['Content-Length'] = \ str(sum([len(a) for a in p_ctx.out_string])) except TypeError: pass start_response(p_ctx.transport.resp_code, _gen_http_headers(p_ctx.transport.resp_headers)) retval = chain(p_ctx.out_string, self.__finalize(p_ctx)) try: process_contexts(self, others, p_ctx, error=None) except Exception as e: # Report but ignore any exceptions from auxiliary methods. logger.exception(e) return retval
def soap_exception(): raise Fault("Plausible", "A plausible fault", 'http://faultactor.example.com')
def client_fault(ctx): raise Fault("Client", "zzzz...")