Beispiel #1
0
    def file_to_string_iterable(self, cls, value):
        if value.data is None:
            if value.handle is None:
                assert value.path is not None, "You need to write data to " \
                         "persistent storage first if you want to read it back."

                try:
                    path = value.path
                    if not isabs(value.path):
                        path = join(value.store, value.path)
                    f = open(path, 'rb')
                except IOError as e:
                    if e.errno == errno.ENOENT:
                        raise ResourceNotFoundError(value.path)
                    else:
                        raise InternalError("Error accessing requested file")

            else:
                f = value.handle
                f.seek(0)

            return _file_to_iter(f)

        else:
            if isinstance(value.data, (list,tuple)) and \
                                                isinstance(value.data[0], mmap):
                return _file_to_iter(value.data[0])
            else:
                return iter(value.data)
    def update_movie(ctx, movie_id, title):
        con = psycopg2.connect(con_str)
        cur = con.cursor(cursor_factory=RealDictCursor)
        cur.execute(
            """SELECT id, title FROM imdb_movies_api WHERE id = %(movie_id)s""",
            {"movie_id": movie_id.zfill(7)})
        res = cur.fetchall()
        if len(res) == 0:
            raise ResourceNotFoundError(faultstring='Not Found',
                                        detail='Not Found')
        movie = {
            "id": movie_id,
            "title": title if title else res[0]['title'],
        }

        for v in [('id', str), ('title', str)]:
            if movie[v[0]] and not isinstance(movie[v[0]], v[1]):
                raise InvalidInputError(faultstring='Bad Request',
                                        detail='Bad Request')

        cur.execute(
            """update imdb_movies_api set title=%(title)s where id=%(id)s""",
            movie)
        con.commit()

        cur.close()
        con.close()
        return movie
Beispiel #3
0
    def modify_user(user):
        global user_database

        if not (user.userid in user_database):
            raise ResourceNotFoundError(user.userid)

        user_database[user.userid] = user
Beispiel #4
0
    def delete_user(userid):
        global user_database

        if not (userid in user_database):
            raise ResourceNotFoundError(userid)

        del user_database[userid]
Beispiel #5
0
    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 ResourceNotFoundError(ctx.method_request_string)

        # instantiate the result message
        if message is self.REQUEST:
            body_class = unwrap_messages(ctx.descriptor.in_message,
                                         self.skip_depth)
        elif message is self.RESPONSE:
            body_class = unwrap_messages(ctx.descriptor.out_message,
                                         self.skip_depth)
        if body_class:
            # assign raw result to its wrapper, result_message
            result_class = ctx.descriptor.in_message
            value = ctx.in_body_doc.get(result_class.get_type_name(), None)
            result_message = self._doc_to_object(result_class, value,
                                                 self.validator)

            ctx.in_object = result_message

        else:
            ctx.in_object = []

        self.event_manager.fire_event('after_deserialize', ctx)
Beispiel #6
0
    def file_to_bytes_iterable(self, cls, value, **_):
        if value.data is not None:
            if isinstance(value.data, (list, tuple)) and \
                                                isinstance(value.data[0], mmap):
                return _file_to_iter(value.data[0])
            return iter(value.data)

        if value.handle is not None:
            f = value.handle
            f.seek(0)
            return _file_to_iter(f)

        assert value.path is not None, "You need to write data to " \
                 "persistent storage first if you want to read it back."

        try:
            path = value.path
            if not isabs(value.path):
                path = join(value.store, value.path)
                assert abspath(path).startswith(value.store), \
                                                 "No relative paths are allowed"
            return _file_to_iter(open(path, 'rb'))

        except IOError as e:
            if e.errno == errno.ENOENT:
                raise ResourceNotFoundError(value.path)
            else:
                raise InternalError("Error accessing requested file")
Beispiel #7
0
    def call_wrapper(self, ctx):
        """This method calls the call_wrapper method in the service definition.
        This can be overridden to make an application-wide custom exception
        management.
        """

        if ctx.descriptor.body_style is BODY_STYLE_BARE:
            ctx.in_object = [ctx.in_object]
        elif ctx.descriptor.body_style is BODY_STYLE_EMPTY:
            ctx.in_object = []

        # service rpc
        if ctx.descriptor.service_class is not None:
            return ctx.descriptor.service_class.call_wrapper(ctx)

        # class rpc
        cls = ctx.descriptor.parent_class
        if cls.__orig__ is not None:
            cls = cls.__orig__
        inst = cls.__respawn__(ctx)
        if inst is None:
            raise ResourceNotFoundError(
                '{%s}%s' % (cls.get_namespace(), cls.get_type_name()))
        args = ctx.in_object[1:]
        if ctx.function is not None:
            if ctx.descriptor.no_ctx:
                return ctx.function(inst, *args)
            else:
                return ctx.function(inst, ctx, *args)
Beispiel #8
0
    def deserialize(self, ctx, message):
        assert message in (self.REQUEST, )

        self.event_manager.fire_event('before_deserialize', ctx)

        if ctx.descriptor is None:
            raise ResourceNotFoundError(ctx.method_request_string)

        req_enc = getattr(ctx.transport, 'request_encoding', None)
        if req_enc is None:
            req_enc = ctx.in_protocol.default_string_encoding

        if ctx.descriptor.in_header is not None:
            # HttpRpc supports only one header class
            in_header_class = ctx.descriptor.in_header[0]
            ctx.in_header = self.simple_dict_to_object(ctx.in_header_doc,
                                                       in_header_class,
                                                       self.validator,
                                                       req_enc=req_enc)

        if ctx.descriptor.in_message is not None:
            ctx.in_object = self.simple_dict_to_object(
                ctx.in_body_doc,
                ctx.descriptor.in_message,
                self.validator,
                req_enc=req_enc)

        self.event_manager.fire_event('after_deserialize', ctx)
Beispiel #9
0
 def update_book_copies(ctx, isbn, copies):
     try:
         book = BookModel.objects.filter(isbn=isbn).first()
         book.copies += copies
         book.save()
     except BookModel.DoesNotExist:
         raise ResourceNotFoundError('Book')
Beispiel #10
0
    def generate_method_contexts(self, ctx):
        """Generates MethodContext instances for every callable assigned to the
        given method handle.

        The first element in the returned list is always the primary method
        context whereas the rest are all auxiliary method contexts.
        """

        call_handles = self.get_call_handles(ctx)
        if len(call_handles) == 0:
            raise ResourceNotFoundError('Method %r not found.' %
                                                      ctx.method_request_string)

        retval = []
        for sc, d in call_handles:
            c = copy(ctx)

            assert d != None

            c.descriptor = d
            c.service_class = sc

            retval.append(c)

        return retval
Beispiel #11
0
    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 ResourceNotFoundError(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

        if body_class:
            # assign raw result to its wrapper, result_message
            doc = ctx.in_body_doc

            class_name = self.get_class_name(body_class)
            if self.ignore_wrappers:
                doc = doc.get(class_name, None)
            result_message = self._doc_to_object(body_class, doc,
                                                 self.validator)
            ctx.in_object = result_message

        else:
            ctx.in_object = []

        self.event_manager.fire_event('after_deserialize', ctx)
Beispiel #12
0
 def faz_jogada(ctx, id, username, password, jogada, cidade, cor):
     try:
         session = Session.objects.get(session_hash=id)
         session_state = SessionState.objects.get(session=session)
         city = City.objects.get(name=cidade)
         city_state = CityState.objects.get(session=session_state,
                                            city=city)
         res = ''
         user = authenticate(username=username, password=password)
         if user is not None:
             player_state = PlayerState.objects.get(session=session_state,
                                                    user=user.id)
             http_request = HttpRequest()
             http_request.user = user
             http_request.method = "POST"
             if jogada == 'move':
                 http_request.POST = QueryDict.fromkeys(['city'],
                                                        value=city.id)
                 request = Request(http_request)
                 request.user = user
                 response = update_player_state(request, player_state.id,
                                                session.session_hash)
                 res = "Aceite" if response.status_code == 200 else "Não aceite"
             elif jogada == 'treat':
                 key = []
                 value = 0
                 if cor == "Black":
                     key.append('black_cubes')
                     value = city_state.black_cubes - 1
                 elif cor == "Yellow":
                     key.append("yellow_cubes")
                     value = city_state.yellow_cubes - 1
                 elif cor == "Red":
                     key.append("red_cubes")
                     value = city_state.red_cubes - 1
                 else:
                     key.append("blue_cubes")
                     value = city_state.blue_cubes - 1
                 http_request.POST = QueryDict.fromkeys(key, value=value)
                 request = Request(http_request)
                 request.user = user
                 response = update_city_state(request, city_state.id,
                                              session.session_hash)
                 res = "Aceite" if response.status_code == 200 else "Não aceite"
             else:
                 http_request.POST = QueryDict.fromkeys(
                     ['research_station'], value=True)
                 request = Request(http_request)
                 request.user = user
                 response = update_city_state(request, city_state.id,
                                              session.session_hash)
                 res = "Aceite" if response.status_code == 200 else "Não aceite"
             return res
         else:
             raise InvalidCredentialsError('User')
     except ObjectDoesNotExist:
         raise ResourceNotFoundError('Session')
Beispiel #13
0
    def set_method_descriptor(self, ctx):
        """DEPRECATED! Use :func:`generate_method_contexts` instead.

        Method to be overriden to perform any sort of custom matching between
        the method_request_string and the methods.
        """

        name = ctx.method_request_string
        if not name.startswith("{"):
            name = '{%s}%s' % (self.app.interface.get_tns(), name)

        ctx.service_class = self.app.interface.service_mapping.get(name, None)
        if ctx.service_class is None:
            raise ResourceNotFoundError('Method %r not bound to a service class.'
                                                                        % name)

        ctx.descriptor = ctx.app.interface.method_mapping.get(name, None)
        if ctx.descriptor is None:
            raise ResourceNotFoundError('Method %r not found.' % name)
Beispiel #14
0
    def call_wrapper(self, ctx):
        """This is the application-wide exception transforming function."""

        try:
            return Application.call_wrapper(self, ctx)

        except NoResultFound, e:
            logger.exception(e)
            ctx.out_string = ["Resource not found"]
            raise ResourceNotFoundError()  # Return HTTP 404
Beispiel #15
0
    def call_wrapper(self, ctx):
        try:
            return ctx.service_class.call_wrapper(ctx)

        except NoResultFound:
            raise ResourceNotFoundError(ctx.in_object)

        except Fault, e:
            logging.error(e)
            raise
 def get_movie(ctx, movie_id):
     con = psycopg2.connect(con_str)
     cur = con.cursor(cursor_factory=RealDictCursor)
     cur.execute(
         """SELECT id, title FROM imdb_movies_api WHERE id = %(movie_id)s""",
         {"movie_id": movie_id.zfill(7)})
     res = cur.fetchall()
     cur.close()
     con.close()
     if len(res) == 0:
         raise ResourceNotFoundError(faultstring='Not Found',
                                     detail='Not Found')
     return res
Beispiel #17
0
    def _wrap(*args, **kwargs):
        self = args[0]

        try:
            retval = f(*args, **kwargs)
            self.session.expunge_all()
            return retval

        except NoResultFound:
            raise ResourceNotFoundError(self.ctx.in_object)

        except Fault, e:
            log.err()
            raise
Beispiel #18
0
    def get_user(userid):
        global user_database

        # If rely on dict lookup raising KeyError here, you'll return an
        # internal error to the client, which tells the client that there's
        # something wrong in the server. However in this case, KeyError means
        # invalid request, so it's best to return a client error.

        # For the HttpRpc case, internal error is 500 whereas
        # ResourceNotFoundError is 404.
        if not (userid in user_database):
            raise ResourceNotFoundError(userid)

        return user_database[userid]
Beispiel #19
0
    def devolve_book_loan(ctx, isbn):
        try:
            book = BookModel.objects.filter(isbn=isbn).first()
        except BookModel.DoesNotExist:
            raise ResourceNotFoundError('Book')

        book_loan = BookLoanModel.objects.filter(
            book=book,
            return_date=None
        ).last()

        book_loan.return_date = datetime.datetime.now()
        book_loan.save()
        return book_loan
Beispiel #20
0
    def call_wrapper(self, ctx):
        try:
            return ctx.service_class.call_wrapper(ctx)

        except NoResultFound:
            raise ResourceNotFoundError(ctx.in_object)

        except Fault as e:
            log.err()
            raise

        except Exception as e:
            log.err()
            # This should not happen! Let the team know via email!
            if EXCEPTION_ADDRESS:
                email_exception(EXCEPTION_ADDRESS)
            raise InternalError(e)
Beispiel #21
0
    def info_jogo(ctx, session_hash):
        try:
            session = Session.objects.get(session_hash=session_hash)
            session_state = SessionState.objects.get(session=session)
            city_states = CityState.objects.all().filter(session=session_state)
            player_states = PlayerState.objects.all().filter(
                session=session_state)
            res = {'research_centers': {}, 'players': {}, 'cities': {}}

            for city_state in city_states:
                city = city_state.city
                if city_state.black_cubes > 0 or city_state.yellow_cubes > 0 or city_state.red_cubes > 0 or city_state.blue_cubes > 0:
                    res['cities'][city.name.replace(' ', '_')] = {}
                if city_state.black_cubes > 0:
                    res['cities'][city.name.replace(
                        ' ', '_')]['Black_Disease'] = city_state.black_cubes
                if city_state.yellow_cubes > 0:
                    res['cities'][city.name.replace(
                        ' ', '_')]['Yellow_Disease'] = city_state.yellow_cubes
                if city_state.red_cubes > 0:
                    res['cities'][city.name.replace(
                        ' ', '_')]['Red_Disease'] = city_state.red_cubes
                if city_state.blue_cubes > 0:
                    res['cities'][city.name.replace(
                        ' ', '_')]['Blue_Disease'] = city_state.blue_cubes
                if city_state.research_station:
                    res['research_centers'][city.name.replace(' ', '_')] = {}

            for player in player_states:
                player_city = player.city
                user = player.user
                res['players'][user.username] = {
                    'position': player_city.name,
                    'neighbour_cities': {}
                }

                all_neighbours = player_city.connections.all()
                for city in all_neighbours:
                    res['players'][user.username]['neighbour_cities'][
                        city.name.replace(' ', '_')] = {}
            print(res)
            return res
        except ObjectDoesNotExist:
            raise ResourceNotFoundError('Session')
 def CreateEvent(ctx, CreateEventInput: EventTicketRequest):
     create_event_url = ctx.udc.create_event_url
     # Get auth_key, event, list section, callback URL
     auth_key = ctx.udc.token
     event = CreateEventInput.event
     list_section = CreateEventInput.list_section
     callback_type = CreateEventInput.callback_type
     callback = CreateEventInput.callback
     # Create payload and request to create_event_url
     payload = create_request(event, list_section, callback, callback_type,
                              auth_key)
     camunda_resp = requests.post(create_event_url, json=payload)
     if camunda_resp.status_code == 404:
         raise ResourceNotFoundError(camunda_resp)
     elif not camunda_resp.ok:
         raise InternalError(Exception("Spyne Server Error"))
     return EventTicketResp(
         200,
         "Processing your input. Detail will be given to your callback URL")
Beispiel #23
0
    def put_user(ctx, user):
        if user.id is None:
            ctx.udc.session.add(user)
            ctx.udc.session.flush()  # so that we get the user.id value

        else:
            if ctx.udc.session.query(User).get(user.id) is None:
                # this is to prevent the client from setting the primary key
                # of a new object instead of the database's own primary-key
                # generator.
                # Instead of raising an exception, you can also choose to
                # ignore the primary key set by the client by silently doing
                # user.id = None
                raise ResourceNotFoundError('user.id=%d' % user.id)

            else:
                ctx.udc.session.merge(user)

        return user.id
Beispiel #24
0
    def deserialize(self, ctx, message):
        assert message in (self.REQUEST,)

        self.event_manager.fire_event('before_deserialize', ctx)

        if ctx.descriptor is None:
            raise ResourceNotFoundError(ctx.method_request_string)

        if ctx.descriptor.in_header is not None:
            # HttpRpc supports only one header class
            in_header_class = ctx.descriptor.in_header[0]
            ctx.in_header = self.flat_dict_to_object(ctx.in_header_doc,
                                                in_header_class, self.validator)

        if ctx.descriptor.in_message is not None:
            ctx.in_object = self.flat_dict_to_object(ctx.in_body_doc,
                                      ctx.descriptor.in_message, self.validator)

        self.event_manager.fire_event('after_deserialize', ctx)
Beispiel #25
0
    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 ResourceNotFoundError(ctx.method_request_string)

        if ctx.protocol.error:
            ctx.in_object = None
            ctx.in_error = self._doc_to_object(ctx, Fault, ctx.in_body_doc)

        else:
            if message is self.REQUEST:
                header_class = ctx.descriptor.in_header
                body_class = ctx.descriptor.in_message

            elif message is self.RESPONSE:
                header_class = ctx.descriptor.out_header
                body_class = ctx.descriptor.out_message

            # decode header objects
            if (ctx.in_header_doc is not None and header_class is not None):
                headers = [None] * len(header_class)
                for i, (header_doc, head_class) in enumerate(
                                          zip(ctx.in_header_doc, header_class)):
                    if header_doc is not None and i < len(header_doc):
                        headers[i] = self._doc_to_object(ctx, head_class,
                                                                     header_doc)

                if len(headers) == 1:
                    ctx.in_header = headers[0]
                else:
                    ctx.in_header = headers
            # decode method arguments
            if ctx.in_body_doc is None:
                ctx.in_object = [None] * len(body_class._type_info)
            else:
                ctx.in_object = self._doc_to_object(ctx, body_class,
                                                                ctx.in_body_doc)

        self.event_manager.fire_event('after_deserialize', ctx)
Beispiel #26
0
    def get(ctx, file_name):
        path = os.path.join(os.path.abspath('./files'), file_name)
        if not path.startswith(os.path.abspath('./files')):
            raise ValidationError(file_name)

        try:
            f = open(path, 'r')
        except IOError:
            raise ResourceNotFoundError(file_name)

        ctx.transport.resp_headers['Content-Disposition'] = (
            'attachment; filename=%s;' % file_name)

        data = f.read(BLOCK_SIZE)
        while len(data) > 0:
            yield data

            data = f.read(BLOCK_SIZE)

        f.close()
Beispiel #27
0
    def _wrap(*args, **kwargs):
        self = args[0]

        try:
            retval = f(*args, **kwargs)
            self.session.expunge_all()
            return retval

        except NoResultFound:
            raise ResourceNotFoundError(self.ctx.in_object)

        except Fault as e:
            log.err()
            raise

        except Exception as e:
            log.err()
            # This should not happen! Let the team know via email!
            email_exception(EXCEPTION_ADDRESS)
            raise InternalError(e)
Beispiel #28
0
 def __init__(self, value):
     ResourceNotFoundError.__init__(self,
             faultstring='Value %r not found' % value
         )
Beispiel #29
0
    def del_user(ctx, user_id):
        count = ctx.udc.session.query(User).filter_by(id=user_id).count()
        if count == 0:
            raise ResourceNotFoundError(user_id)

        ctx.udc.session.query(User).filter_by(id=user_id).delete()
Beispiel #30
0
 def get_container(ctx, pk):
     try:
         return FieldContainer.objects.get(pk=pk)
     except FieldContainer.DoesNotExist:
         raise ResourceNotFoundError('Container_submitseq')
Beispiel #31
0
        def del_(ctx, obj_id):
            count = ctx.udc.session.query(T).filter_by(id=obj_id).count()
            if count == 0:
                raise ResourceNotFoundError(obj_id)

            ctx.udc.session.query(T).filter_by(id=obj_id).delete()