Пример #1
0
    def test_post__success_empty_db(self):
        data_user = User.get()
        data_address = {
            'user_id': data_user.uuid,
            'nation': 'Italia',
            'city': 'Prato',
            'postal_code': '59100',
            'local_address': 'Via Roncioni 10',
            'phone': '0574100100',
        }

        resp = self.app.post('/addresses/', data=data_address)

        query = Address.select()
        address_from_db = Address.get()
        expected_data = {
            'user_id': address_from_db.user.uuid,
            'nation': address_from_db.nation,
            'city': address_from_db.city,
            'postal_code': address_from_db.postal_code,
            'local_address': address_from_db.local_address,
            'phone': address_from_db.phone,
        }
        assert expected_data == data_address
        assert resp.status_code == CREATED
        assert len(query) == 1
        assert query.get().json() == json.loads(resp.data.decode())
Пример #2
0
    def test_delete__success(self):
        data_user = User.get()
        data_address1 = Address.create(
            uuid=uuid.uuid4(),
            user=data_user,
            nation='Italia',
            city='Prato',
            postal_code='59100',
            local_address='Via Roncioni 10',
            phone='0574100100',
        )
        data_address2 = Address.create(
            uuid=uuid.uuid4(),
            user=data_user,
            nation='Italia',
            city='Firenze',
            postal_code='59000',
            local_address='Via Baracca 10',
            phone='0558778666',
        )

        resp = self.app.delete('/addresses/{}'.format(data_address1.uuid))
        all_addresses = Address.select()
        address_from_db = all_addresses.get()
        assert resp.status_code == NO_CONTENT
        assert len(all_addresses) == 1
        assert address_from_db.uuid == data_address2.uuid
Пример #3
0
    def test_post__success(self):
        data_user = User.get()
        address_id_created = uuid.uuid4()
        Address.create(
            uuid=address_id_created,
            user=data_user,
            nation='Italia',
            city='Prato',
            postal_code='59100',
            local_address='Via Roncioni 10',
            phone='0574100100',
        )

        data_address = {
            'user_id': data_user.uuid,
            'nation': 'Italia',
            'city': 'Prato',
            'postal_code': '59100',
            'local_address': 'Via Roncioni 10',
            'phone': '0574100100',
        }

        resp = self.app.post('/addresses/', data=data_address)
        query = Address.select().where(Address.uuid != address_id_created)
        assert resp.status_code == CREATED
        assert query.get().json() == json.loads(resp.data.decode())
Пример #4
0
def update_address_details(request, address_id):

    if request.method == 'PUT':

        try:

            payload = json.loads(request.body)

            user_id = payload['user_id']
            town = payload['town']
            estate = payload['estate']
            street_number = payload['street_number']
            status = payload['status']
            stayed_from = payload['stayed_from']

            address_data = Address(user_id=user_id,
                                   town=town,
                                   estate=estate,
                                   street_number=street_number,
                                   status=status,
                                   stayed_from=stayed_from)

            response = address_data.update_address_data(address_id)

        except:
            response = json.dumps([{'message': 'invalid request'}])

    return HttpResponse(response, content_type='text/json')
Пример #5
0
    def put(self, address_id):
        json = request.get_json()
        try:
            address = (Address.select().where(
                Address.uuid == address_id).where(
                    Address.user == g.current_user).get())
        except Address.DoesNotExist:
            return None, NOT_FOUND

        try:
            Address.verify_json(json)
        except ValidationError as err:
            return {"message": err.message}, BAD_REQUEST

        if address.user.uuid == g.current_user.uuid:
            address.nation = json['nation']
            address.city = json['city']
            address.postal_code = json['postal_code']
            address.local_address = json['local_address']
            address.phone = json['phone']
            address.save()

            return address.json(), CREATED
        else:
            return '', BAD_REQUEST
Пример #6
0
    def test_post__success_empty_db(self):
        data_address = {
            'nation': 'Italia',
            'city': 'Prato',
            'postal_code': '59100',
            'local_address': 'Via Roncioni 10',
            'phone': '0574100100',
        }

        resp = self.open_with_auth('/addresses/',
                                   'post',
                                   self.user.email,
                                   'p4ssw0rd',
                                   data=data_address)

        address_from_db = Address.get()
        expected_data = {
            'nation': address_from_db.nation,
            'city': address_from_db.city,
            'postal_code': address_from_db.postal_code,
            'local_address': address_from_db.local_address,
            'phone': address_from_db.phone,
        }
        assert expected_data == data_address
        assert resp.status_code == CREATED
        assert len(Address.select()) == 1
        assert address_from_db.json() == json.loads(resp.data.decode())
def test_is_hogemail(session):
    # Add user
    user1 = User(name='name_1', fullname='fullname_1', nickname='nickname_1')
    user2 = User(name='name_2', fullname='fullname_2', nickname='nickname_2')
    user3 = User(name='name_3', fullname='fullname_3', nickname='nickname_3')

    for user in [user1, user2, user3]:
        session.add(user)

    # Add address
    address1 = Address(email_address='*****@*****.**',
                       user_id=user1.user_id,
                       user=user1)
    address2 = Address(email_address='*****@*****.**',
                       user_id=user2.user_id,
                       user=user2)
    address3 = Address(email_address='address_3@hogemailcom',
                       user_id=user3.user_id,
                       user=user3)

    for address in [address1, address2, address3]:
        session.add(address)

    # Execute test
    result = is_hogemails(session)
    assert not result
Пример #8
0
def _parse_wrapping_event(ts: str, fields: dict[str, str]) -> WrappingEvent:
    sender: Address = Address(fields["sender (NineChronicles)"])
    recipient: Address = Address(fields["recipient (Ethereum)"])
    amount: float = float(fields["amount"])
    fee: float = float(fields["fee"])

    nc_tx = fields["9c network transaction"].replace("<", "").replace(">", "")
    eth_tx = fields["Ethereum network transaction"].replace("<", "").replace(">", "")

    refund_txid: Optional[TxId] = _map(fields.get("refund transaction"), lambda x: TxId(urllib3.util.url.parse_url(x.replace("<", "").replace(">", "")).query))
    refund_amount = _map(fields.get("refund amount"), float)

    nc_txid: TxId = TxId(urllib3.util.url.parse_url(nc_tx).query)

    network_type = NetworkType(urllib3.util.url.parse_url(nc_tx).path.split("/")[1])
    eth_txid = TxId(urllib3.util.url.parse_url(eth_tx).path.split("/")[-1])

    return WrappingEvent(
        network_type,
        ts,
        sender,
        recipient,
        amount,
        fee,
        nc_txid,
        eth_txid,
        refund_txid,
        refund_amount,
    )
Пример #9
0
    def test_put__success(self):
        data_user = User.get()
        data_address = Address.create(
            uuid=uuid.uuid4(),
            user=data_user,
            nation='Italia',
            city='Prato',
            postal_code='59100',
            local_address='Via Roncioni 10',
            phone='0574100100',
        )

        new_data_address = {
            'user_id': data_user.uuid,
            'nation': 'Italia',
            'city': 'Firenze',
            'postal_code': '505050',
            'local_address': 'Via Baracca 15',
            'phone': '0550550550',
        }

        resp = self.app.put('/addresses/{}'.format(data_address.uuid),
                            data=new_data_address)
        address_from_db = Address.get()
        expected_data = {
            'user_id': address_from_db.user.uuid,
            'nation': address_from_db.nation,
            'city': address_from_db.city,
            'postal_code': address_from_db.postal_code,
            'local_address': address_from_db.local_address,
            'phone': address_from_db.phone,
        }
        assert expected_data == new_data_address
        assert resp.status_code == CREATED
        assert address_from_db.json() == json.loads(resp.data.decode())
Пример #10
0
def address():
    if request.method == 'POST':
        app.logger.debug('Args: {}'.format(request.args))
        restaurant_id = int(request.args.get('restaurant_id', ''))
        address = to_string(request.args.get('address', ''))
        state = to_string(request.args.get('state', ''))
        city = to_string(request.args.get('city', ''))
        zip_code = int(request.args.get('zip', ''))
        r = Restaurant.query.filter(
            Restaurant.id == restaurant_id).first_or_404()
        address = Address.create(address, state, city, zip_code, restaurant=r)
        return json_response({'response': 'Created', 'id': address.id})
    elif request.method == 'GET':
        response_list = list()
        restaurant_id = int(request.args.get('restaurant_id', 0))
        results = Address.get_address_by(restaurant_id)
        app.logger.debug('Address: {}'.format(results))
        if results:
            for result in results:
                response_list.append({
                    'address': result.address,
                    'state': result.state,
                    'city': result.city,
                    'restaurant_id': result.restaurant_id,
                    'id': result.id
                })
        return json_response(response_list)
Пример #11
0
    def setUp(self):
        """Create test client, add sample data."""

        db.drop_all()
        db.create_all()

        self.client = app.test_client()

        # add states
        s1 = State(name="oh")
        s2 = State(name="ca")
        s3 = State(name="ny")
        s4 = State(name="nc")
        db.session.add_all([s1, s2, s3, s4])
        db.session.commit()

        # add test users
        self.testuser = User.signUp(username="******",
                                    password="******",
                                    email="*****@*****.**",
                                    address_line1="123 Sunset Ave",
                                    address_line2="Apt B",
                                    state_name="ca",
                                    zip_code="99999")
        db.session.commit()

        self.testuser = User.query.get(self.testuser.id)

        self.testuser_id = 111
        self.testuser.id = self.testuser_id
        db.session.commit()

        a1 = Address(user_id=self.testuser_id,
                     address_line1="123 Street",
                     state_name="ri",
                     zip_code="43015",
                     favorite=True,
                     nickname="Brutus's House")
        a3 = Address(user_id=self.testuser_id,
                     address_line1="789 Street",
                     state_name="ny",
                     zip_code="88888",
                     favorite=False,
                     nickname="Sister's House")
        a4 = Address(user_id=self.testuser_id,
                     address_line1="112 Street",
                     state_name="nc",
                     zip_code="88888",
                     favorite=True,
                     nickname="Vacation Home")
        db.session.add_all([a1, a3, a4])
        db.session.commit()

        ua1 = User_Addresses(user_id=self.testuser_id, address_id=4)
        ua2 = User_Addresses(user_id=self.testuser_id, address_id=5)
        ua3 = User_Addresses(user_id=self.testuser_id, address_id=6)

        db.session.add_all([ua1, ua2, ua3])
        db.session.commit()
 def test_create_user_and_addr2(self):
     user = User(id=3, name="Alice", fullname="Alice Brown")
     user.addresses = [
         Address(id=4, email_address="*****@*****.**"),
         Address(id=5, email_address="*****@*****.**")
     ]
     session.add(user)
     session.commit()
Пример #13
0
def save_email_addresses(addresses_field: Text):
    '''Save email addresses from Text widget'''
    text = addresses_field.get(1.0, END)

    addresses = [{'email': address.strip()} for address in text.split('\n')]

    Address.delete().where(True).execute()
    Address.insert_many(addresses).execute()
Пример #14
0
def create_tables():
    User.create_table(fail_silently=True)
    Item.create_table(fail_silently=True)
    Address.create_table(fail_silently=True)
    Order.create_table(fail_silently=True)
    OrderItem.create_table(fail_silently=True)
    Picture.create_table(fail_silently=True)
    Favorite.create_table(fail_silently=True)
Пример #15
0
def newRestaurant():
    '''
    {
    "name" : "Drums",
    "category" : "Italian",
    "street" : "254 PLX St.",
    "city" : "Arlington",
    "state" : "TX",
    "zipcode" : 75043

    }
    '''

    restaurantName = request.get_json()["name"]
    categoryName = request.get_json()["category"]

    street = request.get_json()["street"]
    city = request.get_json()["city"]
    state = request.get_json()["state"]
    zipcode = request.get_json()["zipcode"]

    try:
        restaurant_exists = session.query(Restaurant).filter(
            Restaurant.restaurant_name == restaurantName).scalar() is not None
        address_exists = session.query(Address).filter(
            Address.address == street, Address.city == city,
            Address.state == state,
            Address.zipcode == zipcode).scalar() is not None

    except ValueError:
        return ("Unexpected error:", sys.exc_info()[0])

    if restaurant_exists:
        if address_exists:
            return 'Restaurant Already Exists'
        else:
            newAddress = Address(address=street,
                                 city=city,
                                 state=state,
                                 zipcode=zipcode,
                                 restaurant_name=restaurantName)
            session.add(newAddress)
            session.commit()
            return "New Retaurant added"
    else:
        newRestaurant = Restaurant(restaurant_name=restaurantName,
                                   restaurant_category=categoryName)
        newAddress = Address(address=street,
                             city=city,
                             state=state,
                             zipcode=zipcode,
                             restaurant_name=newRestaurant.restaurant_name)

        session.add(newRestaurant)
        session.add(newAddress)
        session.commit()
        return "New Retaurant added"
Пример #16
0
def load_email_addresses_from_file(field: Text):
    address_records = prepare_email_addresses()
    Address.delete().where(True).execute()
    field.delete(1.0, END)

    Address.insert_many(address_records).execute()

    load_addresses_to_field(field)
    save_email_addresses(field)
Пример #17
0
    def test_validate_address_json__success(self):
        data = {
            'user': str(uuid.uuid4()),
            'nation': 'Italia',
            'city': 'Prato',
            'postal_code': '59100',
            'local_address': 'Via Roncioni 10',
            'phone': '0574100100',
        }

        Address.verify_json(data)
Пример #18
0
    def test_validate_address_json__failure_missing_field(self):
        data = {
            'user': str(uuid.uuid4()),
            'nation': 'Italia',
            'postal_code': '59100',
            'local_address': 'Via Roncioni 10',
            'phone': '0574100100',
        }

        with pytest.raises(ValidationError):
            Address.verify_json(data)
Пример #19
0
def drop_tables():
    database.connect()

    # Initialize db by deleting all tables
    Item.drop_table(fail_silently=True)
    User.drop_table(fail_silently=True)
    Address.drop_table(fail_silently=True)
    Order.drop_table(fail_silently=True)
    OrderItem.drop_table(fail_silently=True)
    Picture.drop_table(fail_silently=True)

    database.close()
Пример #20
0
def create_tables():
    database.connect()

    # Create new table with the same name
    Item.create_table()
    User.create_table()
    Address.create_table()
    Order.create_table()
    OrderItem.create_table()
    Picture.create_table()

    database.close()
Пример #21
0
    def post(self):
        coordinates_str = self.request.get('coordinates')
        min_sum = self.request.get_range('min_sum')
        delivery_sum = self.request.get_range('delivery_sum')
        free_delivery_sum = self.request.get_range('free_delivery_sum')

        coordinates = ast.literal_eval(coordinates_str)

        ribs_num = len(coordinates) - 1

        delivery_zone = DeliveryZone()
        delivery_zone.sequence_number = DeliveryZone.generate_sequence_number()

        geo_ribs = []
        for i in range(0, ribs_num - 1):
            start_point = coordinates[i]
            end_point = coordinates[i + 1]

            geo_rib = GeoRib()
            geo_rib.point1 = GeoPt(lat=start_point[1], lon=start_point[0])
            geo_rib.point2 = GeoPt(lat=end_point[1], lon=end_point[0])
            geo_ribs.append(geo_rib)

        start_point = coordinates[ribs_num - 1]
        end_point = coordinates[0]
        last_rib = GeoRib()
        logging.debug('start_point: {}'.format(coordinates))
        last_rib.point1 = GeoPt(lat=start_point[1], lon=start_point[0])
        last_rib.point2 = GeoPt(lat=end_point[1], lon=end_point[0])

        delivery_zone.geo_ribs = geo_ribs

        lat, lon = get_mean_coordinate(geo_ribs)
        candidates = get_cities_by_coordinates(lat, lon)
        if candidates:
            logging.critical('CANDIDATES')
            address = candidates[0]['address']
            address_obj = Address(**address)
            address_obj.lat = lat
            address_obj.lon = lon
            candidates = get_areas_by_coordinates(lat, lon)
            if candidates:
                address_obj.area = candidates[0]['address']['area']
            delivery_zone.address = address_obj

        delivery_zone.search_type = ZONE
        delivery_zone.price = delivery_sum
        delivery_zone.min_sum = min_sum
        delivery_zone.free_delivery_sum = free_delivery_sum
        delivery_zone.put()

        self.redirect('/company/delivery/zone/list')
Пример #22
0
def create_tables():
    auth.User.create_table(fail_silently=True)
    Users.create_table(fail_silently=True)
    Role.create_table(fail_silently=True)
    Category.create_table(fail_silently=True)
    Product.create_table(fail_silently=True)
    Period.create_table(fail_silently=True)
    Order_detail.create_table(fail_silently=True)
    Address.create_table(fail_silently=True)
    Show.create_table(fail_silently=True)
    UserRoles.create_table(fail_silently=True)
    Configure.create_table(fail_silently=True)
    WinRecord.create_table(fail_silently=True)
Пример #23
0
def save_order_addresses(id):
    user_authenticated_id = get_jwt_identity()

    pickup_address = Address(address=request.json.get('pickup').get('address'),
                             city=request.json.get('pickup').get('city'),
                             country=request.json.get('pickup').get('country'),
                             cp=request.json.get('pickup').get('CP'),
                             user_id=user_authenticated_id)
    pickup_address.save()

    delivery_address = Address(
        address=request.json.get('delivery').get('address'),
        city=request.json.get('delivery').get('city'),
        country=request.json.get('delivery').get('country'),
        cp=request.json.get('delivery').get('CP'),
        user_id=user_authenticated_id)
    delivery_address.save()

    order = Order.query.get(id)

    order.address_delivery = delivery_address
    order.address_pickup = pickup_address

    order.save()

    DBManager.commitSession()
    order_new_data_mail(order)

    return jsonify(order.serializeForEditView()), 200
Пример #24
0
 def test_delete__address_id_not_exists(self):
     data_user = User.get()
     Address.create(
         uuid=uuid.uuid4(),
         user=data_user,
         nation='Italia',
         city='Prato',
         postal_code='59100',
         local_address='Via Roncioni 10',
         phone='0574100100',
     )
     resp = self.app.delete('/addresses/{}'.format(uuid.uuid4()))
     assert resp.status_code == NOT_FOUND
     assert len(Address.select()) == 1
def show(id=1):
    try:
        m_addresses = Address()
        m_address = m_addresses.read_data(id)
        # html or Json response
        if request_wants_json():
            return jsonify(data = m_address)
        else:
            return render_template("addresses/show.html", address=m_address, app = app)

    except Exception, ex:
        print("------------ ERROR  ------------\n" + str(ex.message))
        flash(str(ex.message), category="warning")
        abort(404)
Пример #26
0
def create_address():
    address = Address()
    address_hash = getHash(address)
    address.number = "%s" % address_hash
    address.street = "street %s" % address_hash
    address.neighbourhood = "neighbourhood %s" % address_hash
    address.city = "city %s" % address_hash
    address.federal_state = "federal_state %s" % address_hash
    address.cep = "cep %s" % address_hash
    address.country = "country %s" % address_hash
    return address
Пример #27
0
def address_creator(num_addr):
    LIST_COUNTRIES = [
        'Belgium', 'France', 'Germany', 'Greece', 'Italy', 'Portugal', 'Spain'
    ]
    for i in range(num_addr):
        country = random.choice(LIST_COUNTRIES)
        Address.create(
            uuid=fake.uuid4(),
            user=User.select().order_by(fn.Random()).get(),
            country=country,
            city=fake.city(),
            post_code=fake.postcode(),
            address=fake.street_name(),
            phone=fake.phone_number(),
        )
Пример #28
0
    def setup_class(cls):
        db = SqliteDatabase(':memory:')
        User._meta.database = db
        Address._meta.database = db
        User.create_table()
        Address.create_table()
        cls.app = app.test_client()

        User.create(
            uuid=uuid.uuid4(),
            first_name='Mario',
            last_name='Rossi',
            email='*****@*****.**',
            password='******',
        )
Пример #29
0
def _parse_unwrapping_failure_event(ts: str, fields: dict[str, str]) -> UnwrappingFailureEvent:
    sender: Address = Address(fields["sender (Ethereum)"])
    recipient: Address = Address(fields["recipient (NineChronicles)"])
    amount: float = float(fields["amount"])

    eth_tx = fields["Ethereum transaction"].replace("<", "").replace(">", "")
    eth_txid = TxId(urllib3.util.url.parse_url(eth_tx).path.split("/")[-1])

    return UnwrappingFailureEvent(
        ts,
        sender,
        recipient,
        amount,
        eth_txid,
    )
Пример #30
0
def _parse_refund_event_slack_response(message: SlackResponse) -> Optional[RefundEvent]:
    if "attachments" not in message:
        return None

    attachment: dict = message["attachments"][0]

    if "fields" not in attachment:
        return None

    fields = dict(map(lambda x: (x["title"], x["value"]), attachment["fields"]))
    print(fields)

    address: Address = Address(fields["Address"])
    reason: str = fields["Reason"]
    request_txid = urllib3.util.url.parse_url(fields["Request transaction"].replace("<", "").replace(">", "")).query
    refund_txid = urllib3.util.url.parse_url(fields["Refund transaction"].replace("<", "").replace(">", "")).query
    request_amount = float(fields["Request Amount"])
    refund_amount = float(fields["Refund Amount"])
    return RefundEvent(
        request_amount=request_amount,
        request_txid=request_txid,
        address=address,
        reason=reason,
        refund_txid=refund_txid,
        refund_amount=refund_amount,
        ts=message["ts"],
        network_type=NetworkType.MAINNET
    )
Пример #31
0
    def test_should_have_creditcard_as_addressable(self):
        """
        Prueba que una direccion pueda ser asociada
        a una tarjeta de credito
        """

        credit_card = CreditCard(number="1111111111")
        credit_card.save()

        address = Address()
        address.street1 = "Cra 7 # 6-19"
        address.addressable_object = credit_card 
        address.save()

        address_from_db = Address.objects.get(id=address.id)
        self.assertEqual(address_from_db.addressable_type.name, 'credit card')
Пример #32
0
    def test_should_have_user_as_addressable(self):
        """
        Prueba que una direccion pueda ser asociada
        a un usuario
        """

        user = User(email="*****@*****.**", name="nada", last_name="mas")
        user.save()

        address = Address()
        address.street1 = "Cra 7 # 6-19"
        address.addressable_object = user
        address.save()

        address_from_db = Address.objects.get(id=address.id)
        self.assertEqual(address_from_db.addressable_type.name, 'user')
Пример #33
0
    def test_should_have_store_location_as_addressable(self):
        """
        Prueba que una direccion pueda ser asociada
        a una ubicacion de tienda
        """

        store = StoreLocation(city="Chia")
        store.save()

        address = Address()
        address.street1 = "Cra 7 # 6-19"
        address.addressable_object = store 
        address.save()

        address_from_db = Address.objects.get(id=address.id)
        self.assertEqual(address_from_db.addressable_type.name, 'store location')
Пример #34
0
    def test_should_have_store_as_addressable(self):
        """
        Prueba que una direccion pueda ser asociada
        a una tienda
        """

        store = Store(name="My store")
        store.save()

        address = Address()
        address.street1 = "Cra 7 # 6-19"
        address.addressable_object = store 
        address.save()

        address_from_db = Address.objects.get(id=address.id)
        self.assertEqual(address_from_db.addressable_type.name, 'store')
Пример #35
0
def flush():
    ndb.delete_multi(School.query().fetch(keys_only=True))
    ndb.delete_multi(QuestionInstance.query().fetch(keys_only=True))
    ndb.delete_multi(State_Questions.query().fetch(keys_only=True))
    ndb.delete_multi(Topic_States.query().fetch(keys_only=True))
    ndb.delete_multi(Question.query().fetch(keys_only=True))
    ndb.delete_multi(State.query().fetch(keys_only=True))
    ndb.delete_multi(Address.query().fetch(keys_only=True))
    ndb.delete_multi(Teacher.query().fetch(keys_only=True))
    ndb.delete_multi(Class.query().fetch(keys_only=True))
    ndb.delete_multi(Assessment_Record.query().fetch(keys_only=True))
    ndb.delete_multi(Student.query().fetch(keys_only=True))
    ndb.delete_multi(UserInfo.query().fetch(keys_only=True))
    ndb.delete_multi(Student_Assessments.query().fetch(keys_only=True))
    ndb.delete_multi(Assessment.query().fetch(keys_only=True))
    ndb.delete_multi(Subject.query().fetch(keys_only=True))
    ndb.delete_multi(Topic_Questions.query().fetch(keys_only=True))
    ndb.delete_multi(State_Questions.query().fetch(keys_only=True))
    ndb.delete_multi(Topic_States.query().fetch(keys_only=True))
    ndb.delete_multi(Subject_Topics.query().fetch(keys_only=True))
    ndb.delete_multi(Student_Assessments.query().fetch(keys_only=True))
    ndb.delete_multi(Topic.query().fetch(keys_only=True))
    ndb.delete_multi(User.query().fetch(keys_only=True))
    ndb.delete_multi(Assessment_Record.query().fetch(keys_only=True))
    ndb.delete_multi(State_Types.query().fetch(keys_only=True))
Пример #36
0
def registration(request):
    if request.user.is_authenticated():
        # ideal, but not created yet, going with homepage
        #return HttpResponseRedirect('/profile/')
        return HttpResponseRedirect('/')
    if request.method == 'POST':
        #fills out with whatever was posted
        form = RegistrationForm(request.POST)
        # runs all clean methods in form
        if form.is_valid():
            try: #customer exists
                cusAlreadyExists = User.objects.get(username=
                                form.cleaned_data['username'])
                username_taken = True
                context = {'form': form, 'username_taken': username_taken}
                return render_to_response('register.html', context,
                                context_instance=RequestContext(request))
            except User.DoesNotExist: #customer did not exist
                user = User.objects.create_user(
                    username=form.cleaned_data['username'],
                    password=form.cleaned_data['password1'])
                user.save()
                addr = Address(
                    AddressLineOne = form.cleaned_data['street'],
                    City = form.cleaned_data['city'],
                    State = form.cleaned_data['state'],
                    ZIPCode = form.cleaned_data['zipcode']
                )
                addr.save()
                customer = Customer(user=user, Address=addr,
                    FirstName = form.cleaned_data['firstName'],
                    LastName = form.cleaned_data['lastName']
                )
                customer.save()
                customer = authenticate(username=form.cleaned_data['username'],
                    password=form.cleaned_data['password1'])
                login(request, customer)
                return HttpResponseRedirect('/')
        else:
            return render_to_response('register.html', {'form': form},
                                    context_instance=RequestContext(request))
    else:
        #user not submitting the form, send blank form
        form = RegistrationForm()
        context = {'form': form}
        return render_to_response('register.html', context,
                                    context_instance=RequestContext(request))
Пример #37
0
def get_or_create_person(address_tuple):
    name, email_address = address_tuple
    existing_addresses = Address.objects.filter(email=email_address.lower())
    if len(existing_addresses) == 0:
        new_person = Person(name=name)
        new_person.save()
        new_address = Address(email=email_address.lower(), person=new_person)
        new_address.save()
        return new_address
    elif len(existing_addresses) > 0:
        if len(existing_addresses) > 1:
            print "found multiple db entries for address %s - returning first" % email_address
        existing_address = existing_addresses[0]
        if existing_address.person.name == '':
            existing_address.person.name = name
            existing_address.person.save()
        return existing_address
Пример #38
0
def address_create():
	address_form = AddressForm(request.form)
	user = auth.get_logged_in_user()
	if request.method == "POST":
		address = Address(
			user = user,
			street=address_form.street.data,
			zipcode=address_form.zipcode.data,
			state=address_form.state.data,
			country=address_form.country.data
			)
		address.save()
		flash("Address successfully saved")
		return redirect(url_for("dashboard"))
	elif request.method == "GET":
		try:
			exist = Address.select().where(Address.user == user).get()
			return redirect(url_for("address"))
		except Address.DoesNotExist:
			if request.method == "POST":
				address = Address(
					user = user,
					street=address_form.street.data,
					zipcode=address_form.zipcode.data,
					state=address_form.state.data,
					country=address_form.country.data
					)
				address.save()
				flash("Address successfully saved")
				return redirect(url_for("dashboard"))
			else:
				return render_template("address_create.html", address_form=address_form)
Пример #39
0
def add_address(object, id):
    """
    Ajout une address dans la base de données et retourne la clé de l'adresse    """
    if id is not None and id != "":
        cle = ndb.Key("Address", long(id))
        newUserAddress = cle.get()
        if newUserAddress is None:
            newUserAddress = Address()
    else:
        newUserAddress = Address()

    newUserAddress.civicNo = object["civicNo"]
    newUserAddress.routeName = object["routeName"]
    newUserAddress.postalCode = object["postalCode"]
    newUserAddress.appartNo = object["appartNo"]
    newUserAddress.long = object["long"]
    newUserAddress.lat = object["lat"]
    return newUserAddress.put()

    newUser.idAddress = newUserAddress.put().id()
Пример #40
0
def get_address_by_coordinates(latitude, longitude):
    """Returns address object by coordinates"""
    try:
        address = Address.objects.get(latitude=Decimal(latitude), longitude=Decimal(longitude))
    except ObjectDoesNotExist:

        try:
            address_chunks = gm_get_location(Decimal(latitude), Decimal(longitude))
        except:
            return None

        town, created = Town.objects.get_or_create(name=address_chunks['town'])
        street, created = Street.objects.get_or_create(name=address_chunks['street'], town=town)

        street_number = address_chunks['number']
        address = Address(street=street, street_number=street_number)
        address.save()
    else:
        return None

    return address
Пример #41
0
    def __get_address(self, cep):
        page = pq(url=self.CORREIOS_URL % cep)
        fields = page.find(".resposta")
        err = page.find(".erro").text()
        
        result = SearchAddrResult()

        if not err is None:
            result.message = err
            result.status = SearchAddrStatus.NOT_FOUND
            return result

        city, state = self.__get_field(fields, "Localidade / UF").split('/')

        address = Address()
        address.street = self.__get_field(fields, "Logradouro")
        address.district = self.__get_field(fields, "Bairro")
        address.city = city.strip('\n').strip()
        address.state =  state.strip('\n').strip()
        address.cep = cep
        
        result.address = address
        result.status = SearchAddrStatus.FOUND
        
        return result
Пример #42
0
    def setUp(self):

        # create classifcation
        self.classification = create_classification('Men\'s Open')

        # create an Address and a Field
        self.address = Address(street='ABC Street')
        self.address.save()
        self.field = Field(name='Field 1', address=self.address)
        self.field.save()

        # create teams
        self.team_1 = create_team('Team 1', self.classification)
        self.team_2 = create_team('Team 2', self.classification)

        # create some players
        self.player_1 = create_player('One', '1')
        self.player_2 = create_player('Two', '2')
        self.player_3 = create_player('Three', '3')

        # assign the players
        self.playfor_1 = PlayFor(player=self.player_1, team=self.team_1, from_date=datetime.date.today())
        self.playfor_1.save()
        self.playfor_2 = PlayFor(player=self.player_2, team=self.team_1, from_date=datetime.date.today())
        self.playfor_2.save()
        self.playfor_3 = PlayFor(player=self.player_3, team=self.team_1, from_date=datetime.date.today())
        self.playfor_3.save()

        # create referee
        person = Person(first_name='Ref', last_name='Ref')
        person.save()
        self.referee = Referee(person=person)
        self.referee.save()

        # create two seasons
        self.season_1 = create_season(self.classification, 'Division 1', '2014-2015', datetime.date.today(), datetime.date.today())
        self.season_2 = create_season(self.classification, 'Division 2', '2015-2016', datetime.date.today(), datetime.date.today())

        # create some games
        self.matchday_season_1 = Matchday(season=self.season_1, label='1', date=datetime.date.today())
        self.matchday_season_1.save()
        self.game_season_1 = Game(matchday=self.matchday_season_1, date=datetime.date.today(),
            away_team=self.team_1, home_team=self.team_2, referee=self.referee,
            played=True, field=self.field)
        self.game_season_1.save()

        self.matchday_season_2 = Matchday(season=self.season_2, label='2', date=datetime.date.today())
        self.matchday_season_2.save()
        self.game_season_2 = Game(matchday=self.matchday_season_2, date=datetime.date.today(),
            away_team=self.team_1, home_team=self.team_1, referee=self.referee,
            played=True, field=self.field)
        self.game_season_2.save()
Пример #43
0
 def _parse_resource(self, resource):
     address = resource['address']
     log.debug('Matched address is %s', address)
     parsed_address=Address()
     street=address.get('road') or address.get('pedestrian') or address.get('village') or address.get('hamlet')
     if address.get('house_number') and street:
         street+=' '+address['house_number']
     parsed_address.street=street
     parsed_address.city=address.get('city') or address.get('town')
     parsed_address.country=address.get('country')
     parsed_address.county=address.get('county')
     parsed_address.state=address.get('state')
     parsed_address.postal_code=address.get('postcode')
     
     
     latitude = resource['lat'] or None
     longitude = resource['lon'] or None
     if latitude and longitude:
         latitude = float(latitude)
         longitude = float(longitude)
     
     return (parsed_address, (latitude, longitude))
Пример #44
0
def do(request, nid, aid, browser_tab):
    WZ = Z.SetWhoZwho(request, browser_tab)
    if WZ['ErrorMessage']:
        return GoLogout(request, WZ)

    try:
        name = Name.objects.get(pk=int(nid))
    except:
        return GoLogout(request, WZ, "[EA01]: URL containd an invalid name ID.")

        if WZ['Authority'] < Z.Admin and name.owner != WZ['AuthorizedOwner']:
            return GoLogout(request, WZ, "[EA02]: URL containd an invalid name ID.")

    if aid != '0':
        try:
            address = Address.objects.get(pk=int(aid))
        except:
            return GoLogout(request, WZ, "[EA03]: URL containd an invalid addressID.")

        if address.owner != name.owner:
            return GoLogout(request, WZ, "[EA04]: URL containd an invalid address ID.")

        if WZ['Authority'] < Z.Admin and address.owner != WZ['AuthorizedOwner']:
            return GoLogout(request, WZ, "[EA05]: URL containd an invalid ID.")

    if request.method == 'POST': # If the form has been submitted...
        form = DirectoryEditAddressForm(request.POST, request.FILES)
        if form.is_valid():
            if aid == '0':
                address = Address()
                address.owner = name.owner

            address.street = form.cleaned_data['street']
            address.address_line2 = form.cleaned_data['address_line2']
            address.municipality = form.cleaned_data['municipality']
            address.city = form.cleaned_data['city']
            address.province = form.cleaned_data['province']
            address.country = form.cleaned_data['country']
            address.postcode = form.cleaned_data['postcode']
            address.phone = form.cleaned_data['home_phone']
            address.save()

            if aid == '0':
                name.address_id = address.id
                name.save()

            logger.info(WZ['User'] + ' EA ' + str(request.POST))

            if name.private == True:
                return HttpResponseRedirect('/WhoZwho/editpc/' + nid + '/' + browser_tab)
            else:
                return HttpResponseRedirect('/WhoZwho/ename/' + nid + '/' + browser_tab)
        else:
            WZ['ErrorMessage'] = str(form.errors)
    else:
        if aid == '0':
            form = DirectoryEditAddressForm()
        else:
            form = DirectoryEditAddressForm(initial={
                'street': address.street,
                'address_line2': address.address_line2,
                'municipality': address.municipality,
                'city': address.city,
                'province': address.province,
                'country': address.country,
                'postcode': address.postcode,
                'home_phone': address.phone,
                }) 

    if aid == '0':
        EditAddressTitle = 'Add New Address:'
    else:
        EditAddressTitle = 'Edit Address: ' + address.street

    context = {
        'EditAddressTitle': EditAddressTitle,
        'aid': aid,
        'browser_tab': WZ['Tabs'][WZ['ActiveTab']][2],
        'form': form,
        'nid': nid,
        'WZ': WZ
        }

    context.update(csrf(request))
    return render_to_response('DirectoryEditAddress.html', context )
Пример #45
0
    (r'^login/$', 'newtest.login.login'),
    (r'^logout/$', 'newtest.login.logout'),
    (r'^wiki/$', 'newtest.wiki.views.index'),
    (r'^wiki/(?P<pagename>\w+)/$', 'newtest.wiki.views.index'),
    (r'^wiki/(?P<pagename>\w+)/edit/$', 'newtest.wiki.views.edit'),
    (r'^wiki/(?P<pagename>\w+)/save/$', 'newtest.wiki.views.save'),
    (r'^address/', include('newtest.address.urls')),

    # Uncomment this for admin:
     (r'^admin/', include('django.contrib.admin.urls')),
)

if request.POST:
    post = request.POST
    new_address = Address(
        name = post["name"],
        number = post["number"],
        telephone = post["telephone"],
        Email = post["Email"],
        address = post["address"],
        QQ = post["QQ"],
        birthday = post["birthday"],
        )
    new_address.save()



urlpatterns = patterns('',
    # ... the rest of your URLconf goes here ...
) + static(settings.STATIC_URL, document_root=settings.MEDIA_ROOT)
Пример #46
0
def import_places(temp_file, extra_params, name, description=None, private=False, 
                  user=None, existing='update', encoding='utf-8', 
                  error_cb=None, progress_cb=None, context=None,
                  format='CSV'):
    log.debug('Processing file %s with this extra params %s', temp_file, extra_params)
    errors=[]
    def add_error(line, msg):
        errors.append(_('Line %d - %s') % (line, msg))
        if error_cb:
            error_cb(line, msg)
    file_reader=fmt.get_fmt_descriptor(format).reader(temp_file, extra_params)
    exists=PlacesGroup.objects.filter(name=name, private=False).exclude(created_by=user).count()
    if exists:
        add_error(0, _('Collection with same name was created by other user'))
        return
    group, created= PlacesGroup.objects.get_or_create_ns(name=name, created_by=user)
    if created:
        group.description=description
        group.private=private
        group.save(user=user)
    elif existing=='remove':
        group.places.all().delete()
    num_lines = file_reader.count()
    with file_reader:  
        line=0    
        while True:
            line+=1
            log.debug('Processing line %d', line)
            try:
                l=file_reader.next()
            except StopIteration:
                break
            except LineError, e:
                add_error(line, e.message)
                continue
            except Exception, e:
                add_error(line, _('File reading error (%s)')% str(e))
                traceback.print_exc()
                break
            
            place_name=l['name']
            try:
                place=Place.objects.get(name=place_name, group=group)
            except Place.DoesNotExist:
                place=None
            if place and existing=='skip':
                log.debug('Skipping line %d as existing', line)
            if existing=='update' or not place:
                try:
                    with transaction.atomic():
                        if not place:
                            place=Place(name=place_name, group=group)
                        address=None
                        if l.get('address'):
                            address=Address(**l['address'])
                        place.description=l.get('description')
                        place.url=l.get('url')
                        if l.get('position'):
                            pos=l['position']      
                            place.position=Point(*pos, srid=4326)  
                        else:
                            #geocode from address
                            try:
                                new_address,point=geocode.get_coordinates_remote(address, context=context)
                            except geocode.NotFound:
                                raise LineError( _('Cannot get location for address %s')% unicode(address)) 
                            except remote.TimeoutError:
                                raise LineError(_('Geocoding process is not responding'))
                            except remote.RemoteError, e:
                                raise LineError( _('Geocoding process error (%s)')% str(e))
#                             except geocode.ServiceError, e:
#                                 raise LineError( _('Geocoding Error (%s)')% str(e))
#                             except ValueError,e:
#                                 raise LineError(_('Data Error (%s)')% str(e))
                            place.position=point
                        try:
                            if address:
                                address.save(user=user)
                                place.address=address
                            place.save(user=user)
                        except MaxObjectsLimitReached:
                            add_error(line, _('Reached limit of records per user'))   
                            break
                        except Exception, e:
                            raise LineError( _('Error saving line (%s)')%str(e))
Пример #47
0
    def post(self):
        if 'edit' not in self.request.url:
            self.response.set_status(405) 
            return
        # this method updates user information (from profile page)
        # request body contain the form values
#         data = self.request.POST[0]
        data = json.loads(self.request.body)

        user_id = logic.get_current_userid(self.request.cookies.get('user'))
        if user_id is None:
            self.response.set_status(403)
            self.response.write('')
#             self.redirect('/')
            return
#         user, status = logic.user_get(user_id, None)
#         if status != "OK":
#             self.redirect("/error")

        user = PFuser()
        if data.get('new') is not None and data.get('new') != '':
            is_new = data.get('new')
#         if data.get('first_name') is not None and data.get('first_name') != '':
#             user.first_name = data.get('first_name')
#         if data.get('role') is not None and data.get('role') != '':
#             user.role = data.get('role')
#         if data.get('last_name') != '':
#             user.last_name = data.get('last_name')
#         if data.get('first_name') != '' and data.get('last_name') != '':
#             user.full_name = data.get('first_name') + ' ' + data.get('last_name')
#         if data.get('age') != '':
#             user.age = data.get('age')
#         if data.get('gender') != '':
#             user.gender = data.get('gender')
            
            
        logging.info("DATA: " + str(data))
            
        home = Address()
        home.city = data.get('locality')
        home.province = data.get(
            'administrative_area_level_2')
        home.country = data.get('country')
        
        lat = data.get('lat')
        lon = data.get('lon')
        logging.info("lat = %s, lon = %s" % (str(lat), str(lon)))
        if isinstance(lat, (str, unicode)):
            try:
                lat = float(lat)
            except Exception:
                lat = 0.0
        if not isinstance(lat, float):
            lat = 0.0
        if isinstance(lon, (str, unicode)):
            try:
                lon = float(lon)
            except Exception:
                lon = 0.0
        if not isinstance(lon, float):
            lon = 0.0
        logging.info("lat = %s, lon = %s" % (str(lat), str(lon)))
        home.location = GeoPt(
                lat, lon)
            
        user.home = home
        
        user, status, errcode = logic.user_update(user, user_id, None)
        if status != "OK":
            self.response.set_status(errcode)
            self.response.write(status)
#             self.render("error.html", {'error_code': errcode, 'error_string': status, 'lang': LANG})
            return
#         if is_new == True or is_new == "true":
#         self.redirect('/profile/2')
        self.response.set_status(200)
        self.response.write('')
Пример #48
0
def build_delivery_address_form(request):
    """ Builds a form class representing form asking for delivery addresses for items of an order. """

    def init(self, *args, **kwargs):
        kwargs["initial"] = self.__initial
        super(self.__class__, self).__init__(*args, **kwargs)

    def has_items(self):
        """ Returns True if there are items which to choose addresses for. """
        return self.__items.exists()

    def has_addresses(self):
        """ Returns True if there are addresses which to choose from. """
        return self.__addresses.exists()

    def get_address_fields(self):
        """ Iterates through all address field_dict in form. """
        for name in self.__address_fields:
            yield BoundField(self, self.__address_fields[name], name)

    def get_item_address_pairs(self):
        """ Iterates through all (order items / address) pairs displayed on the form. """
        for field_name in self.__address_fields:
            yield (self.__items.get(id__exact = field_name.split("_")[1]),
                   self.cleaned_data.get(field_name))

    def clean_hdnValidationHash(self):
        """ Ensures that the validation hash gotten from sent form is correct. """
        given_hash = self.cleaned_data.get("hdnValidationHash")
        our_hash = ShoppingCartItem.validation_hash_for_shopping_cart(request)
        if not given_hash == our_hash:
            self.add_common_error(CHECKOUT_ERR_MSG_INVALID_HASH)

    items = ShoppingCartItem.items_of_user_with_albums_and_addresses(request.user)
    addresses = Address.addresses_of_user(request.user)
    validation_hash = ShoppingCartItem.validation_hash_for_shopping_cart(request)

    field_dict = {}
    address_field_dict = {}
    initial_value_dict = {}

    field_dict["hdnValidationHash"] = forms.CharField(
        widget = forms.HiddenInput()
    )
    initial_value_dict["hdnValidationHash"] = validation_hash

    for item in items:
        field_name = u"cmbAddress_" + unicode(item.id)

        new_field = DeliveryAddressChoiceField(
            queryset = addresses,
            empty_label = None,
            label = item.album.title
        )
        field_dict[field_name] = new_field
        address_field_dict[field_name] = new_field

        if item.deliveryAddress:
            initial_value_dict[field_name] = item.deliveryAddress

    members = {
        "__request": request,
        "__items": items,
        "__addresses": addresses,
        "__validation_hash": validation_hash,
        "base_fields": field_dict,
        "__address_fields": address_field_dict,
        "__initial": initial_value_dict,
        "has_items": has_items,
        "has_addresses": has_addresses,
        "address_fields": get_address_fields,
        "item_address_pairs": get_item_address_pairs,
        "clean_hdnValidationHash": clean_hdnValidationHash,
        "__init__": init
    }

    return type("DeliveryAddressForm", (CommonAlbumizerBaseForm,), members)
Пример #49
0
 def address_with_id(self, address_id):
     return Address.get(Address.id == address_id)
Пример #50
0
class SeasonTest(TestCase):

    def setUp(self):

        # create classifcation
        self.classification = create_classification('Men\'s Open')

        # create an Address and a Field
        self.address = Address(street='ABC Street')
        self.address.save()
        self.field = Field(name='Field 1', address=self.address)
        self.field.save()

        # create teams
        self.team_1 = create_team('Team 1', self.classification)
        self.team_2 = create_team('Team 2', self.classification)

        # create some players
        self.player_1 = create_player('One', '1')
        self.player_2 = create_player('Two', '2')
        self.player_3 = create_player('Three', '3')

        # assign the players
        self.playfor_1 = PlayFor(player=self.player_1, team=self.team_1, from_date=datetime.date.today())
        self.playfor_1.save()
        self.playfor_2 = PlayFor(player=self.player_2, team=self.team_1, from_date=datetime.date.today())
        self.playfor_2.save()
        self.playfor_3 = PlayFor(player=self.player_3, team=self.team_1, from_date=datetime.date.today())
        self.playfor_3.save()

        # create referee
        person = Person(first_name='Ref', last_name='Ref')
        person.save()
        self.referee = Referee(person=person)
        self.referee.save()

        # create two seasons
        self.season_1 = create_season(self.classification, 'Division 1', '2014-2015', datetime.date.today(), datetime.date.today())
        self.season_2 = create_season(self.classification, 'Division 2', '2015-2016', datetime.date.today(), datetime.date.today())

        # create some games
        self.matchday_season_1 = Matchday(season=self.season_1, label='1', date=datetime.date.today())
        self.matchday_season_1.save()
        self.game_season_1 = Game(matchday=self.matchday_season_1, date=datetime.date.today(),
            away_team=self.team_1, home_team=self.team_2, referee=self.referee,
            played=True, field=self.field)
        self.game_season_1.save()

        self.matchday_season_2 = Matchday(season=self.season_2, label='2', date=datetime.date.today())
        self.matchday_season_2.save()
        self.game_season_2 = Game(matchday=self.matchday_season_2, date=datetime.date.today(),
            away_team=self.team_1, home_team=self.team_1, referee=self.referee,
            played=True, field=self.field)
        self.game_season_2.save()

    def test_player_season(self):

        # add team to season
        self.season_1.enrolled.add(self.team_1)

        self.assertItemsEqual((self.team_1,), self.player_1.teams_per(self.season_1))

    def test_goals_by_season(self):

        # 2 goals in season 1 by player 1
        goal_1 = Goal(scored_by=self.playfor_1, scored_for=self.team_1,
            game=self.game_season_1)
        goal_1.save()
        goal_2 = Goal(scored_by=self.playfor_1, scored_for=self.team_1,
            game=self.game_season_1)
        goal_2.save()
        # 1 goal by player 1 in season 2
        goal_x = Goal(scored_by=self.playfor_1, scored_for=self.team_1,
            game=self.game_season_2)
        goal_x.save()
        # 1 goal in season 2 by player 2
        goal_3 = Goal(scored_by=self.playfor_2, scored_for=self.team_1,
            game=self.game_season_2)
        goal_3.save()
        # 1 own goal in season 1 by player 3
        goal_4 = Goal(scored_by=self.playfor_3,
            scored_for=self.team_2, game=self.game_season_1)
        goal_4.save()

        self.assertIn(self.player_1, self.season_1.scorers())
        self.assertNotIn(self.player_2, self.season_1.scorers())
        self.assertNotIn(self.player_3, self.season_1.scorers())
        self.assertEqual(3, self.season_1.count_goals())
        self.assertEqual(2, self.season_1.scorers()[0].num_scored)

    def test_disciplinary(self):

        yellow_card_1 = Card(color='Y', play_for=self.playfor_1,
            in_game=self.game_season_1)
        yellow_card_1.save()
        yellow_card_2 = Card(color='Y', play_for=self.playfor_1,
            in_game=self.game_season_1)
        yellow_card_2.save()
        yellow_card_3 = Card(color='Y', play_for=self.playfor_1,
            in_game=self.game_season_2)
        yellow_card_3.save()
        red_card_1 = Card(color='R', play_for=self.playfor_3,
            in_game=self.game_season_1)
        red_card_1.save()

        self.assertItemsEqual((self.playfor_1, self.playfor_3),
            self.season_1.booked_playfors())
        self.assertEqual(2,
            self.season_1.booked_playfors()[0].num_of_cards)
        self.assertEqual(2,
            self.season_1.yellow_booked_playfors()[0].num_of_cards)
        self.assertItemsEqual((self.playfor_3,),
            self.season_1.red_booked_playfors())
        self.assertEqual(1,
            self.season_1.red_booked_playfors()[0].num_of_cards)


        num_of_yellows = self.\
            playfor_1.count_yellow_cards_per(self.season_1)
        self.assertEqual(num_of_yellows, 2)

    def test_get_season(self):

        # create two seasons
        classification = Classification(label='test mens')
        classification.save()
        competition = Competition(
            name='div 1',
            mode='l',
            classification=classification
        )
        competition.save()
        season_1 = Season(label='s1',
            start_date=datetime.date.today(),
            end_date=datetime.date.today() + datetime.timedelta(365),
            competition=competition,
            published=True
        )
        season_2 = Season(label='s2',
            start_date=datetime.date.today() + datetime.timedelta(365),
            end_date=datetime.date.today() + datetime.timedelta(730),
            competition=competition
        )
        season_1.save()
        season_2.save()

        self.assertIn(season_1,
            Season.get_current_season_by_slugs('test-mens', 'div-1'))
        self.assertNotIn(season_2,
            Season.get_current_season_by_slugs('test-mens', 'div-1'))
Пример #51
0
 def addresses(self):
     addresses = []
     for address in Address.select():
         addresses.append(address.dict())
     return addresses