Example #1
0
def make_a_order():
    """"
    version:0.0.1
    创建一个订单,必须的字段
    title,describe,money,location_x,location_y
    """

    if request.method == 'POST':
        # 从请求表单中创建变量
        title = request.form['title']
        describe = request.form['describe']
        money = request.form['money']
        address = request.form['address']
        location_x = request.form['location_x']
        location_y = request.form['location_y']
        progress = Order.Progeress_Enum.on
        # 简单的订单创建逻辑,没有考虑恶意刷单,用户验证情况
        order = Order(title=title, describe=describe, money=money, address=address,
                      create_at=datetime.datetime.now(),
                      send_time=None, paid_at=None,
                      location_x=location_x, location_y=location_y, progress=progress)
        db_session.add(order)
        db_session.commit()
        return render_template('result_create_order.html')
    if request.method == 'GET':
        return render_template('create_order.html')
Example #2
0
def register_handler():
    username = request.form['username']
    password = request.form['password']
    email = session['email']
    errors = []

    if not re.match('^[a-z0-9]+$', username):
        errors.append("The submitted username contains non-alphanumeric characters")
    if User.query.filter(User.email == email).first():
        errors.append("A user with the same email already exists")
    if not User.strong_password(password):
        errors.append("Your password must contain a mix of letters and numerical characters and be at least 6 characters long")

    # Checking if a user exists in RabbitMQ OR in our db
    try:
        pulse_management.user(username=username)
        in_rabbitmq = True
    except PulseManagementException:
        in_rabbitmq = False

    if in_rabbitmq:
        errors.append("A user with the same username already exists in Pulse")
    if User.query.filter(User.username == username).first():
        errors.append("A user with the same username already exists in our database")
    if errors:
        signup_error = "{0}.".format(', '.join(errors))
        return render_template('register.html', email=email, signup_error=signup_error)

    user = User.new_user(email=email, username=username, password=password, management_api=pulse_management)
    db_session.add(user)
    db_session.commit()

    return render_template('confirm.html')
Example #3
0
    def update_queue_information(self, queue_data):
        if not 'messages' in queue_data:
            # FIXME: We should do something here, probably delete the queue,
            # as it's in a weird state.  More investigation is required.
            # See bug 1066338.
            return None

        q_size, q_name = (queue_data['messages'], queue_data['name'])
        queue = Queue.query.filter(Queue.name == q_name).first()

        # If the queue doesn't exist in the db, create it.
        if queue is None:
            logger.info("New queue '{0}' encountered. "
                        "Adding to the database.".format(q_name))
            queue = Queue(name=q_name, owner=None)

        # Update the saved queue size.
        queue.size = q_size
        db_session.add(queue)
        db_session.commit()

        # If we don't know who created the queue...
        if queue.owner is None:
            logger.debug("Queue '{0}' owner's unknown.".format(q_name))

            # If no client is currently consuming the queue, just skip it.
            if queue_data['consumers'] == 0:
                logger.debug(
                    "Queue '{0}' skipped (no owner, no current consumer).".
                    format(q_name))
                return queue

            # Otherwise look for its user.
            owner_name = self.api.queue_owner(queue_data)

            user = User.query.filter(User.username == owner_name).first()

            # If the queue was created by a user that isn't in the
            # pulseguardian database, skip the queue.
            if user is None:
                logger.info(
                    "Queue '{0}' owner, {1}, isn't in the db. Creating the user."
                    .format(q_name, owner_name))
                user = User.new_user(username=owner_name,
                                     email='',
                                     password='',
                                     management_api=None)

            # Assign the user to the queue.
            logger.info("Assigning queue '{0}' to user {1}.".format(
                q_name, user))
            queue.owner = user
            db_session.add(queue)
            db_session.commit()

        return queue
Example #4
0
    def test_user(self):
        user = User.new_user(email='*****@*****.**', username='******',
                             password='******', management_api=None)
        db_session.add(user)
        db_session.commit()

        self.assertIn(user, User.query.all())
        # Emails are normalized by putting them lower-case
        self.assertEqual(User.query.filter(User.email == '*****@*****.**').first(), user)
        self.assertEqual(User.query.filter(User.username == 'dummy').first(), user)
        self.assertIsNone(User.query.filter(User.username == 'DOMMY').first())
Example #5
0
    def delete_zombie_queues(self, queues):
        db_queues = Queue.query.all()

        # Filter queues that are in the database but no longer on RabbitMQ.
        alive_queues_names = set(q['name'] for q in queues)
        zombie_queues = set(q for q in db_queues
                            if q.name not in alive_queues_names)

        # Delete those queues.
        for queue in zombie_queues:
            db_session.delete(queue)
        db_session.commit()
Example #6
0
    def delete_zombie_queues(self, queues):
        db_queues = Queue.query.all()

        # Filter queues that are in the database but no longer on RabbitMQ.
        alive_queues_names = set(q['name'] for q in queues)
        zombie_queues = set(q for q in db_queues if q.name
                            not in alive_queues_names)

        # Delete those queues.
        for queue in zombie_queues:
            db_session.delete(queue)
        db_session.commit()
Example #7
0
    def update_queue_information(self, queue_data):
        if not 'messages' in queue_data:
            # FIXME: We should do something here, probably delete the queue,
            # as it's in a weird state.  More investigation is required.
            # See bug 1066338.
            return None

        q_size, q_name = (queue_data['messages'],
                          queue_data['name'])
        queue = Queue.query.filter(Queue.name == q_name).first()

        # If the queue doesn't exist in the db, create it.
        if queue is None:
            logger.info("New queue '{0}' encountered. "
                        "Adding to the database.".format(q_name))
            queue = Queue(name=q_name, owner=None)

        # Update the saved queue size.
        queue.size = q_size
        db_session.add(queue)
        db_session.commit()

        # If we don't know who created the queue...
        if queue.owner is None:
            logger.debug("Queue '{0}' owner's unknown.".format(q_name))

            # If no client is currently consuming the queue, just skip it.
            if queue_data['consumers'] == 0:
                logger.debug("Queue '{0}' skipped (no owner, no current consumer).".format(q_name))
                return queue

            # Otherwise look for its user.
            owner_name = self.api.queue_owner(queue_data)

            user = User.query.filter(User.username == owner_name).first()

            # If the queue was created by a user that isn't in the
            # pulseguardian database, skip the queue.
            if user is None:
                logger.info(
                    "Queue '{0}' owner, {1}, isn't in the db. Creating the user.".format(q_name, owner_name))
                user = User.new_user(username=owner_name, email='', password='',
                                     management_api=None)

            # Assign the user to the queue.
            logger.info(
                "Assigning queue '{0}' to user {1}.".format(q_name, user))
            queue.owner = user
            db_session.add(queue)
            db_session.commit()

        return queue
Example #8
0
def delete_queue(queue_name):
    queue = Queue.query.get(queue_name)

    if queue and g.user and queue.owner == g.user or g.user.admin:
        db_session.delete(queue)
        db_session.commit()
        try:
            pulse_management.delete_queue(vhost='/', queue=queue.name)
            return jsonify(ok=True)
        except PulseManagementException as e:
            app.logger.warning(
                "Couldn't delete the queue '{0}' on rabbitmq: {1}".format(queue_name, e))

    return jsonify(ok=False)
Example #9
0
def dummy_data():
    # Dummy test users
    for i in xrange(4):
        User.new_user(
            email='dummy{0}@dummy.com'.format(i), username='******'.format(i),
            password='******', management_api=pulse_management)

    users = User.query.all()

    # And some dummy queues
    dummy_queue = Queue(name='dummy-empty-queue', size=0, owner=users[0])
    db_session.add(dummy_queue)
    db_session.commit()

    dummy_queue = Queue(name='dummy-non-empty-queue', size=config.warn_queue_size/5, owner=users[0])
    db_session.add(dummy_queue)
    db_session.commit()

    dummy_queue = Queue(name='dummy-warning-queue', size=config.warn_queue_size + 1, owner=users[1])
    db_session.add(dummy_queue)
    db_session.commit()

    dummy_queue = Queue(name='dummy-deletion-queue', size=int(config.del_queue_size * 1.2), owner=users[2])
    db_session.add(dummy_queue)
    db_session.commit()

    # Test admin user
    User.new_user(
        email='*****@*****.**', username='******', password='******',
        management_api=pulse_management, admin=True)

    logger.info('Finished generating dummy data.')
Example #10
0
def delete_queue(queue_name):
    queue = Queue.query.get(queue_name)

    if queue and g.user and queue.owner == g.user or g.user.admin:
        db_session.delete(queue)
        db_session.commit()
        try:
            pulse_management.delete_queue(vhost='/', queue=queue.name)
            return jsonify(ok=True)
        except PulseManagementException as e:
            app.logger.warning(
                "Couldn't delete the queue '{0}' on rabbitmq: {1}".format(
                    queue_name, e))

    return jsonify(ok=False)
Example #11
0
    def test_user(self):
        user = User.new_user(email='*****@*****.**',
                             username='******',
                             password='******',
                             management_api=None)
        db_session.add(user)
        db_session.commit()

        self.assertIn(user, User.query.all())
        # Emails are normalized by putting them lower-case
        self.assertEqual(
            User.query.filter(User.email == '*****@*****.**').first(), user)
        self.assertEqual(
            User.query.filter(User.username == 'dummy').first(), user)
        self.assertIsNone(User.query.filter(User.username == 'DOMMY').first())
Example #12
0
    def monitor_queues(self, queues):
        for queue_data in queues:
            # Updating the queue's information in the database (owner, size).
            queue = self.update_queue_information(queue_data)
            if not queue:
                continue

            # If a queue is over the deletion size, regardless of it having an
            # owner or not, delete it.
            if queue.size > self.del_queue_size:
                logger.warning(
                    "Queue '{0}' deleted. Queue size = {1}; del_queue_size = {2}"
                    .format(queue.name, queue.size, self.del_queue_size))
                if queue.owner:
                    self.deletion_email(queue.owner, queue_data)
                if self.on_delete:
                    self.on_delete(queue.name)
                self.api.delete_queue(vhost=queue_data['vhost'],
                                      queue=queue.name)
                db_session.delete(queue)
                db_session.commit()
                continue

            if queue.owner is None:
                continue

            if queue.size > self.warn_queue_size and not queue.warned:
                logger.warning(
                    "Warning queue '{0}' owner. Queue size = {1}; warn_queue_size = {2}"
                    .format(queue.name, queue.size, self.warn_queue_size))
                queue.warned = True
                if self.on_warn:
                    self.on_warn(queue.name)
                self.warning_email(queue.owner, queue_data)
            elif queue.size <= self.warn_queue_size and queue.warned:
                # A previously warned queue got out of the warning threshold;
                # its owner should not be warned again.
                logger.warning(
                    "Queue '{0}' was in warning zone but is OK now".format(
                        queue.name, queue.size, self.del_queue_size))
                queue.warned = False
                self.back_to_normal_email(queue.owner, queue_data)

            # Commit any changes to the queue.
            db_session.add(queue)
            db_session.commit()
Example #13
0
def delete_pulse_user(pulse_username):
    logging.info('Request to delete Pulse user "{0}".'.format(pulse_username))
    pulse_user = PulseUser.query.filter(PulseUser.username == pulse_username).first()

    if pulse_user and (g.user.admin or pulse_user.owner == g.user):
        try:
            pulse_management.delete_user(pulse_user.username)
        except PulseManagementException as e:
            logging.warning("Couldn't delete user '{0}' on "
                               "rabbitmq: {1}".format(pulse_username, e))
            return jsonify(ok=False)
        logging.info('Pulse user "{0}" deleted.'.format(pulse_username))
        db_session.delete(pulse_user)
        db_session.commit()
        return jsonify(ok=True)

    return jsonify(ok=False)
Example #14
0
    def setUp(self):
        init_and_clear_db()
        self.management_api = PulseManagementAPI()
        self.guardian = PulseGuardian(self.management_api, warn_queue_size=TEST_WARN_SIZE,
                                      del_queue_size=TEST_DELETE_SIZE, emails=False)

        self.consumer_cfg = pulse_cfg.copy()
        self.consumer_cfg['applabel'] = str(uuid.uuid1())

        # Configure / Create the test user to be used for message consumption
        self.consumer_cfg['user'], self.consumer_cfg['password'] = CONSUMER_USER, CONSUMER_PASSWORD
        username, password = self.consumer_cfg['user'], self.consumer_cfg['password']
        self.user = User.new_user(username=username, email=CONSUMER_EMAIL,
                                  password=password, management_api=self.management_api)
        db_session.add(self.user)
        db_session.commit()

        self.publisher = self.publisher_class(**pulse_cfg)
Example #15
0
    def monitor_queues(self, queues):
        for queue_data in queues:
            # Updating the queue's information in the database (owner, size).
            queue = self.update_queue_information(queue_data)
            if not queue:
                continue

            # If a queue is over the deletion size, regardless of it having an
            # owner or not, delete it.
            if queue.size > self.del_queue_size:
                logger.warning("Queue '{0}' deleted. Queue size = {1}; del_queue_size = {2}".format(
                    queue.name, queue.size, self.del_queue_size))
                if queue.owner:
                    self.deletion_email(queue.owner, queue_data)
                if self.on_delete:
                    self.on_delete(queue.name)
                self.api.delete_queue(vhost=queue_data['vhost'], queue=queue.name)
                db_session.delete(queue)
                db_session.commit()
                continue

            if queue.owner is None:
                continue

            if queue.size > self.warn_queue_size and not queue.warned:
                logger.warning("Warning queue '{0}' owner. Queue size = {1}; warn_queue_size = {2}".format(
                    queue.name, queue.size, self.warn_queue_size))
                queue.warned = True
                if self.on_warn:
                    self.on_warn(queue.name)
                self.warning_email(queue.owner, queue_data)
            elif queue.size <= self.warn_queue_size and queue.warned:
                # A previously warned queue got out of the warning threshold;
                # its owner should not be warned again.
                logger.warning("Queue '{0}' was in warning zone but is OK now".format(
                               queue.name, queue.size, self.del_queue_size))
                queue.warned = False
                self.back_to_normal_email(queue.owner, queue_data)

            # Commit any changes to the queue.
            db_session.add(queue)
            db_session.commit()
Example #16
0
def register_handler():
    username = request.form['username']
    password = request.form['password']
    email = session['email']
    errors = []

    if not re.match('^[a-z0-9]+$', username):
        errors.append(
            "The submitted username contains non-alphanumeric characters")
    if User.query.filter(User.email == email).first():
        errors.append("A user with the same email already exists")
    if not User.strong_password(password):
        errors.append(
            "Your password must contain a mix of letters and numerical characters and be at least 6 characters long"
        )

    # Checking if a user exists in RabbitMQ OR in our db
    try:
        pulse_management.user(username=username)
        in_rabbitmq = True
    except PulseManagementException:
        in_rabbitmq = False

    if in_rabbitmq:
        errors.append("A user with the same username already exists in Pulse")
    if User.query.filter(User.username == username).first():
        errors.append(
            "A user with the same username already exists in our database")
    if errors:
        signup_error = "{0}.".format(', '.join(errors))
        return render_template('register.html',
                               email=email,
                               signup_error=signup_error)

    user = User.new_user(email=email,
                         username=username,
                         password=password,
                         management_api=pulse_management)
    db_session.add(user)
    db_session.commit()

    return render_template('confirm.html')
Example #17
0
def init_and_clear_db():
    # Initializing the database schema
    init_db()

    # Removing all pulse users created by the web app
    for user in User.query.all():
        try:
            pulse_management.delete_user(user.username)
        except PulseManagementException:
            pass

    # Clearing the database from old data
    for queue in Queue.query.all():
        db_session.delete(queue)
    for user in User.query.all():
        db_session.delete(user)

    db_session.commit()

    logger.info('Finished initializing database.')
Example #18
0
def init_and_clear_db():
    # Initializing the database schema
    init_db()

    # Removing all pulse users created by the web app
    for user in User.query.all():
        try:
            pulse_management.delete_user(user.username)
        except PulseManagementException:
            pass

    # Clearing the database from old data
    for queue in Queue.query.all():
        db_session.delete(queue)
    for user in User.query.all():
        db_session.delete(user)

    db_session.commit()

    logger.info('Finished initializing database.')
Example #19
0
    def setUp(self):
        init_and_clear_db()
        self.management_api = PulseManagementAPI()
        self.guardian = PulseGuardian(self.management_api,
                                      warn_queue_size=TEST_WARN_SIZE,
                                      del_queue_size=TEST_DELETE_SIZE,
                                      emails=False)

        self.consumer_cfg = pulse_cfg.copy()
        self.consumer_cfg['applabel'] = str(uuid.uuid1())

        # Configure / Create the test user to be used for message consumption
        self.consumer_cfg['user'], self.consumer_cfg[
            'password'] = CONSUMER_USER, CONSUMER_PASSWORD
        username, password = self.consumer_cfg['user'], self.consumer_cfg[
            'password']
        self.user = User.new_user(username=username,
                                  email=CONSUMER_EMAIL,
                                  password=password,
                                  management_api=self.management_api)
        db_session.add(self.user)
        db_session.commit()

        self.publisher = self.publisher_class(**pulse_cfg)
Example #20
0
def dummy_data():
    # Dummy test users
    for i in xrange(4):
        User.new_user(email='dummy{0}@dummy.com'.format(i),
                      username='******'.format(i),
                      password='******',
                      management_api=pulse_management)

    users = User.query.all()

    # And some dummy queues
    dummy_queue = Queue(name='dummy-empty-queue', size=0, owner=users[0])
    db_session.add(dummy_queue)
    db_session.commit()

    dummy_queue = Queue(name='dummy-non-empty-queue',
                        size=config.warn_queue_size / 5,
                        owner=users[0])
    db_session.add(dummy_queue)
    db_session.commit()

    dummy_queue = Queue(name='dummy-warning-queue',
                        size=config.warn_queue_size + 1,
                        owner=users[1])
    db_session.add(dummy_queue)
    db_session.commit()

    dummy_queue = Queue(name='dummy-deletion-queue',
                        size=int(config.del_queue_size * 1.2),
                        owner=users[2])
    db_session.add(dummy_queue)
    db_session.commit()

    # Test admin user
    User.new_user(email='*****@*****.**',
                  username='******',
                  password='******',
                  management_api=pulse_management,
                  admin=True)

    logger.info('Finished generating dummy data.')