Пример #1
0
	def post(self):
		args = parser.parse_args()
		nc = Contact()
		nc.name  = args['contact_name']
		nc.email = args['contact_email']
		nc.notes = args['contact_notes']
		db.session.add(nc)
		db.session.commit()
		return nc , 201
def get_contact_by_id(contact_id):
    connection = get_connection()
    cursor = connection.cursor()
    cursor.execute("SELECT * FROM contact WHERE contact_id = ?", [contact_id.value])
    row = cursor.fetchone()
    contact = Contact.create(row[1], row[2], row[3], ContactId(row[0]), row[4])
    return contact
Пример #3
0
    def post(self, request):
        csvfile = request.FILES['csv']
        csvfile.open()
        reader = csv.reader(csvfile, delimiter=';')
        for row in reader:
            row[0] = str(row[0]).replace('\xa0', ' ')
            row[1] = int(row[1])
            print row
            try:
                contact = Contact.objects.get(name=row[0],zip_code=row[1])
            except ObjectDoesNotExist:
                contact = Contact(name=row[0],zip_code=row[1])
                contact.save()
            else:
                pass

        return TemplateResponse(request, self.template_name,
            {'current_page': self.template_name})
def main():
    init_db()
    rebase()
    contact = Contact.create(
        "John F Kidd",
        "0765242421",
        "*****@*****.**",
        comments="A test comment @ {}".format(time.strftime("%H:%M:%S")))

    execute = handle_error(log_error, log_info)
    execute(lambda: create_and_read(contact), get_description)
Пример #5
0
 def test_contact_to_string(self):
     name_stub = "John F Kidd"
     mobile_stub = "0776666621"
     email_address_stub = "*****@*****.**"
     target = Contact.create(name_stub, mobile_stub, email_address_stub)
     expected = "\tContact\n\t{}\n\t\tName: {}\n\t\tMobile: {}\n\t\tEmail: {}\n\t\tComments: {}\n\t\tValid: {}"\
         .format(
             target.contact_id,
             target.name,
             target.mobile,
             target.email,
             target.comments,
             target.is_valid())
     actual = target.__str__()
     self.assertEqual(expected, actual)
Пример #6
0
def create_fake_contacts(id):
    print '%d Contacts found'% len(Contact.objects.all())
    c = Contact.objects.filter(pk=id)
    if len(c)==1:
        c = c[0]
        print 'Contact #%d already exists' % id
    else:
        c = Contact()
        print 'Contact #%d created' % id
    c.name = 'Contact #%d' % id
    c.address = 'Address #%d' % id
    c.phone = 'Phone #%d' % id
    c.save()
 def get_contact_by_id_stub(contact_id):
     return Contact.create("John F Kidd", "+4478866662", "*****@*****.**", contact_id)
Пример #8
0
    db.session.add(g1)
    db.session.add(g2)
    db.session.add(g3)
    db.session.commit()
except:
    db.session.rollback()

f = open('NAMES.DIC', "rb")
names_list = [x.strip() for x in f.readlines()]
    
f.close()



for i in range(1,100000):
    c = Contact()
    c.name = get_random_name(names_list, random.randrange(2,6)) 
    c.address = 'Street ' + names_list[random.randrange(0,len(names_list))]
    c.personal_phone = random.randrange(1111111,9999999)
    c.personal_celphone = random.randrange(1111111,9999999)
    c.group_id = random.randrange(1,4)
    year = random.choice(range(1900, 2012))
    month = random.choice(range(1, 12))
    day = random.choice(range(1, 28))
    c.birthday  = datetime(year, month, day)
    db.session.add(c)
    try:
        db.session.commit()
        print "inserted", c
    except:
        db.session.rollback()
Пример #9
0
    genders.append(Gender(name="Male"))
    genders.append(Gender(name="Female"))
    db.session.add(genders[0])
    db.session.add(genders[1])
    db.session.commit()
except Exception as e:
    log.error("Creating Genders: %s", e)
    db.session.rollback()

f = open("NAMES.DIC", "rb")
names_list = [x.strip() for x in f.readlines()]

f.close()

for i in range(1, 1000):
    c = Contact()
    c.name = get_random_name(names_list, random.randrange(2, 6))
    c.address = "Street " + names_list[random.randrange(
        0, len(names_list))].decode("utf-8")
    c.personal_phone = random.randrange(1111111, 9999999)
    c.personal_celphone = random.randrange(1111111, 9999999)
    c.contact_group = groups[random.randrange(0, 3)]
    c.gender = genders[random.randrange(0, 2)]
    year = random.choice(range(1900, 2012))
    month = random.choice(range(1, 12))
    day = random.choice(range(1, 28))
    c.birthday = datetime(year, month, day)
    db.session.add(c)
    try:
        db.session.commit()
        print("inserted", c)
Пример #10
0
def add_contact(user, c):
    contact = Contact(**c)  # unpack dict `c` to model class parameters
    user.contacts.append(contact)
    db.session.commit()
    return jsonify({'id': contact.id, 'message': 'POST successful!'})
Пример #11
0
from app.models import ContactGroup, Gender, Contact
import random
from datetime import datetime


def get_random_name(names_list, size=1):
    name_lst = [names_list[random.randrange(0, len(names_list))].capitalize() for i in range(0, size)]
    return " ".join(name_lst)

ContactGroup.drop_collection()
Gender.drop_collection()
Contact.drop_collection()

g1 = ContactGroup(name='Friends').save()
g2 = ContactGroup(name='Family').save()
g3 = ContactGroup(name='Work').save()
groups = [g1,g2,g3]

gender1 = Gender(name='Male').save()
gender2 = Gender(name='Female').save()
genders = [gender1, gender2]

f = open('NAMES.DIC', "rb")
names_list = [x.strip() for x in f.readlines()]

f.close()

for i in range(1, 1000):
    c = Contact()
    c.name = get_random_name(names_list, random.randrange(2, 6))
    c.address = 'Street ' + names_list[random.randrange(0, len(names_list))]
Пример #12
0
 def test_contact_with_no_mobile_raises_expected_error(self):
     with self.assertRaises(ValueError):
         Contact.create("John F Kidd", None, "*****@*****.**", None)
Пример #13
0
def test_get_aliases_v2(flask_client):
    user = User.create(email="[email protected]",
                       password="******",
                       name="Test User",
                       activated=True)
    db.session.commit()

    # create api_key
    api_key = ApiKey.create(user.id, "for test")
    db.session.commit()

    a0 = Alias.create_new(user, "prefix0")
    a1 = Alias.create_new(user, "prefix1")
    db.session.commit()

    # add activity for a0
    c0 = Contact.create(
        user_id=user.id,
        alias_id=a0.id,
        website_email="*****@*****.**",
        reply_email="re0@SL",
    )
    db.session.commit()
    EmailLog.create(contact_id=c0.id, user_id=user.id)
    db.session.commit()

    # a1 has more recent activity
    c1 = Contact.create(
        user_id=user.id,
        alias_id=a1.id,
        website_email="*****@*****.**",
        reply_email="re1@SL",
    )
    db.session.commit()
    EmailLog.create(contact_id=c1.id, user_id=user.id)
    db.session.commit()

    # get aliases v2
    r = flask_client.get(
        url_for("api.get_aliases_v2", page_id=0),
        headers={"Authentication": api_key.code},
    )
    assert r.status_code == 200

    # make sure a1 is returned before a0
    r0 = r.json["aliases"][0]
    # r0 will have the following format
    # {
    #     "creation_date": "2020-04-25 21:10:01+00:00",
    #     "creation_timestamp": 1587849001,
    #     "email": "*****@*****.**",
    #     "enabled": true,
    #     "id": 3,
    #     "name": "Hey hey",
    #     "latest_activity": {
    #         "action": "forward",
    #         "contact": {
    #             "email": "*****@*****.**",
    #             "name": null,
    #             "reverse_alias": "\"c1 at example.com\" <re1@SL>"
    #         },
    #         "timestamp": 1587849001
    #     },
    #     "mailbox": {
    #         "email": "[email protected]",
    #         "id": 1
    #     },
    #     "nb_block": 0,
    #     "nb_forward": 1,
    #     "nb_reply": 0,
    #     "note": null
    # }
    assert "name" in r0
    assert r0["email"].startswith("prefix1")
    assert r0["latest_activity"]["action"] == "forward"
    assert "timestamp" in r0["latest_activity"]

    assert r0["latest_activity"]["contact"]["email"] == "*****@*****.**"
    assert "name" in r0["latest_activity"]["contact"]
    assert "reverse_alias" in r0["latest_activity"]["contact"]

    assert "id" in r0["mailbox"]
    assert "email" in r0["mailbox"]

    assert r0["mailboxes"]
    for mailbox in r0["mailboxes"]:
        assert "id" in mailbox
        assert "email" in mailbox

    assert "support_pgp" in r0
    assert not r0["support_pgp"]

    assert "disable_pgp" in r0
    assert not r0["disable_pgp"]
Пример #14
0
    genders.append(Gender(name='Male'))
    genders.append(Gender(name='Female'))
    db.session.add(genders[0])
    db.session.add(genders[1])
    db.session.commit()
except Exception, e:
    log.error("Creating Genders: %s", e)
    db.session.rollback()

f = open('NAMES.DIC', "rb")
names_list = [x.strip() for x in f.readlines()]

f.close()

for i in range(1, 1000):
    c = Contact()
    c.name = get_random_name(names_list, random.randrange(2, 6))
    c.address = 'Street ' + names_list[random.randrange(0, len(names_list))]
    c.personal_phone = random.randrange(1111111, 9999999)
    c.personal_celphone = random.randrange(1111111, 9999999)
    group = random.randrange(0, 2)
    if group == 0:
        sub_group = random.randrange(0, 2)
    else:
        sub_group = random.randrange(1, 4)
    c.contact_group = groups[group]
    c.contact_sub_group = sub_groups[sub_group]

    c.gender = genders[random.randrange(0, 2)]
    year = random.choice(range(1900, 2012))
    month = random.choice(range(1, 12))
Пример #15
0
    genders.append(Gender(name="Male"))
    genders.append(Gender(name="Female"))
    db.session.add(genders[0])
    db.session.add(genders[1])
    db.session.commit()
except Exception as e:
    log.error("Creating Genders: %s", e)
    db.session.rollback()

f = open("NAMES.DIC", "rb")
names_list = [x.strip() for x in f.readlines()]

f.close()

for i in range(1, 1000):
    c = Contact()
    c.name = get_random_name(names_list, random.randrange(2, 6))
    c.address = "Street " + names_list[random.randrange(0, len(names_list))].decode(
        "utf-8"
    )
    c.personal_phone = random.randrange(1111111, 9999999)
    c.personal_celphone = random.randrange(1111111, 9999999)
    c.contact_group = groups[random.randrange(0, 3)]
    c.gender = genders[random.randrange(0, 2)]
    year = random.choice(range(1900, 2012))
    month = random.choice(range(1, 12))
    day = random.choice(range(1, 28))
    c.birthday = datetime(year, month, day)
    db.session.add(c)
    try:
        db.session.commit()
Пример #16
0
 def test_contact_with_invalid_email_address_returns_expected_value(self):
     contact_stub = Contact.create("John F Kidd", "0776666621", "j.test.com")
     actual = contact_stub.is_valid()
     self.assertFalse(actual)
Пример #17
0
 def test_contact_with_no_email_raises_expected_error(self):
     with self.assertRaises(ValueError):
         Contact.create("John F Kidd", "075535533", None, None)
Пример #18
0
def register(request):
    try:
        body = json.loads(request.body.decode('utf-8'))
    except ValueError as e:
        return HttpResponse(status=401,
                            content='{"Error": "Invalid JSON string: ' + e.__str__() + '"}',
                            content_type='application/json')

    try:
        # Check captcha
        token = body['captchaToken']
        if not validate_captcha(token):
            raise ValidationError('Invalid Captcha')
        # Build Contact
        contact = Contact()
        contact.contactCategory = ContactCategory.objects.get(contactCategoryId=body['contact']['contactCategory'])

        if contact.contactCategory.isIndividual:
            contact.firstName = body['contact']['firstName']
            contact.lastName = body['contact']['lastName']
            contact.activityFree = body['contact']['activityFree']
            if (not body['contact']['activityFromList'] is None) and (int(body['contact']['activityFromList']) > 0):
                contact.activityFromList = ContactActivity.objects.get(
                    contactActivityId=body['contact']['activityFromList'])
            contact.contactAfiliationFree = body['contact']['afiliationFree']
            if (not body['contact']['afiliationFromList'] is None) and (int(body['contact']['afiliationFromList'])) > 0:
                contact.contactAfiliationFromList = ContactAfiliation.objects.get(
                    contactAfiliationId=body['contact']['afiliationFromList'])
        else:
            contact.organizationName = body['contact']['organizationName']

        contact.borderLocationFree = body['contact']['borderLocationFree']
        if (not body['contact']['borderLocationFromList'] is None) and \
                (int(body['contact']['borderLocationFromList']) > 0):
            contact.borderLocationFromList = Border.objects.get(borderId=body['contact']['borderLocationFromList'])
        contact.contactCountry = Country.objects.get(countryId=body['contact']['contactCountry'])
        contact.phoneLocalNumber = body['contact']['phoneLocalNumber']
        contact.email = body['contact']['email']
        contact.contactStatus = ContactStatus.objects.get(contactStatusId=Contact.NEW)

        try:
            contact.full_clean()
            contact.save()
        except ValidationError as e:
            return HttpResponse(status=400,
                                content='{"Error": "Invalid contact data: ' + e.__str__() + '"}',
                                        content_type='application/json')
    except Exception as e:
        return HttpResponse(status=400,
                            content='{"Error": "Contact not created (' + e.__str__() + ')"}',
                            content_type='application/json')

    return HttpResponse(status=200,
                        content=json.dumps(simplify_data([contact], [])),
                        content_type='application/json')
Пример #19
0
 def test_contact_with_empty_name_raises_expected_error(self):
     with self.assertRaises(ValueError):
         Contact.create("", "076363633", "*****@*****.**", None)
Пример #20
0
    db.session.add(Gender(name='Male'))
    db.session.add(Gender(name='Female'))
    db.session.commit()
except Exception, e:
    log.error('Gender creation error: %s', e)
    db.session.rollback()
    exit(1)

f = open('NAMES.DIC', "rb")
names_list = [x.strip() for x in f.readlines()]

f.close()

j = 1
for i in range(1, 100):
    c = Contact()
    c.name = get_random_name(names_list, random.randrange(2, 6))
    c.address = 'Street ' + names_list[random.randrange(0, len(names_list))]
    c.personal_phone = random.randrange(1111111, 9999999)
    c.personal_celphone = random.randrange(1111111, 9999999)
    c.contact_group_id = random.randrange(1, 4)
    c.gender_id = random.randrange(1, 3)
    year = random.choice(range(1900, 2012))
    month = random.choice(range(1, 12))
    day = random.choice(range(1, 28))
    c.birthday = datetime(year, month, day)
    c.changed_on = datetime.now()
    c.created_on = datetime.now()
    if j == 1:
        j+=1
        _user = user1
from app.models import Contact


contact = Contact(first_name='Павел',
                  last_name='Сидоров',
                  email_address='*****@*****.**',
                  description='Повар')
contact.save()

contact = Contact(first_name='Наталья',
                  last_name='Сидорова',
                  email_address='*****@*****.**',
                  description='Жена поаора')
contact.save()

contact = Contact(first_name='Иван',
                  last_name='Петров',
                  email_address='*****@*****.**',
                  description='Лучший друг повара')
contact.save()