Esempio n. 1
0
class TaskGenerator(Actor):
    def __init__(self, hive, id):
        super(TaskGenerator, self).__init__(hive, id)
        self.session = Session()

        self.message_routing.update({"start": self.startGeneratingTasks})

    def startGeneratingTasks(self, message):
        _log.debug("sleeping some time")
        some_locations = [[2, 9], [3, 10], [3, 9], [3, 11], [4, 4], [4, 1.5],
                          [2.5, 9], [4, 10], [4, 11]]
        number_of_locations = randint(1, 4)
        locations_to_visit = []
        for _ in range(number_of_locations):
            loc = randint(0, len(some_locations) - 1)
            locations_to_visit.append(some_locations[loc])
        locations = locations_to_visit

        user = "******"
        status = 'pending'
        locations = [Point(l) for l in locations]
        new_task = Task(username=user, locations=locations, status=status)
        try:
            self.session.add(new_task)
            self.session.commit()
            entry_id = new_task.id
            _log.debug("-------------------------sending new request")
            self.send_message(to=settings.SCHEDULER, directive="request",\
                                           body = {'locations':locations, 'request_id':entry_id})
            yield from asyncio.sleep(30)
            self.send_message(to="generator", directive="start")

        except Exception as e:
            self.session.rollback()
            self.set_status(400)
Esempio n. 2
0
 def deleteShiftDutyRecord(shift_duty_date,
                           shift_duty_period=DutyPeriod.NightDuty):
     session = Session()
     duty_shift_chain = DBOperation.getDutyShiftChain(
         shift_duty_date, shift_duty_period)
     if duty_shift_chain is None:
         print("无日期为{}的值班记录".format(shift_duty_date))
         return
     shift_chain_list = duty_shift_chain.shift_chain
     shift_count = len(shift_chain_list) - 1
     try:
         if shift_count == 0:
             print("can not delete origin duty.")
             return
         elif shift_count == 1:
             session.query(OriginDuty).filter(
                 OriginDuty == shift_chain_list[-2]).update(
                     {OriginDuty.shift_duty_id: None})
         else:
             session.query(ShiftDuty).filter(
                 ShiftDuty == shift_chain_list[-2]).update(
                     {ShiftDuty.next_shift_duty_id: None})
         session.delete(shift_chain_list[-1])
         session.commit()
     except Exception as e:
         print(e)
         session.rollback()
     finally:
         session.close()
Esempio n. 3
0
class Admin(tornado.web.RequestHandler):
    def __init__(self, application, request, **kwargs):
        super(Admin, self).__init__(application, request, **kwargs)
        _log.debug('admin init')
        self.session = Session()
        self.request_handler_actor = self.application.settings[
            'request_handler_actor']

    def __del__(self):
        self.session.close()

    # list existing bots
    def get(self):
        result = self.session.query(TurtlebotAgent).all()
        jsonResult = json.dumps(result, cls=TurtlesEncoder)
        self.write(jsonResult)

    # add a new bot with name and location

    def post(self):

        if settings.SIMULATION == True:
            initial_location = [settings.NEST_X, settings.NEST_Y]
            robots_in_database = self.session.query(TurtlebotAgent.name).all()
            if len(robots_in_database) == 0:
                maximal_index = -1
            else:
                maximal_index = max(
                    [int(r[0].split('_')[1]) for r in robots_in_database])
            turtlebot_name = 'robot_' + repr(maximal_index + 1)
            if maximal_index == settings.MAXIMAL_NUMBER_OF_BOTS - 1:
                self.set_status(204, "maximal number of bots already reached")
                self.finish()
        else:
            try:
                initial_location = json.loads(
                    self.get_body_argument(name='location'))
            except:
                self.set_status(400)
                self.finish()
            else:
                turtlebot_name = self.get_body_argument(name='name')
                robots_with_same_name = self.session.query(
                    TurtlebotAgent).filter_by(name=turtlebot_name).all()
                if len(robots_with_same_name) > 0:
                    self.set_status(400, "the turtlebot name must be unique")
                elif len(initial_location) != 2:
                    self.set_status(
                        400, "the initial location must be a 2d vector")
                    self.finish()

        try:
            new_agent = TurtlebotAgent(name=turtlebot_name,
                                       location=Point(initial_location))
            self.session.add(new_agent)
            self.session.commit()

        except Exception as e:
            self.session.rollback()
            self.set_status(400, 'error writing in the database')
def delete_account(user_data):
    """Delete user transaction"""

    session = Session()
    response = None
    try:
        user = session.query(User).filter(User.email == user_data['email'] ).first()

        if user is not None:
            if __hash_pass(user_data['password']) == user.password:
                session.delete(user)
                session.commit()
                # TRANSACTION SUCCESSFUL
                response = success_response(user, 'delete')
            else:
                response = error_response(err_concept='bad_credentials')
        else:
            response = error_response(err_concept='non_user')
    
    except exc.DBAPIError as e:
        session.rollback()
        response = error_response(e.code, e.orig, 'transaction')
    
    finally:
        if response is not None:
            return response
Esempio n. 5
0
 def shiftDuty(duty_date, duty_period, member):
     session = Session()
     try:
         shift_duty = ShiftDuty(duty_date, duty_period, member.member_id)
         duty = session.query(OriginDuty).filter(
             and_(OriginDuty.duty_date == duty_date,
                  OriginDuty.duty_period == duty_period.value)).first()
         if duty is not None:
             if duty.shift_duty_id is None:
                 shift_duty.previous_shift_duty_id = duty.duty_id
                 duty.shift_duty_id = shift_duty.shift_duty_id
                 session.add(shift_duty)
                 session.commit()
             else:
                 shift_id = duty.shift_duty_id
                 while shift_id is not None:
                     pre_shift_duty = session.query(ShiftDuty).filter(
                         ShiftDuty.shift_duty_id == shift_id).first()
                     shift_id = pre_shift_duty.next_shift_duty_id
                 pre_shift_duty.next_shift_duty_id = shift_duty.shift_duty_id
                 shift_duty.previous_shift_duty_id = pre_shift_duty.shift_duty_id
                 session.add(shift_duty)
                 session.commit()
     except Exception as e:
         print(e)
         session.rollback()
     finally:
         session.close()
Esempio n. 6
0
    def upload(user_id, package_name, version, time, remark):
        try:
            session_obj = Session()
            tmp = session_obj.query(user_info).filter_by(id=user_id).first()
            if (tmp == None):
                Session.remove()
                return -1

            tmp = session_obj.query(package_info).options(
                subqueryload(package_info.user)).filter_by(
                    package_name=package_name).filter_by(
                        user_id=user_id).first()
            if tmp is not None:
                tmp = session_obj.query(package_info).get(tmp.id)
                session_obj.delete(tmp)
                session_obj.commit()

            package_obj = package_info(user_id=user_id,
                                       package_name=package_name,
                                       version=version,
                                       time=time,
                                       remarks=remark)
            session_obj.add(package_obj)
            session_obj.commit()
            Session.remove()

            return 0
        except Exception as e:
            Logger().get_logger().error(str(e))
            session_obj.rollback()
            return -2
Esempio n. 7
0
def session_scope():
    session = Session()
    try:
        yield session
        session.commit()
    except:
        session.rollback()
    finally:
        session.close()
Esempio n. 8
0
def save_result(result: dict) -> bool:
    try:
        cep = ms.load(result, session=Session)
        Session.add(cep)
        Session.commit()
        return True
    except Exception:
        Session.rollback()
        return False
Esempio n. 9
0
File: agent.py Progetto: ayllon/Borg
 def add(self, hostname, user, password):
     try:
         agent = Agent(hostname=hostname, user=user, password=password)
         Session.merge(agent)
         Session.commit()
         return agent
     except:
         Session.rollback()
         raise
Esempio n. 10
0
 def updateEvent(self, event_id, update_data):
     session = Session()
     try:
         session.query(Event).filter_by(id=event_id).update(json.loads(update_data))
     except:
         session.rollback()
         raise #exception of some sort
     finally:
         session.close()
Esempio n. 11
0
File: test.py Progetto: ayllon/Borg
 def add(self, alias, location):
     _validate_alias(alias)
     try:
         suite = TestSuite(alias=alias, location=location)
         Session.merge(suite)
         Session.commit()
     except:
         Session.rollback()
         raise
Esempio n. 12
0
File: test.py Progetto: ayllon/Borg
 def remove(self, alias):
     try:
         suite = Session.query(TestSuite).get(alias)
         if suite:
             Session.delete(suite)
             Session.commit()
     except:
         Session.rollback()
         Session.commit()
Esempio n. 13
0
 def update_tags(cls, xg_device_token, tags):
     try:
         r = Session.query(cls).filter(cls.xg_device_token == xg_device_token).first()
         r.tags = tags
         Session.add(r)
         Session.commit()
     except sqlalchemy.exc.IntegrityError, e:
         logger.warning('msg[update tags error] table[%s] e[%s]' % (__tablename__, e))
         Session.rollback()
Esempio n. 14
0
File: agent.py Progetto: ayllon/Borg
 def remove(self, hostname):
     try:
         agent = Session.query(Agent).get(hostname)
         if not agent:
             raise KeyError("%s not found" % hostname)
         Session.delete(agent)
         Session.commit()
     except:
         Session.rollback()
         raise
Esempio n. 15
0
 def query_packages(package_id):
     try:
         session_obj = Session()
         ret = session_obj.query(package_info).options(
             subqueryload(
                 package_info.user)).filter_by(id=package_id).first()
         Session.remove()
         return ret
     except Exception as e:
         Logger().get_logger().error(str(e))
         session_obj.rollback()
         return -1
Esempio n. 16
0
def product_query(req):
    """ Product Query method. Lazy load the product
        elaborating a Query object before hitting 
        the database. """
    session = Session()
    query = None
    response = None
    page = None
    try:
        query = Query([Products.name, 
                        Products.cost, 
                        Products.total_products, 
                        Products.batch,
                        Products.expiration_date, 
                        Product_Types.name.label('type')]).join(Product_Types)

        if len(req.args) is 0:  
            pass
        else:
            if 'type' in req.args:
                product_type = req.args['type']
                query = query.filter(Product_Types.name == product_type)

            if 'lower_than' in req.args:
                cost = float(req.args['lower_than'])
                query = query.filter(Products.cost < cost)

            if 'higher_than' in req.args:
                cost = float(req.args['higher_than'])
                query = query.filter(Products.cost > cost)

            if 'name' in req.args:
                name = req.args['name']
                query = query.filter(Products.name.like(f'%{name}%'))

    except exc.DBAPIError as e:
        session.rollback()
        response = error_response(e.code, e.orig)

    else:
        if 'page' in req.args:
            page = int(req.args['page'])
            query = query.limit(10).offset( (page - 1) * 10 )
        else:
            page = 1
            query = query.limit(10).offset(0)
        
        query.session = session
        response = product_response(query, 'products_query', page)

    finally:
        return response
Esempio n. 17
0
def insert_members():
    session = Session()
    mdf = pd.read_csv('data/application_team_data.csv')
    try:
        for i in mdf.index:
            member = Member(int(mdf['ID'][i]), mdf['Name'][i])
            session.add(member)
        session.commit()
    except Exception as e:
        print(e)
        session.rollback()
    finally:
        session.close()
Esempio n. 18
0
 def generate(self, current_time, timestep):
     try:
         requests = Session.execute(
             query.format(table=self.table,
                          t1=current_time,
                          t2=current_time + timestep))
         customers = [Customer(request) for request in requests]
     except:
         Session.rollback()
         raise
     finally:
         Session.remove()
     return customers
 def create_v_neighborhood(volunteer_id, neighborhoods):
     s = Session()
     try:
         for n in neighborhoods:
             v = VolunteerNeighborhoods(n, volunteer_id)
             s.add(v)
         s.commit()
     except:
         s.rollback()
         return False
     finally:
         s.close()
     return True
 def create_v_availability(volunteer_id, avail):
     s = Session()
     try:
         for a in avail:
             v = VolunteerAvailability(a, volunteer_id)
             s.add(v)
             s.commit()
     except:
         s.rollback()
         return False
     finally:
         s.close()
     return True
Esempio n. 21
0
 def update(cls, sid, status, valid=1, identifier=''):
     try:
         r = Session.query(cls).filter(cls.sid == sid).first()
         if r:
             r.identifier = identifier
             r.status = status
             r.valid = valid
             Session.add(r)
             Session.commit()
         return r
     except sqlalchemy.exc.IntegrityError, e:
         Session.rollback()
         logger.warning('msg[update %s error] e[%s]' % (__tablename__, e))
         return None
Esempio n. 22
0
def store(tickets):
    session = Session()
    try:
        #log.info('Storing {} tickets'.format(len(tickets)))
        for ticket in tickets:
            changes = changeset(session.merge(ticket))
            changes.pop("search_date_time", None)
            if changes:
                log.info('{} updated {} '.format(ticket, ' '.join(['{}(old:{} new:{} {:+.2f})'.format(k, w[0], w[1], w[1]/w[0]*100-100) for k, w in changes.items()])))
            session.commit()
    except Exception:
        log.exception('Exception')
        session.rollback()
    finally:
        session.close()
Esempio n. 23
0
    def vote_song(self, user, song_id=None, video_url=None):
        """Vote for a song"""
        session = Session()

        if video_url:
            packet = session.query(Packet).filter_by(
                video_url=video_url, player_name=PLAYER_NAME).first()
        elif song_id is not None:
            packet = session.query(Packet).filter_by(
                song_id=song_id, player_name=PLAYER_NAME).first()
        else:
            raise Exception('Must specify either song_id or video_url')

        if packet:  # Song is already queued; add a vote
            if user == packet.user:
                session.rollback()
                raise Exception('User %s has already voted for this song' %
                                user)
            try:
                packet.additional_votes.append(Vote(user=user))
                session.commit()
            except FlushError:
                session.rollback()
                raise Exception('User %s has already voted for this song' %
                                user)
            self._update_finish_times(packet.user)
        else:  # Song is not queued; queue it
            if video_url:
                if 'www.youtube.com' in video_url:
                    try:
                        video_details = get_youtube_video_details(video_url)
                        packet = Packet(video_url=video_url,
                                        video_title=video_details['title'],
                                        video_length=video_details['length'],
                                        user=user,
                                        arrival_time=self.virtual_time,
                                        player_name=PLAYER_NAME)
                        session.add(packet)
                        session.commit()
                    except Exception, e:
                        session.rollback()
                        raise e
                else:
                    session.rollback()
                    raise Exception('Unsupported website')
            else:
Esempio n. 24
0
def rollback():
    Session.rollback()