示例#1
0
def update_done():
    def callback(session):
        for todo in session.query(Todo).all():
            todo.done = ('done.%d' % todo.id) in request.form
    run_transaction(sessionmaker, callback)
    flash('Updated status')
    return redirect(url_for('show_all'))
示例#2
0
def new():
    if request.method == 'POST':
        if not request.form['title']:
            flash('Title is required', 'error')
        elif not request.form['text']:
            flash('Text is required', 'error')
        else:
            def callback(session):
                todo = Todo(request.form['title'], request.form['text'])
                session.add(todo)
            run_transaction(sessionmaker, callback)
            flash(u'Todo item was successfully created')
            return redirect(url_for('show_all'))
    return render_template('new.html')
示例#3
0
    def add_vehicle(self, vehicle_type, longitude, latitude, battery):
        """
        Wraps a `run_transaction` call that adds a vehicle.

        Arguments:
            vehicle_type {String} -- The type of vehicle.
        """
        return run_transaction(
            sessionmaker(bind=self.engine), lambda session: add_vehicle_txn(
                session, vehicle_type, longitude, latitude, battery))
示例#4
0
def add_users(engine, num_users, city):
    chunk_size = 1000
    datagen = Faker()

    def add_users_helper(sess, chunk, n):
        users = []
        for i in range(chunk, n):
            users.append(
                User(id=MovRGenerator.generate_uuid(),
                     city=city,
                     name=datagen.name(),
                     address=datagen.address(),
                     credit_card=datagen.credit_card_number()))
        sess.bulk_save_objects(users)

    for chunk in range(0, num_users, chunk_size):
        run_transaction(
            sessionmaker(bind=engine), lambda s: add_users_helper(
                s, chunk, min(chunk + chunk_size, num_users)))
示例#5
0
    def start_ride(self, vehicle_id, user_email):
        """
        Wraps a `run_transaction` call that starts a ride.

        Arguments:
            vehicle_id {UUID} -- The vehicle's unique ID.
        """
        return run_transaction(
            self.sessionfactory,
            lambda session: start_ride_txn(session, vehicle_id, user_email))
示例#6
0
    def remove_vehicle(self, vehicle_id):
        """
        Wraps a `run_transaction` call that "removes" a vehicle. No rows are deleted by this function.

        Arguments:
            id {UUID} -- The vehicle's unique ID.
        """
        return run_transaction(
            self.sessionmaker,
            lambda session: remove_vehicle_txn(session, vehicle_id))
示例#7
0
    def remove_user(self, user_id):
        """
        Wraps a `run_transaction` call that "removes" a user. No rows are deleted by this function.

        Arguments:
            id {UUID} -- The user's unique ID.
        """
        return run_transaction(
            self.sessionmaker,
            lambda session: remove_user_txn(session, user_id))
示例#8
0
    def remove_vehicle(self, vehicle_id):
        """
        Wraps a `run_transaction` call that "removes" a vehicle.

        Arguments:
            id {UUID} -- The vehicle's unique ID.
        """
        return run_transaction(
            sessionmaker(bind=self.engine),
            lambda session: remove_vehicle_txn(session, vehicle_id))
示例#9
0
    def start_ride(self, vehicle_id):
        """
        Wraps a `run_transaction` call that starts a ride.

        Arguments:
            vehicle_id {UUID} -- The vehicle's unique ID.
        """
        return run_transaction(
            sessionmaker(bind=self.engine),
            lambda session: start_ride_txn(session, vehicle_id))
示例#10
0
def login():
    username = request.json.get('username')
    password = request.json.get('password')
    print('inside login')
    user = None

    def callback(session):
        user = session.query(User).filter_by(username=username).one()
        if not user:
            abort(501, {'message': 'Username or password incorrect'})

        if not user.verify_password(password):
            abort(501, {'message': 'Username or password incorrect'})
        else:
            return (jsonify({
                'username': username,
                'message': 'Login successful'
            }), 200)

    run_transaction(sessionmaker, callback)
示例#11
0
    def end_ride(self, ride_id, location):
        """
        Wraps a `run_transaction` call that ends a ride.

        Arguments:
            ride_id {UUID} -- The ride's unique ID.
            location {String} -- The vehicle's last location.
        """
        return run_transaction(
            self.sessionmaker,
            lambda session: end_ride_txn(session, ride_id, location))
示例#12
0
    def remove_vehicle(self, city, vehicle_id):
        """
        Wraps a `run_transaction` call that "removes" a vehicle. No rows are deleted by this function.

        Arguments:
            city {String} -- The vehicle's city.
            id {UUID} -- The vehicle's unique ID.
        """
        return run_transaction(
            sessionmaker(bind=self.engine),
            lambda session: remove_vehicle_txn(session, city, vehicle_id))
示例#13
0
    def end_ride(self, city, ride_id):
        def end_ride_helper(session, city, ride_id):
            ride = session.query(Ride).filter_by(
                city=city, id=ride_id) if self.multi_region else session.query(
                    Ride).filter_by(id=ride_id)
            r = ride.first()
            vehicle = session.query(Vehicle).filter_by(
                city=city, id=r.vehicle_id
            ) if self.multi_region else session.query(Vehicle).filter_by(
                id=r.vehicle_id)
            vehicle.update({'status': 'available'})
            v = vehicle.first()
            ride.update({
                'end_address': v.current_location,
                'revenue': MovRGenerator.generate_revenue(),
                'end_time': datetime.datetime.now()
            })

        run_transaction(
            sessionmaker(bind=self.engine),
            lambda session: end_ride_helper(session, city, ride_id))
示例#14
0
    def get_users(self, city):
        """
        Wraps a `run_transaction` call that gets users in a particular city as a list of dictionaries.

        Arguments:
            city {String} -- The users' city.

        Returns:
            List -- A list of dictionaries containing user data.
        """
        return run_transaction(self.sessionmaker,
                               lambda session: get_users_txn(session, city))
示例#15
0
    def start_ride(self, city, rider_id, vehicle_id):
        """
        Wraps a `run_transaction` call that starts a ride.

        Arguments:
            city {String} -- The ride's city.
            rider_id {UUID} -- The user's unique ID.
            vehicle_id {UUID} -- The vehicle's unique ID.
        """
        return run_transaction(
            self.sessionmaker, lambda session: start_ride_txn(
                session, city, rider_id, vehicle_id))
示例#16
0
    def get_vehicles(self, city):
        """
        Wraps a `run_transaction` call that gets vehicles in a particular city as a list of dictionaries.

        Arguments:
            city {String} -- The vehicle's city.

        Returns:
            List -- A list of dictionaries containing vehicle data.
        """
        return run_transaction(sessionmaker(bind=self.engine),
                               lambda session: get_vehicles_txn(session, city))
示例#17
0
    def add_user(self, city, name, address, credit_card_number):
        def add_user_helper(session, city, name, address, credit_card_number):
            u = User(city=city,
                     id=MovRGenerator.generate_uuid(),
                     name=name,
                     address=address,
                     credit_card=credit_card_number)
            session.add(u)
            return {'city': u.city, 'id': u.id}

        return run_transaction(
            sessionmaker(bind=self.engine), lambda session: add_user_helper(
                session, city, name, address, credit_card_number))
示例#18
0
def get_sport(sport_id: str):
    def callback(session, sport_id):
        found = session.query(Sports).filter_by(id=sport_id).first()
        if found:
            return {
                "id": found.id,
                "name": found.name,
                "description": found.description
            }
        else:
            raise HTTPException(status_code=404, detail="Sport not found")

    return run_transaction(sessionmaker, lambda s: callback(s, sport_id))
示例#19
0
    def add_user(self, email, last_name, first_name, phone_numbers):
        """
        Wraps a `run_transaction` call that adds a user.

        Arguments:
            email {String} -- The user's email.
            first_name {String} -- The user's first name.
            last_name {String} -- The user's last name.
            phone_numbers {String} -- The user's phone numbers.
        """
        return run_transaction(
            self.sessionfactory, lambda session: add_user_txn(
                session, email, last_name, first_name, phone_numbers))
示例#20
0
    def get_promo_codes(self, follower_reads=False, limit=None):
        def get_promo_codes_helper(session, follower_reads, limit=None):
            if follower_reads:
                session.execute(
                    text(
                        'SET TRANSACTION AS OF SYSTEM TIME experimental_follower_read_timestamp()'
                    ))
            pcs = session.query(PromoCode).limit(limit).all()
            return list(map(lambda pc: pc.code, pcs))

        return run_transaction(
            sessionmaker(bind=self.engine), lambda session:
            get_promo_codes_helper(session, follower_reads, limit))
示例#21
0
文件: movr.py 项目: rhedgpeth/movr
    def get_cities(self, follower_reads=False):
        def get_cities_helper(session, follower_reads):
            if follower_reads:
                session.execute(
                    text(
                        'SET TRANSACTION AS OF SYSTEM TIME follower_read_timestamp()'
                    ))
            users = self.session.query(User).distinct(User.city).all()
            return tuple(user.city for user in users)

        return run_transaction(
            sessionmaker(bind=self.engine),
            lambda session: get_cities_helper(session, follower_reads))
示例#22
0
    def get_rides(self, rider_id):
        """
        Wraps a `run_transaction` call that gets rides in a particular city as a list of dictionaries.

        Arguments:
            rider_id {UUID} -- The user's unique ID.

        Returns:
            List -- A list of dictionaries containing ride data.
        """
        return run_transaction(
            sessionmaker(bind=self.engine),
            lambda session: get_rides_txn(session, rider_id))
示例#23
0
def post_sport(sport: SportsCreate):
    def callback(session, sport):
        new_sport = Sports(id=uuid(),
                           name=sport.name,
                           description=sport.description)
        session.add(new_sport)
        return {
            "id": new_sport.id,
            "name": new_sport.name,
            "description": new_sport.description
        }

    return run_transaction(sessionmaker, lambda s: callback(s, sport))
示例#24
0
    def get_rides_by_user(self, email):
        """
        Wraps a `run_transaction` call that gets rides for a user.

        Arguments:
            user_email {String} -- The user's email address.

        Returns:
            List -- A list of dictionaries containing ride data.
        """
        return run_transaction(
            self.sessionfactory,
            lambda session: get_rides_by_user_txn(session, email))
示例#25
0
    def get_vehicles(self, max_vehicles=None):
        """
        Wraps a `run_transaction` call that gets all vehicle.

        Returns:
            A list of dictionaries containing vehicle data.
        """
        if max_vehicles is None:
            max_vehicles = self.max_records

        return run_transaction(
            self.sessionfactory,
            lambda session: get_vehicles_txn(session, max_vehicles))
示例#26
0
文件: loadmovr.py 项目: nstewart/movr
def add_vehicle_location_histories(engine, num_histories, city):
    chunk_size = 5000

    def add_vehicle_location_histories_helper(sess, chunk, n):
        rides = sess.query(Ride).filter_by(city=city).all()

        histories = []
        for i in range(chunk, min(chunk + chunk_size, num_histories)):
            latlong = MovRGenerator.generate_random_latlong()
            histories.append(
                VehicleLocationHistory(city=city,
                                       ride_id=random.choice(rides).id,
                                       lat=latlong["lat"],
                                       long=latlong["long"]))

        sess.bulk_save_objects(histories)

    for chunk in range(0, num_histories, chunk_size):
        run_transaction(
            sessionmaker(bind=engine),
            lambda s: add_vehicle_location_histories_helper(
                s, chunk, min(chunk + chunk_size, num_histories)))
示例#27
0
def register():
    username = request.json.get('username')
    password = request.json.get('password')

    def check_user_exists(session):
        user = bool(session.query(User).filter_by(username=username).first())
        if user:
            abort(501, {'message': 'Username already exists'})

    run_transaction(sessionmaker, check_user_exists)

    def callback(session):
        user = User(username=username)
        user.hash_password(password)
        session.add(user)

    run_transaction(sessionmaker, callback)

    # db.session.commit()
    return (jsonify({
        'username': username,
        'message': 'User created successfully'
    }), 201)
示例#28
0
    def get_user(self, username=None, user_id=None):
        """
        Wraps a `run_transaction` call that gets a User object. As a required function for LoginManager, the function must take the `user_id` argument, and return a User object.

        Keyword Arguments:
            username {String} -- The user's username. (default: {None})
            user_id {UUID} -- The user's unique ID. (default: {None})

        Returns:
            User -- A User object.
        """
        return run_transaction(
            sessionmaker(bind=self.engine),
            lambda session: get_user_txn(session, username, user_id))
示例#29
0
def setup_app():
    # Setup Flask app.
    app = Flask(__name__)
    app.config.from_pyfile('server.cfg')
    app.config['SQLALCHEMY_DATABASE_URI'] = os.getenv("ADDR", DEFAULT_URL)
    app.debug = False

    # Disable log messages, which are outputted to stderr and treated as errors
    # by the test driver.
    if not app.debug:
        logging.getLogger('werkzeug').setLevel(logging.ERROR)

    # Initialize flask-sqlachemy.
    db.init_app(app)
    # We need to create the application tables within a retry loop.
    # CockroachDB doesn't stop the world when running DDL statements,
    # so it's possible that they may fail due to transaction conflicts
    # when modifying the internal database descriptors.
    with app.test_request_context():
        sessionmaker = sqlalchemy.orm.sessionmaker(db.engine)
        run_transaction(sessionmaker, lambda _: db.create_all())

    return app
示例#30
0
def setup_app():
    # Setup Flask app.
    app = Flask(__name__)
    app.config.from_pyfile('server.cfg')
    app.config['SQLALCHEMY_DATABASE_URI'] = os.getenv("ADDR", DEFAULT_URL)
    app.debug = False

    # Disable log messages, which are outputted to stderr and treated as errors
    # by the test driver.
    if not app.debug:
        logging.getLogger('werkzeug').setLevel(logging.ERROR)

    # Initialize flask-sqlachemy.
    db.init_app(app)
    # We need to create the application tables within a retry loop.
    # CockroachDB doesn't stop the world when running DDL statements,
    # so it's possible that they may fail due to transaction conflicts
    # when modifying the internal database descriptors.
    with app.test_request_context():
        sessionmaker = sqlalchemy.orm.sessionmaker(db.engine)
        run_transaction(sessionmaker, lambda _: db.create_all())

    return app
示例#31
0
文件: loadmovr.py 项目: nstewart/movr
def add_promo_codes(engine, num_codes):
    chunk_size = 800
    datagen = Faker()

    def add_codes_helper(sess, chunk, n):
        codes = []
        for i in range(chunk, min(chunk + chunk_size, num_codes)):
            code = "_".join(datagen.words(nb=3)) + "_" + str(time.time())
            codes.append(
                PromoCode(code=code,
                          description=datagen.paragraph(),
                          expiration_time=datetime.datetime.now() +
                          datetime.timedelta(days=random.randint(0, 30)),
                          rules={
                              "type": "percent_discount",
                              "value": "10%"
                          }))
        sess.bulk_save_objects(codes)

    for chunk in range(0, num_codes, chunk_size):
        run_transaction(
            sessionmaker(bind=engine), lambda s: add_codes_helper(
                s, chunk, min(chunk + chunk_size, num_codes)))
示例#32
0
    def get_active_rides(self, city, follower_reads=False, limit=None):
        def get_active_rides_helper(session, city, follower_reads, limit=None):
            if follower_reads:
                session.execute(
                    text(
                        'SET TRANSACTION AS OF SYSTEM TIME experimental_follower_read_timestamp()'
                    ))
            rides = session.query(Ride).filter_by(
                city=city, end_time=None).limit(limit).all()
            return list(map(lambda ride: {'city': city, 'id': ride.id}, rides))

        return run_transaction(
            sessionmaker(bind=self.engine), lambda session:
            get_active_rides_helper(session, city, follower_reads, limit))
示例#33
0
    def create_promo_code(self, code, description, expiration_time, rules):
        def add_promo_code_helper(session, code, description, expiration_time,
                                  rules):
            pc = PromoCode(code=code,
                           description=description,
                           expiration_time=expiration_time,
                           rules=rules)
            session.add(pc)
            return pc.code

        return run_transaction(
            sessionmaker(bind=self.engine),
            lambda session: add_promo_code_helper(session, code, description,
                                                  expiration_time, rules))
示例#34
0
def show_all():
    def callback(session):
        return render_template(
            'show_all.html',
            todos=session.query(Todo).order_by(Todo.pub_date.desc()).all())
    return run_transaction(sessionmaker, callback)