예제 #1
0
    def post(self):
        json_data = request.get_json(force=True)
        if not json_data:
            return {'message': 'No input data provided'}, 400
        # Validate and deserialize input
        data, errors = phone_schema.load(json_data)
        if errors:
            return errors, 422
        # Check if the keys entered are the ones expected
        try:
            phone = Phone(phone_number=data['phone_number'], name=data['name'])
        except KeyError:
            return {
                'message':
                "The key/s you entered is/are invalid. Please check and try again"
            }, 400
        repeated_phone = db.session.query(Phone).filter(
            Phone.phone_number == data['phone_number']).first()
        # Check if the phone is already on the database
        if repeated_phone:
            return {
                'message':
                'Phone already exists. Check the number and try again'
            }, 400
        db.session.add(phone)
        db.session.commit()

        result = phone_schema.dump(phone).data

        return result, 200
예제 #2
0
파일: phone.py 프로젝트: kingst/loop-viewer
def lookup_or_create(number):
    number = number.strip()
    phone = Phone.get_by_id(number)
    if phone is None:
        phone = Phone(id=number)
        phone.put()

    return phone
예제 #3
0
    def setUp(self):
        from app import app
        app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:////tmp/test.db'
        app.config["TESTING"] = True
        self.app = app.test_client()

        with app.app_context():
            db.init_app(app)
            db.drop_all()
            db.create_all()

            phone = Phone(11111111, "test")
            db.session.add(phone)
            db.session.commit()
예제 #4
0
def db_fill(session: object, data: list):
    articles = []
    phones = []
    ids_pool = []

    logger.info('{} articles found in general.'.format(len(data) * 32))

    db_meta = meta_get_or_create(session, MetaInfo)
    db_meta.last_start = datetime.datetime.now(tz=pytz.utc)
    db_meta.status = False
    session.commit()

    ins_counter = 0
    for collection in data:
        if not isinstance(collection, list):
            logger.warning('No articles found in collection.')
            continue
        for article in collection:
            link = article['link']
            article_id = md5(link.encode()).hexdigest()

            if article_id not in ids_pool:
                ids_pool.append(article_id)
            else:
                logger.debug(
                    'Article {} with id {} already present in DB.'.format(
                        link, article_id))
                continue

            if not session.query(CarArticle).get(article_id):
                ins_counter += 1

                brutto = True if 'brutto' in article['price_detail'] else False
                netto = True if 'netto' in article['price_detail'] else False
                negotiation = True if 'donegocjacji' in article[
                    'price_detail'] else False
                vat = True if 'fakturavat' in article['price_detail'] else False

                car_obj = CarArticle(
                    article_id, article['name'], article['manufacturer'],
                    article['item_year'], article['item_mileage'],
                    article['item_engine_capacity'], article['item_fuel_type'],
                    str(article['price']), brutto, netto, negotiation, vat,
                    article['currency'], article['seller_location'], link,
                    article['seller_id'])

                articles.append(car_obj)

                for phone in article['phones']:
                    phone_obj = Phone(phone, car_obj)
                    phones.append(phone_obj)

    session.bulk_save_objects(articles)
    session.bulk_save_objects(phones)

    db_meta.status = True

    session.commit()

    logger.info(
        '\nScraper finished successfully. {} new articles found and inserted.'.
        format(ins_counter))
예제 #5
0
url = open('/home/apoorv/.elephant/url').read()
engine = create_engine(url)

Session = sessionmaker(bind=engine)
session = Session()

# Base.metadata.create_all(engine)
# print("done with createall")
session.query(Person).delete(synchronize_session=False)  # cascades
print("deleted initial contents.")
p1 = Person(id=1,
            name="Apoorv",
            age=26,
            phones=[
                Phone(ptype='home', number=123),
                Phone(ptype='office', number=234)
            ])

p2 = Person(id=2,
            name="Billy",
            age=26,
            phones=[
                Phone(ptype='home', number=444),
                Phone(ptype='office', number=555)
            ])

p3 = Person(id=3,
            name="John",
            age=26,
            phones=[
예제 #6
0
        "last_name": "Doe",
        "number": "87867675655"
    },
    {
        "first_name": "Minnie",
        "last_name": "Marshall",
        "number": "97654333567"
    },
    {
        "first_name": "John",
        "last_name": "Link",
        "number": "76353344333"
    },
]

# Delete database file if it exists currently
if os.path.exists("phones.db"):
    os.remove("phones.db")

# Create the database
db.create_all()

# iterate over the PEOPLE structure and populate the database
for phone in PHONES:
    p = Phone(first_name=phone.get("first_name"),
              last_name=phone.get("last_name"),
              number=phone.get("number"))
    db.session.add(p)

db.session.commit()
예제 #7
0
    def deserialize(self, import_buffer, target_class, tenant):
        result = ImportResult()
        EMAIL_TYPES = tuple(t[0] for t in Email.TYPES)
        PHONE_TYPES = tuple(t[0] for t in Phone.TYPES)
        PHONE_SUBTYPES = tuple(t[0] for t in Phone.SUBTYPES)
        ADDRESS_TYPES = tuple(t[0] for t in Address.TYPES)
        for vcard in vobject.readComponents(import_buffer):
            if issubclass(vcard.behavior, vobject.vcard.VCard3_0):
                contact = target_class(tenant=tenant)
                try:
                    if isinstance(contact, Contact):
                        assert vcard.getChildValue('n').family
                        assert vcard.getChildValue('n').given
                        contact.name = vcard.getChildValue('n').family
                        contact.firstname = vcard.getChildValue('n').given
                        contact.additional_names = vcard.getChildValue(
                            'n').additional or None
                        # Handle organizations ?
                        if vcard.getChildValue('bday'):
                            contact.birthday = parse(vcard.bday.value)
                    if isinstance(contact, Organization):
                        assert vcard.getChildValue('org')
                        contact.corporate_name = vcard.getChildValue('org')

                    emails = vcard.contents.get(toVName('email')) or []
                    for email in emails:
                        email_type = None
                        try:
                            email_type = email.type_param
                        except:
                            pass
                        contact.emails.append(
                            Email(type=email_type
                                  if email_type in EMAIL_TYPES else None,
                                  email=email.value))

                    phones = vcard.contents.get(toVName('tel')) or []
                    for phone in phones:
                        phone_types = []
                        phone_type = None
                        phone_subtype = None
                        try:
                            phone_types = phone.type_paramlist
                            for ptype in phone_types:
                                if ptype in PHONE_TYPES and not phone_type:
                                    phone_type = ptype
                                elif ptype in PHONE_SUBTYPES and not phone_subtype:
                                    phone_subtype = ptype
                        except:
                            pass
                        contact.phones.append(
                            Phone(type=phone_type,
                                  subtype=phone_subtype,
                                  phone=phone.value))

                    addresses = vcard.contents.get(toVName('adr')) or []
                    for address in addresses:
                        address_type = None
                        try:
                            address_type = address.type_param
                        except:
                            pass
                        contact.addresses.append(
                            Address(type=address_type
                                    if address_type in ADDRESS_TYPES else None,
                                    postoffice_box=address.value.box,
                                    street_address=address.value.street,
                                    extended_address=address.value.extended,
                                    postal_code=address.value.code,
                                    city=address.value.city,
                                    state=address.value.region,
                                    country=address.value.country))
                    contact.save()
                    result.success.append(contact)
                except:
                    record_name = vcard.getChildValue('fn')
                    if not record_name:
                        name = vcard.getChildValue('n').family
                        firstname = vcard.getChildValue('n').given
                        if name and firstname:
                            record_name = u'%s %s' % (firstname, name)
                        elif name:
                            record_name = name
                        elif firstname:
                            record_name = firstname
                    if not record_name:
                        try:
                            record_name = vcard.getChildValue('org')[0]
                        except:
                            pass
                    if not record_name:
                        record_name = _('No name')
                    result.errors.append(record_name)
        return result