def changeMovieSoap(Id, Title, Genre, Release_date, Rating, Album_ID): try: r = requests.get('http://web1:81/albums/' + Album_ID) if r.status_code == 200 and re.search('^[0-9]?$', Id): movies[int(Id)]['Title'] = Title movies[int(Id)]['Genre'] = Genre movies[int(Id)]['Rating'] = Rating movies[int(Id)]['Release_date'] = Release_date movies[int(Id)]['Album_ID'] = Album_ID movie = movies[int(Id)] else: raise Fault(faultcode='Client', faultstring='', faultactor='', detail={ 'Message': 'Error. Service Albums status is not 200.' }) return Movie(ID=movie["ID"], Title=movie["Title"], Genre=movie["Genre"], Rating=movie["Rating"], Release_date=movie["Release_date"], Album_ID=movie["Album_ID"]) except: raise Fault( faultcode='Client', faultstring='', faultactor='', detail={'Message': 'Error. Service Albums is not available.'})
def _from_soap(in_envelope_xml, xmlids=None): '''Parses the xml string into the header and payload.''' if xmlids: resolve_hrefs(in_envelope_xml, xmlids) if in_envelope_xml.tag != '{%s}Envelope' % ns.soap_env: raise Fault('Client.SoapError', 'No {%s}Envelope element was found!' % ns.soap_env) header_envelope = in_envelope_xml.xpath('e:Header', namespaces={'e': ns.soap_env}) body_envelope = in_envelope_xml.xpath('e:Body', namespaces={'e': ns.soap_env}) if len(header_envelope) == 0 and len(body_envelope) == 0: raise Fault('Client.SoapError', 'Soap envelope is empty!' % ns.soap_env) header = None if len(header_envelope) > 0: header = header_envelope[0].getchildren() body = None if len(body_envelope) > 0 and len(body_envelope[0]) > 0: body = body_envelope[0][0] return header, body
def deserialize(self, ctx, message): assert message in (self.REQUEST, self.RESPONSE) self.event_manager.fire_event('before_deserialize', ctx) if ctx.descriptor is None: raise Fault("Client", "Method %r not found." % ctx.method_request_string) # instantiate the result message if message is self.REQUEST: body_class = ctx.descriptor.in_message elif message is self.RESPONSE: body_class = ctx.descriptor.out_message else: raise Exception("what?") if ctx.in_error: ctx.in_error = Fault(**ctx.in_error) elif body_class: ctx.in_object = self._doc_to_object(body_class, ctx.in_body_doc, self.validator) else: ctx.in_object = [] self.event_manager.fire_event('after_deserialize', ctx)
def _from_soap(in_envelope_xml, xmlids=None, **kwargs): """Parses the xml string into the header and payload. """ ns_soap = kwargs.pop('ns', ns.NS_SOAP11_ENV) if xmlids: resolve_hrefs(in_envelope_xml, xmlids) if in_envelope_xml.tag != '{%s}Envelope' % ns_soap: raise Fault('Client.SoapError', 'No {%s}Envelope element was found!' % ns_soap) header_envelope = in_envelope_xml.xpath('e:Header', namespaces={'e': ns_soap}) body_envelope = in_envelope_xml.xpath('e:Body', namespaces={'e': ns_soap}) if len(header_envelope) == 0 and len(body_envelope) == 0: raise Fault('Client.SoapError', 'Soap envelope is empty!') header = None if len(header_envelope) > 0: header = header_envelope[0].getchildren() body = None if len(body_envelope) > 0 and len(body_envelope[0]) > 0: body = body_envelope[0][0] return header, body
def update_whois_info(id, wInfo): for entry in EntryContainer.entries: if entry.id == id: for contact in wInfo.contacts: if contactparser.contact_exists(contact.id): res, status = contactparser.edit_contact( contact.id, contact) if status != 200: raise Fault( faultcode="Server", faultstring= "Internal error when updating contacts!") else: res, status = contactparser.add_contact(contact) if status != 201: raise Fault(faultcode="Server", faultstring= "Internal error when adding contacts!") entry.id = wInfo.id entry.website = wInfo.website entry.ipaddress = wInfo.ipaddress entry.contacts = wInfo.contacts return wInfo raise Fault(faultcode="Client", faultstring="Could not find entry with given id!")
def get_whois_info(id): if id == None: raise Fault(faultcode="Client", faultstring="'id' field is empty") for entry in EntryContainer.entries: if entry.id == id: entry.updateContactList() return entry raise Fault(faultcode="Client", faultstring="Entry not found with given id!")
def find_infraction(self, id): try: infraction = Infraction.objects.get(pk=id) return infraction except IntegrityError as e: raise Fault(faultcode=str(e.args[0]), faultstring=e.args[1]) except Infraction.DoesNotExist: raise Fault(faultcode='404', faultstring=str('Infraction not exist'))
def find_municipality(self, id): try: municipality = Municipality.objects.get(pk=id) return municipality except IntegrityError as e: raise Fault(faultcode=str(e.args[0]), faultstring=e.args[1]) except Municipality.DoesNotExist: raise Fault(faultcode='404', faultstring=str('Municipality not exist'))
def change_password(ctx, UserName, Password): token = ctx.in_header.Token user_name = ctx.in_header.UserName if all([user_name, token]): result = handlers.change_password(UserName, Password, token) if result['result']: return result['message'] raise Fault(result['side'], result['message']) raise Fault('Client', 'Нет прав доступа.')
def set_stock_price(ctx, StockName, Price): user_name = ctx.in_header.UserName token = ctx.in_header.Token if all([user_name, token]): result = handlers.set_stock_price(user_name, token, StockName, Price) if result['result']: return result['message'] raise Fault(result['side'], result['message']) raise Fault('Client', 'Нет прав доступа.')
def delete_whois_info(id): for entry in EntryContainer.entries: if entry.id == id: EntryContainer.entries.remove(entry) return "Item deleted!" raise Fault(faultcode="Client", faultstring="Entry not found with given id!")
def handle_rpc(self, request, *args, **kwargs): """Handle rpc request. :params request: Django HttpRequest instance. :returns: HttpResponse instance. """ contexts = self.get_contexts(request) p_ctx, others = contexts[0], contexts[1:] if p_ctx.in_error: return self.handle_error(p_ctx, others, p_ctx.in_error) 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) self.get_out_object(p_ctx) if p_ctx.out_error: return self.handle_error(p_ctx, others, p_ctx.out_error) try: self.get_out_string(p_ctx) except Exception, 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)
def _parse_xml_string(xml_string, parser, charset=None): xml_string = iter(xml_string) chunk = next(xml_string) if isinstance(chunk, six.binary_type): string = b''.join(chain((chunk, ), xml_string)) else: string = ''.join(chain((chunk, ), xml_string)) if charset: string = string.decode(charset) try: try: root, xmlids = etree.XMLID(string, parser) except ValueError as e: logger.debug('ValueError: Deserializing from unicode strings with ' 'encoding declaration is not supported by lxml.') root, xmlids = etree.XMLID(string.encode(charset), parser) except XMLSyntaxError as e: logger_invalid.error("%r in string %r", e, string) raise Fault('Client.XMLSyntaxError', str(e)) return root, xmlids
def decompose_incoming_envelope(self, ctx, message): """Sets ``ctx.in_body_doc``, ``ctx.in_header_doc`` and ``ctx.method_request_string`` using ``ctx.in_document``. """ assert message in (ProtocolBase.REQUEST, ProtocolBase.RESPONSE) # set ctx.in_header ctx.transport.in_header_doc = None # use an rpc protocol if you want headers. doc = ctx.in_document ctx.in_header_doc = None ctx.in_body_doc = doc if len(doc) == 0: raise Fault("Client", "Empty request") logger.debug('\theader : %r' % (ctx.in_header_doc)) logger.debug('\tbody : %r' % (ctx.in_body_doc)) if not isinstance(doc, dict) or len(doc) != 1: raise ValidationError("Need a dictionary with exactly one key " "as method name.") mrs, = doc.keys() ctx.method_request_string = '{%s}%s' % (self.app.interface.get_tns(), mrs)
def test_ctor_defaults(self): fault = Fault() self.assertEqual(fault.faultcode, 'Server') self.assertEqual(fault.faultstring, 'Fault') self.assertEqual(fault.faultactor, '') self.assertEqual(fault.detail, None) self.assertEqual(repr(fault), "Fault(Server: 'Fault')")
def add_infraction(self, infraction): data = infraction.as_dict() try: inf = Infraction.objects.create(**data) sendmailnotification = SendMailNotifications() sendmailnotification.send_mail( list_emails=[data['offender_mail']], subject='Multa de Transito - Simit Services', content_xml='<h2>Multa de Transito N0: ' + str(inf.id) + '</h2></br><p>' + 'Estimado Infractor se ha creado una nueva Multa de Transito asociado al ciudadano ' + str(inf.offender_document_id) + ' - ' + str(inf.offender_name) + '</p></br><p>Realice el pago lo mas pronto posible para evitar sanciones</p>' + '<br><h3>SIMIT Services</h3>') return Infraction.objects.filter(id=inf.id).values( 'id', 'date', 'road_type', 'road_name', 'municipality', 'location', 'plate', 'infraction_code', 'vehicle_type', 'vehicle_service', 'offender_type', 'offender_document_type', 'offender_document_id', 'offender_name', 'offender_license_id', 'offender_address', 'offender_age', 'offender_phone', 'offender_mail', 'owner_document_type', 'owner_document_id', 'owner_name', 'company_id', 'company_name', 'transit_agent_name', 'transit_agent_entity', 'transit_agent_id', 'transit_agent_observations', 'document_url', 'state', 'state_date').first() except IntegrityError as e: raise Fault(faultcode=str(e.args[0]), faultstring=e.args[1])
def add_infraction(self, infraction): data = infraction.as_dict() try: inf = Infraction.objects.create(**data) sendmailnotification = Sendmail() sendmailnotification.send_mail( mail_list=[data['offender_mail']], subject='Multa de Transito - Simit Services', template='infraction_mail', offender_name=str(inf.offender_name), infraction_id=str(inf.id), date=str(inf.date), location=str(inf.location)) return Infraction.objects.filter(id=inf.id).values( 'id', 'date', 'road_type', 'road_name', 'municipality', 'location', 'plate', 'infraction_code', 'vehicle_type', 'vehicle_service', 'offender_type', 'offender_document_type', 'offender_document_id', 'offender_name', 'offender_license_id', 'offender_address', 'offender_age', 'offender_phone', 'offender_mail', 'owner_document_type', 'owner_document_id', 'owner_name', 'company_id', 'company_name', 'transit_agent_name', 'transit_agent_entity', 'transit_agent_id', 'transit_agent_observations', 'document_url', 'state', 'state_date').first() except IntegrityError as e: raise Fault(faultcode=str(e.args[0]), faultstring=e.args[1])
def _handle_rpc_body(self, p_ctx) -> typing.Optional[Fault]: """ Do the heavy lifting of the request handling here. This can be run in a thread. """ self.get_in_object(p_ctx) if p_ctx.in_error: logger.error(p_ctx.in_error) return p_ctx.in_error self.get_out_object(p_ctx) if p_ctx.out_error: logger.error(p_ctx.out_error) return p_ctx.out_error try: self.get_out_string(p_ctx) except Exception as e: p_ctx.out_error = Fault("Server", get_fault_string_from_exception(e)) logger.exception(p_ctx.out_error, exc_info=e) return p_ctx.out_error have_protocol_headers = (isinstance(p_ctx.out_protocol, HttpRpc) and p_ctx.out_header_doc is not None) if have_protocol_headers: p_ctx.transport.resp_headers.update(p_ctx.out_header_doc) return None
def addTicketToEvent(MovieName, NumberOfTickets): try: if (len(MovieName) == 0): raise Fault(faultcode='Client', faultstring='', faultactor='', detail={ 'Message': 'Error. Title not provided or is invalid' }) if (NumberOfTickets < 1): raise Fault( faultcode='Client', faultstring='', faultactor='', detail={'Error. TicNumber not provided or is invalid'}) requestData = {'title': MovieName} r = requests.get('http://service:81/movies', params=requestData) eventID = r.json() for i in range(0, NumberOfTickets): lastId = int(ticketsDB[len(ticketsDB) - 1]['ID']) + 1 ticket = { 'ID': str(lastId), 'Barcode': '', 'EID': eventID[0]['ID'], 'Current_Zone': '0', 'Rated': '0' } ticketsDB.append(ticket) eventTickets = [ tic for tic in ticketsDB if (tic['EID'] == str(eventID[0]['ID'])) ] m = [] for ticket in eventTickets: m.append( Ticket(ID=ticket["ID"], Barcode=ticket["Barcode"], EID=ticket["EID"], Current_Zone=ticket["Current_Zone"], Rated=ticket["Rated"])) return m except requests.RequestException as e: raise Fault(faultcode='503', faultstring='', faultactor='', detail={'Message': str(e)})
def process_request(self, ctx): """Takes a MethodContext instance. Returns the response to the request as a native python object. If the function throws an exception, it returns None and sets the exception object to ctx.out_error. Overriding this method would break event management. So this is not meant to be overridden unless you know what you're doing. """ try: # fire events self.event_manager.fire_event('method_call', ctx) if ctx.service_class is not None: ctx.service_class.event_manager.fire_event('method_call', ctx) # call the method ctx.out_object = self.call_wrapper(ctx) # out object is always an iterable of return values. see # MethodContext docstrings for more info if ctx.descriptor.body_style is not BODY_STYLE_WRAPPED or \ len(ctx.descriptor.out_message._type_info) <= 1: # the return value should already be wrapped by a sequence. ctx.out_object = [ctx.out_object] # Now that the processing is switched to the outgoing message, point # ctx.protocol to ctx.out_protocol ctx.protocol = ctx.outprot_ctx # fire events self.event_manager.fire_event('method_return_object', ctx) if ctx.service_class is not None: ctx.service_class.event_manager.fire_event( 'method_return_object', ctx) except Fault as e: if e.faultcode == 'Client' or e.faultcode.startswith('Client.'): logger_client.exception(e) else: logger.exception(e) ctx.out_error = e # fire events self.event_manager.fire_event('method_exception_object', ctx) if ctx.service_class is not None: ctx.service_class.event_manager.fire_event( 'method_exception_object', ctx) except Exception as e: logger.exception(e) ctx.out_error = Fault('Server', get_fault_string_from_exception(e)) # fire events self.event_manager.fire_event('method_exception_object', ctx) if ctx.service_class is not None: ctx.service_class.event_manager.fire_event( 'method_exception_object', ctx)
def edit_municipality(self, municipality): data = municipality.as_dict() try: Municipality.objects.filter(id=data['id']).update(**data) return Municipality.objects.filter(id=data['id']).values( 'id', 'dian_code', 'name').first() except IntegrityError as e: raise Fault(faultcode=str(e.args[0]), faultstring=e.args[1])
def Login(ctx, _this, userName, password): self = ctx.udc if (userName == 'root' and password == 'Embe1mpls') or \ (userName == 'u' and password == 'p') or \ (userName == 'user' and password == 'pass'): self.auth = serializers.AuthResponse() self.auth.key = self.login_id return self.auth.serialize() raise Fault('Client.Authentication', 'Authorization failed')
def _eb_deferred(ret, request, p_ctx, others, resource): app = p_ctx.app # DRY this with what's in Application.process_request if issubclass(ret.type, Redirect): try: ret.value.do_redirect() # Now that the processing is switched to the outgoing message, # point ctx.protocol to ctx.out_protocol p_ctx.protocol = p_ctx.outprot_ctx _cb_deferred(None, request, p_ctx, others, resource, cb=False) # fire events app.event_manager.fire_event('method_redirect', p_ctx) if p_ctx.service_class is not None: p_ctx.service_class.event_manager.fire_event( 'method_redirect', p_ctx) except Exception as e: logger_server.exception(e) p_ctx.out_error = Fault('Server', get_fault_string_from_exception(e)) # fire events app.event_manager.fire_event('method_redirect_exception', p_ctx) if p_ctx.service_class is not None: p_ctx.service_class.event_manager.fire_event( 'method_redirect_exception', p_ctx) elif issubclass(ret.type, Fault): p_ctx.out_error = ret.value ret = resource.handle_rpc_error(p_ctx, others, p_ctx.out_error, request) # fire events app.event_manager.fire_event('method_exception_object', p_ctx) if p_ctx.service_class is not None: p_ctx.service_class.event_manager.fire_event( 'method_exception_object', p_ctx) request.write(ret) else: p_ctx.out_error = ret.value ret.printTraceback() p_ctx.out_error = InternalError(ret.value) # fire events app.event_manager.fire_event('method_exception_object', p_ctx) if p_ctx.service_class is not None: p_ctx.service_class.event_manager.fire_event( 'method_exception_object', p_ctx) request.finish()
def changeMovieAlbumSoap(Id, Title, Genre, Release_date, Rating, Album, AlbumGenre, Producer, Artist): if Artist != '': try: for i in range(0, len(movies)): if movies[i]["ID"] == Id: r = requests.put('http://web1:81/albums/' + movies[i]["Album_ID"], json={ "Album": Album, "Artist": Artist, "Genre": AlbumGenre, "Producer": Producer }) if r.status_code == 200 and re.search('^[0-9]?$', Id): movies[i]['Title'] = Title movies[i]['Genre'] = Genre movies[i]['Rating'] = Rating movies[i]['Release_date'] = Release_date movie = movies[i] else: raise Fault( faultcode='Client', faultstring='', faultactor='', detail={ 'Message': 'Error. Service Albums status is not 200.' }) return Movie(ID=movie["ID"], Title=movie["Title"], Genre=movie["Genre"], Rating=movie["Rating"], Release_date=movie["Release_date"], Album_ID=movie["Album_ID"]) except: raise Fault(faultcode='Client', faultstring='', faultactor='', detail={ 'Message': 'Error. Service Albums is not available.' })
def create_in_document(self, ctx, in_string_encoding=None): """Sets ``ctx.in_document`` using ``ctx.in_string``.""" if in_string_encoding is None: in_string_encoding = 'UTF-8' try: ctx.in_document = json.loads(''.join(ctx.in_string).decode( in_string_encoding)) except JSONDecodeError, e: raise Fault('Client.JsonDecodeError', repr(e))
def test_to_parent_w_detail(self): from lxml.etree import Element element = Element('testing') detail = Element('something') fault = Fault(detail=detail) cls = Fault XmlDocument().to_parent(None, cls, fault, element, 'urn:ignored') (child,) = element.getchildren() self.assertTrue(child.find('detail').find('something') is detail)
def create_in_document(self, ctx, charset=None): """Uses the iterable of string fragments in ``ctx.in_string`` to set ``ctx.in_document``.""" string = _bytes_join(ctx.in_string) try: try: ctx.in_document = etree.fromstring(string, self.parser) except XMLSyntaxError, e: logger.error(string) raise Fault('Client.XMLSyntaxError', str(e)) except ValueError: try: ctx.in_document = etree.fromstring(string.decode(charset), self.parser) except XMLSyntaxError, e: logger.error(string) raise Fault('Client.XMLSyntaxError', str(e))
def add_whois_info(wInfo): for entry in EntryContainer.entries: if entry.id == wInfo.id: raise Fault(faultcode="Client", faultstring="Item with given ID already exists") for contact in wInfo.contacts: if contactparser.contact_exists(contact.id): res, status = contactparser.edit_contact(contact.id, contact) if status != 200: raise Fault( faultcode="Server", faultstring="Internal error when updating contacts!") else: res, status = contactparser.add_contact(contact) if status != 201: raise Fault( faultcode="Server", faultstring="Internal error when adding contacts!") EntryContainer.entries.append(wInfo) return wInfo
def create_in_document(self, ctx, in_string_encoding=None): """Sets ``ctx.in_document`` using ``ctx.in_string``.""" if in_string_encoding is None: in_string_encoding = 'UTF-8' try: ctx.in_document = yaml.load(b''.join(ctx.in_string).decode( in_string_encoding), **self.in_kwargs) except ParserError as e: raise Fault('Client.YamlDecodeError', repr(e))
def GetSiteInfoObject(ctx, site, authToken=None): try: siteInfoResponse = wof_inst.create_get_site_info_response(site) outStream = io.StringIO() siteInfoResponse.export( outStream, 0, name_="sitesResponse", namespacedef_=NSDEF ) return outStream.getvalue() except Exception as inst: if type(inst) == Fault: raise inst else: raise Fault(faultstring=str(inst))