Example #1
0
    def db_init(drop):
        """
        Initialize the database of the Flask application.
        Create the tables, and fill some basic data.
        :return: None.
        """
        if drop:
            click.confirm('This operation will delete the database, do you want to continue?', abort=True)
            click.echo('Dropping tables...')
            db.drop_all()
            click.echo('Dropped.')

        click.echo('Creating database...')
        db.create_all()
        click.echo('Created.')

        click.echo('Filling basic data...')
        # Data for class Gender().
        db.session.add_all([
            Gender(name='Unknown', name_zh='未知'),
            Gender(name='Male', name_zh='男性'),
            Gender(name='Female', name_zh='女性'),
        ])

        # Data for class Company().
        db.session.add_all([
            Project(name='南京2016G61地块项目', code='海珀'),
            Project(name='南京2017G41地块项目', code='海悦'),
        ])

        click.echo('Filled.')

        click.echo('Committing...')
        db.session.commit()
        click.echo('Commit succeed.')
Example #2
0
def create_politician(data):
    politician = Politician(**data)
    politician.save()

    gender = Gender().fetch(data.get('gender'))
    region = Region().fetch(data.get('region'))
    political_office = PoliticalOffice().fetch(data.get('political_office'))
    political_party = PoliticalParty().fetch(data.get('political_party'))

    if gender:
        gender.politicians.add(politician)
        gender.save()

    if region:
        region.politicians.add(politician)
        region.save()

    if political_office:
        political_office.politicians.add(politician)
        political_office.save()

    if political_party:
        political_party.politicians.add(politician)
        political_party.save()

    return politician
Example #3
0
    def mutate(self, info, **kwargs):
        Politician.delete_all()
        Gender.delete_all()
        Region.delete_all()
        PoliticalOffice.delete_all()
        PoliticalParty.delete_all()

        return DeleteDB(success=True)
def create_genders(genders):
    for item in genders:
        new_gender = Gender()
        new_gender.gender = item['gender']
        new_gender.gender_ru = item['gender_ru']
        db.session.add(new_gender)
    db.session.commit()
    print_db_table(Gender)
Example #5
0
def deploy():
    """Run deployment tasks."""
    # migrate database to latest version
    upgrade()
    Role.insert_roles()
    Activity.insert_activities()
    Status.insert_statuses()
    Gender.insert_genders()
    Title.insert_titles()
Example #6
0
    def init_db(app, db):
        # print('init_db')
        from app.models import Province, Gender, NotificationType

        provincesList = ['An Giang','Bà Rịa - Vũng Tàu','Bạc Liêu','Bắc Kạn','Bắc Giang','Bắc Ninh','Bến Tre','Bình Dương','Bình Định','Bình Phước','Bình Thuận','Cà Mau','Cao Bằng','Cần Thơ','Đà Nẵng','Đắk Lắk','Đắk Nông','Đồng Nai','Đồng Tháp','Điện Biên','Gia Lai','Hà Giang','Hà Nam','Hà Nội','Hà Tĩnh','Hải Dương','Hải Phòng','Hòa Bình','Hậu Giang','Hưng Yên','Thành phố Hồ Chí Minh','Khánh Hòa','Kiên Giang','Kon Tum','Lai Châu','Lào Cai','Lạng Sơn','Lâm Đồng','Long An','Nam Định','Nghệ An','Ninh Bình','Ninh Thuận','Phú Thọ','Phú Yên','Quảng Bình','Quảng Nam','Quảng Ngãi','Quảng Ninh','Quảng Trị','Sóc Trăng','Sơn La','Tây Ninh','Thái Bình','Thái Nguyên','Thanh Hóa','Thừa Thiên - Huế','Tiền Giang','Trà Vinh','Tuyên Quang','Vĩnh Long','Vĩnh Phúc','Yên Bái']
        coordinatesList = [(10.5149025, 105.1131792), (10.5819798, 107.2899841), (9.2824882, 105.7260685), (22.1321485, 105.8448032), (21.2779313, 106.1938814), (21.1212051, 106.0880245), (10.1245254, 106.4690447), (11.1969829, 106.7080527), (14.1525201, 108.9239618), (11.6790213, 106.797558), (11.101462, 107.9415938), (9.1749605, 105.1960897), (22.6574478, 106.2463873), (10.1131587, 105.6294528), (16.0679814, 108.2119396), (12.8399392, 108.2284947), (12.1288687, 107.5874261), (11.0063212, 107.1921807), (10.5954417, 105.5778479), (21.7210126, 103.0410819), (13.7964067, 108.2608263), (22.8274313, 104.9866145), (20.5269088, 105.9543527), (21.0294498, 105.8544441), (18.3543859, 105.897683), (20.9443681, 106.3780373), (20.858864, 106.6749591), (20.8130014, 105.3452974), (9.7633197, 105.6379524), (20.6490983, 106.0509951), (10.7758439, 106.7017555), (9.3940245, 106.0078954), (9.9776598, 105.2566062), (14.3406675, 107.9807771), (22.3915785, 103.4787316), (22.4997452, 103.9656924), (21.8932309, 106.5884313), (11.6937725, 108.152754), (10.726794, 106.1909011), (20.4230328, 106.1683794), (19.3738868, 104.9233469), (20.2449753, 105.9826291), (11.7449715, 108.8983408), (11.5486226, 109.0281472), (13.2126552, 109.0834225), (17.5462658, 106.2576229), (15.5973344, 107.9758089), (15.1190037, 108.8095598), (21.1718046, 107.2012742), (16.8581352, 106.8588935), (9.5664427, 105.876444), (21.3282643, 103.9005252), (11.365631, 106.1283496), (20.4528848, 106.340023), (21.5545825, 105.7987344), (20.1071694, 105.2124457), (16.3375374, 107.5563708), (10.4176819, 106.1997767), (9.8371629, 106.2394463), (21.8262252, 105.2132832), (10.0937316, 106.0313566), (18.416893, 105.695355), (21.7097865, 104.8872126)]
        
        gendersList = ['Nam', 'Nữ']
        
        notificationsList = ['admin', 'auth', 'match', 'like', 'comment']
        
        with app.app_context():
            if Province.query.filter_by(name=provincesList[0]).count() == 0:
                i = 0
                for province in provincesList:
                    p = Province(name=province)
                    p.coordinates = coordinatesList[i]
                    i += 1
                    db.session.add(p)
            if Gender.query.filter_by(name=gendersList[0]).count() == 0:
                for genger in gendersList:
                    g = Gender(name=genger)
                    db.session.add(g)
            if NotificationType.query.filter_by(name=notificationsList[0]).count() == 0:
                for noti in notificationsList:
                    n = NotificationType(name=noti)
                    db.session.add(n)
                db.session.commit()
Example #7
0
def gender_preference_edit():
    user = User.query.get(current_user.id).id
    form = GenderPreferenceForm()
    form['csrf_token'].data = request.cookies['csrf_token']

    if form.validate_on_submit():
        gender_preferences = Gender(gender_name=form.data['gender_preference'])

        db.session.add(gender_preferences)
        db.session.commit()
        user_id_for_join = user.id
        gender_id_for_join = gender_preferences.id
        gender_join = GenderPreference(user_id=user_id_for_join,
                                       gender_id=gender_id_for_join)
        db.session.add(gender_join)
        db.session.commit()
        return user.to_dict()
    return {'errors': validation_errors_to_error_messages(form.errors)}
Example #8
0
def sign_up():  
    """
    Creates a new user and logs them in
    """
    form = SignUpForm()
    file = request.files.get("profile_photo_file")
    form['csrf_token'].data = request.cookies['csrf_token']

    if form.validate_on_submit():
        s3_photo_url = 'https://wing.s3.us-east-2.amazonaws.com/Week4_HarleyDavyDoodle.jpg'
        file = form.data['profile_photo_file']
        if file:
            file.filename = secure_filename(file.filename)
            s3_photo_url = upload_file_to_s3(file, Config.S3_BUCKET)
        user = User(
            username=form.data['username'],
            email=form.data['email'],
            first_name=form.data['first_name'],
            last_name=form.data['last_name'],
            age=form.data['age'],
            zip_code=form.data['zip_code'],
            bio=form.data['bio'],
            gender_id=form.data['gender_id'],
            password=form.data['password'],
            profile_photo_url=s3_photo_url,
            )
        gender_preferences = Gender(
                gender_name=form.data['gender_preference']
            ) 
        db.session.add(user)
        db.session.add(gender_preferences)
        db.session.commit()
        user_id_for_join = user.id
        gender_id_for_join = gender_preferences.id
        gender_join = GenderPreference(
            user_id=user_id_for_join,
            gender_id=gender_id_for_join
        )
        db.session.add(gender_join)
        db.session.commit()
        login_user(user)
        return user.to_dict()
    return {'errors': validation_errors_to_error_messages(form.errors)}
Example #9
0
                               role_admin, 'password')
user3 = appbuilder.sm.add_user('user3', 'user3', 'test', '*****@*****.**',
                               role_admin, 'password')

try:
    db.session.add(ContactGroup(name='Friends'))
    db.session.add(ContactGroup(name='Family'))
    db.session.add(ContactGroup(name='Work'))
    db.session.commit()
except Exception, e:
    log.error('Group creation error: %s', e)
    db.session.rollback()
    exit(1)

try:
    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()
Example #10
0
        ContactSubGroup(name="Long time no see", contact_group=groups[0]))
    sub_groups.append(ContactSubGroup(name="BBIC", contact_group=groups[1]))
    sub_groups.append(ContactSubGroup(name="Miniclip",
                                      contact_group=groups[1]))
    db.session.add(sub_groups[0])
    db.session.add(sub_groups[1])
    db.session.add(sub_groups[2])
    db.session.add(sub_groups[3])
    db.session.commit()
except Exception as e:
    log.error("Creating Groups: %s", e)
    db.session.rollback()

try:
    genders = list()
    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()
Example #11
0
def deploy():
    '''
    Run deployment tasks.
    '''

    # migrate database to latest revision
    from flask_migrate import upgrade
    upgrade()

    # insert data
    from app.models import Color
    Color.insert_entries()

    from app.models import Permission
    Permission.insert_entries()

    from app.models import Role
    Role.insert_entries()

    from app.models import IDType
    IDType.insert_entries()

    from app.models import Gender
    Gender.insert_entries()

    from app.models import Relationship
    Relationship.insert_entries()

    from app.models import PurposeType
    PurposeType.insert_entries()

    from app.models import ReferrerType
    ReferrerType.insert_entries()

    from app.models import BookingState
    BookingState.insert_entries()

    from app.models import AssignmentScoreGrade
    AssignmentScoreGrade.insert_entries()

    from app.models import GREAWScore
    GREAWScore.insert_entries()

    from app.models import ScoreLabel
    ScoreLabel.insert_entries()

    from app.models import InvitationType
    InvitationType.insert_entries()

    from app.models import EducationType
    EducationType.insert_entries()

    from app.models import ScoreType
    ScoreType.insert_entries()

    from app.models import CourseType
    CourseType.insert_entries()

    from app.models import iPadCapacity
    iPadCapacity.insert_entries()

    from app.models import iPadState
    iPadState.insert_entries()

    from app.models import Room
    Room.insert_entries()

    from app.models import Lesson
    Lesson.insert_entries()

    from app.models import Section
    Section.insert_entries()

    from app.models import Assignment
    Assignment.insert_entries()

    from app.models import Test
    Test.insert_entries()

    from app.models import AnnouncementType
    AnnouncementType.insert_entries()

    from config import basedir
    data = raw_input(u'Enter data identifier (e.g.: initial or 20160422): ')
    datadir = os.path.join(basedir, 'data', data)
    if os.path.exists(datadir):
        from app.models import User
        User.insert_entries(data=data, basedir=basedir)

        from app.models import UserCreation
        UserCreation.insert_entries(data=data, basedir=basedir)

        from app.models import Punch
        Punch.insert_entries(data=data, basedir=basedir)

        from app.models import Tag
        Tag.insert_entries(data='initial', basedir=basedir)

        from app.models import Product
        Product.insert_entries(data='initial', basedir=basedir)

        from app.models import Course
        Course.insert_entries(data='initial', basedir=basedir)

        from app.models import Period
        Period.insert_entries(data='initial', basedir=basedir)

        from app.models import iPad
        iPad.insert_entries(data='initial', basedir=basedir)

        from app.models import iPadContent
        iPadContent.insert_entries(data='initial', basedir=basedir)

        from app.models import NotaBene
        NotaBene.insert_entries(data='initial', basedir=basedir)

        from app.models import Feed
        Feed.insert_entries(data=data, basedir=basedir)
    else:
        print u'---> Invalid data identifier: %s' % data
Example #12
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))].decode("utf-8").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()
Example #13
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()
Example #14
0
def manual_signup():
    """ Admin signup page, allows signup outside of registration period """
    form = SignupForm(request.form)
    try:
        event = Events.query.filter(Events.active).first()
        if event != None:
            eventid = event.id
            timeslots = TimeSlots.query.filter(
                TimeSlots.event_id == eventid).all()
            if timeslots != None:
                [available_slots_choices, available_special_slots_choices
                 ] = get_slots_choices(timeslots)

                form.availableslots.choices = available_slots_choices
                form.availablespecialslots.choices = available_special_slots_choices

    except Exception as e:
        print(e)
        return render_template('error.html')

    if request.method == 'POST' and form.validate():
        try:
            timestamp = datetime.now()
            name = str(request.form['name'])
            prename = str(request.form['prename'])
            gender = Gender(int(request.form['gender']))
            email = str(request.form['email'])
            email2 = str(request.form['email2'])
            if email != email2:
                message = 'Deine Mailadressen stimmen nicht überein!\
                Bitte geh zurück und korrigiere deine Mailadresse.'

                return render_template('error.html', message=message)
            mobile = str(request.form['mobile_nr'])
            address = str(request.form['address'])
            birthday = str(request.form['birthday'])
            studycourse = str(request.form['study_course'])
            studysemester = str(request.form['study_semester'])
            perfectdate = str(request.form['perfect_date'])
            fruit = str(request.form['fruit'])
            availablespecialslots = None
            if event.special_slots:
                availablespecialslots = request.form.getlist(
                    'availablespecialslots')
            availableslots = request.form.getlist('availableslots')
            confirmed = False
            present = False
            paid = False
            slots = 0
            if availableslots:
                slots = int(availableslots[0])
            elif availablespecialslots:
                slots = int(availablespecialslots[0])
            else:
                message = 'Du hast kein passendes Datum ausgewählt!\
                Bitte geh zurück und wähle ein dir passendes Datum aus.'

                return render_template('error.html', message=message)
            bday = datetime.strptime(birthday, '%d.%m.%Y')
            chosen_timeslot = TimeSlots.query.filter(
                TimeSlots.id == int(slots)).first()
            slot_datetime = str(
                chosen_timeslot.date.strftime("%A %d. %B %Y")) + '  ' + str(
                    chosen_timeslot.start_time.strftime("%H:%M"))
            try:
                new_participant = Participants(creation_timestamp=timestamp,
                                               event_id=eventid,
                                               name=name,
                                               prename=prename,
                                               email=email,
                                               mobile_nr=mobile,
                                               address=address,
                                               birthday=bday,
                                               gender=gender,
                                               study_course=studycourse,
                                               study_semester=studysemester,
                                               perfect_date=perfectdate,
                                               fruit=fruit,
                                               slot=slots,
                                               confirmed=confirmed,
                                               present=present,
                                               paid=paid)
                db.session.add(new_participant)
                db.session.commit()
                # The participant signed up successfully
                # Emit signal and show success page
                SIGNAL_NEW_SIGNUP.send('signup view',
                                       participant=new_participant,
                                       slot_datetime=slot_datetime)
            except Participants.AlreadySignedUpException:
                message = 'Die E-Mail Adresse ' + email + \
                    ' wurde bereits für das Speeddating angewendet.\
                    Bitte versuchen Sie es erneut mit einer neuen E-Mail Adresse.'

                return render_template('error.html', message=message)

        except Exception as e:
            print('Exception of type {} occurred: {}'.format(type(e), str(e)))
            return render_template('error.html')

        return render_template('success.html',
                               name=('{} {}'.format(prename, name)),
                               mail=email,
                               datetime=slot_datetime)

    return render_template('manual_signup.html', form=form, event=event)
Example #15
0
        ContactSubGroup(name='Long time no see', contact_group=groups[0]))
    sub_groups.append(ContactSubGroup(name='BBIC', contact_group=groups[1]))
    sub_groups.append(ContactSubGroup(name='Miniclip',
                                      contact_group=groups[1]))
    db.session.add(sub_groups[0])
    db.session.add(sub_groups[1])
    db.session.add(sub_groups[2])
    db.session.add(sub_groups[3])
    db.session.commit()
except Exception, e:
    log.error("Creating Groups: %s", e)
    db.session.rollback()

try:
    genders = list()
    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()
Example #16
0
def edit_participant(timeslot_id, participant_id):
    """ Admin edit signed up participants, allows to do changes
        on an already signed up particpant """
    event = Events.query.filter(Events.active).first()
    slot = TimeSlots.query.get_or_404(timeslot_id)
    participant = Participants.query.get_or_404(participant_id)
    form = SignupForm(request.form, obj=participant)
    if event != None:
        eventid = event.id
        timeslots = TimeSlots.query.filter(TimeSlots.event_id == eventid).all()
        if timeslots != None:
            [available_slots_choices,
             available_special_slots_choices] = get_slots_choices(timeslots)
            form.availableslots.choices = available_slots_choices
            form.availablespecialslots.choices = available_special_slots_choices
    form.birthday.data = participant.birthday.strftime("%d.%m.%Y")
    form.email2.data = participant.email
    if len(available_slots_choices) > 0:
        for i in range(0, len(available_slots_choices)):
            if participant.slot in available_slots_choices[i]:
                form.availableslots.data = [participant.slot]
    if len(available_special_slots_choices) > 0:
        for i in range(0, len(available_special_slots_choices)):
            if participant.slot in available_special_slots_choices[i]:
                form.availablespecialslots.data = [participant.slot]

    if request.method == 'POST' and form.validate():
        try:
            form.populate_obj(participant)
            email = str(request.form['email'])
            email2 = str(request.form['email2'])
            if email != email2:
                message = 'Deine Mailadressen stimmen nicht überein!\
                Bitte geh zurück und korrigiere die Mailadresse.'

                return render_template('error.html', message=message)
            gender = Gender(int(request.form['gender']))
            birthday = str(request.form['birthday'])
            participant.birthday = datetime.strptime(birthday, '%d.%m.%Y')
            participant.gender = gender
            availablespecialslots = None
            if event.special_slots:
                availablespecialslots = request.form.getlist(
                    'availablespecialslots')
            availableslots = request.form.getlist('availableslots')
            slots = 0
            if availableslots:
                slots = int(availableslots[0])
            elif availablespecialslots:
                slots = int(availablespecialslots[0])
            else:
                message = 'Du hast kein passendes Datum ausgewählt!\
                Bitte geh zurück und wähle ein dir passendes Datum aus.'

                return render_template('error.html', message=message)
            participant.slot = int(slots)
            db.session.commit()
        except Exception as e:
            print('Exception of type {} occurred: {}'.format(type(e), str(e)))
            return render_template('error.html')
        return redirect(request.referrer)
    return render_template('edit_participant.html',
                           form=form,
                           event=event,
                           slot=slot,
                           participant=participant)
Example #17
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))]
Example #18
0
def seed_genders():
    for i in range(len(genders)):
        entry = Gender(gender_name=genders[i])
        db.session.add(entry)
    db.session.commit()
Example #19
0
            0, len(names_list))].decode("utf-8").capitalize()
        for i in range(0, size)
    ]
    return " ".join(name_lst)


try:
    db.session.add(ContactGroup(name="Friends"))
    db.session.add(ContactGroup(name="Family"))
    db.session.add(ContactGroup(name="Work"))
    db.session.commit()
except:
    db.session.rollback()

try:
    db.session.add(Gender(name="Male"))
    db.session.add(Gender(name="Female"))
    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, 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))].decode("utf-8")
Example #20
0
    def mutate(self, info, **kwargs):
        gender = Gender(**kwargs)
        gender.save()

        return CreateGender(gender=gender, success=True)