Example #1
0
def createUser(login_session):
    '''
    Take user from login session and save to db
    returns user.id
    Uniqueness is defined as having unique oauth id number. For hypotheoretical
    case (highly unlikely) when id numbers from different oauth providers can possibly match
    there are prefixes stored ensuring uniqueness of oauth ID
    fb - facebook
    gl - google
    gh - github
    '''

    if login_session['provider'] == 'facebook':
        oauthid = 'fb'
    if login_session['provider'] == 'google':
        oauthid = 'gl'
    if login_session['provider'] == 'github':
        oauthid = 'gh'
    oauthid = oauthid+ str(login_session['oauthid'])
    newUser = User(name=login_session['username'], email=login_session['email'],
                   picture=login_session['picture'],
                   oauthid=oauthid)
    sql_session.add(newUser)
    sql_session.commit()
    user = sql_session.query(User).filter_by(oauthid=oauthid).one()
    return user.id
Example #2
0
def model_edit(model_id):
    if not model_id:
        return 'Error. No record to edit. Please go back'
    if 'username' not in login_session:
        flash('Please login to be able to edit content')
        return redirect(url_for('mainpage'))
    model_edit_record = sql_session.query(Model).filter(Model.id == model_id).one()
    if model_edit_record.user_id != login_session['user_id']:
        flash("You are not the original creator! You don't have permission to edit the record")
        return redirect(url_for('mainpage'))
    if request.method == 'POST':
        try:
            record_name = request.form['model_name']
            record_pic_url = request.form['model_pic_url']
        except:
            return 'Error accessing form.Please <a href="/" > click here </a> to go to main menu'
        if not record_name:
            error = 'Model name is required. Please try again'
            return render_template('edit_model.html', error=error, record=model_edit_record,
                                   record_pic_url=record_pic_url)
        model_edit_record.name = record_name
        model_edit_record.pic_url = record_pic_url
        try:
            mfr = model_edit_record.mfr.id
            sql_session.commit()
            flash('successfully updated model ID: %s, Name: %s' % (model_edit_record.id,
                                                                   model_edit_record.name))
            return redirect(url_for('mainpage', mfr=mfr))
        except:
            return 'Error updating database. Please try again later'
    else:
        return render_template('edit_model.html', record=model_edit_record)
Example #3
0
def createmfr():
    if 'username' not in login_session:
        flash('Please login to be able to create content')
        return redirect(url_for('mainpage'))
    if request.method == 'POST':
        values = request.form
        try:
            name = values['mfr_full_name']
            country = values['mfr_country']
            commonname = values['mfr_commonname']
            vehicle_type = values['mfr_vehicle_type']
        except:
            return ('Error accesing form values. Please <a href="/" > click here </a>'
                    ' to go to main menu')
        if not name or not country or not vehicle_type:
            error = 'All fields except short name must be filled in'
            return render_template('create_mfr.html', record_name=name,
                                   record_country=country, record_commonname=commonname,
                                   record_vehicle_type=vehicle_type, error=error)
        if not commonname:
            commonname = name
        try:
            mfr = Mfr(name=name, country=country, commonname=commonname, vehicle_type=vehicle_type,
                      user_id=login_session['user_id'])
            sql_session.add(mfr)
            sql_session.commit()
            flash('successfully added record. Id: %s, Shortname: %s' % (mfr.id, mfr.commonname))
            return redirect(url_for('mainpage'))
        except:
            return 'Error updating database. Please try again later'
    else:
        return render_template('create_mfr.html')
Example #4
0
def createmodel(mfr_id):
    if 'username' not in login_session:
        flash('Please login to be able to create content')
        return redirect(url_for('mainpage', mfr=mfr_id))
    try:
        parent_mfr = sql_session.query(Mfr).filter(Mfr.id == mfr_id).one()
    except:
        return 'Wrong mfr_id. Please Go back to the main page'
    if request.method == 'POST':
        model_name = request.form['model_name']
        model_pic_url = request.form['model_pic_url']
        if not model_name:
            error = 'Model name is empty. This is required field'
            return render_template('create_model.html', error=error, record_name=model_name,
                                   record_pic_url=model_pic_url)
        try:
            child_model = Model(name=model_name, pic_url=model_pic_url,
                                user_id=login_session['user_id'])
            parent_mfr.model.append(child_model)
            sql_session.add(child_model)
            sql_session.commit()
            flash('Model with ID %s and name %s added succesfully for manufacturer %s'
                  % (child_model.id, child_model.name, parent_mfr.commonname))
            return redirect(url_for('mainpage'))
        except:
            return 'Error creating model. Go back to the main page'
    return render_template('create_model.html', mfr_name=parent_mfr.commonname)
Example #5
0
    def fill_mfr_db(page, deleteTable, login_session):
        if login_session.get('username') == None:
            return (0, 0, 'You must be signed in to add models <BR>' +
                    '<a href="/login">Click here</a> to login')
        if deleteTable == "yes":
            # The following drop table does not work with cascade delete from model table, at least as of now. Thus
            # simply delete all records in MFR for cascade delete the model table
            # Mfr.__table__.drop(engine)
            # Base.metadata.create_all(engine)
            print 'we are here. Deleting the tables'
            records = sql_session.query(Mfr).all()
            for record in records:
                creator_id = record.user_id
                # Check if the record belongs to authorized user
                if creator_id == login_session['username']:
                    sql_session.delete(record)
                else:
                    # If not then skip record. Later some nice stuff might be added to get back the list of
                    # models not deleted and returned in a separate modal window
                    pass
            sql_session.commit()
        data = Mfr.getMFCdata(int(page))
        # this list keeps the number of id's processed
        ids = []
        # count for records appended and total records retrieved
        new_records = 0
        total_records = len(data)
        for mfr_row in data:
            # Check if Mfr_ID exists in DB = if yes => skip the record
            if sql_session.query(Mfr).filter(
                    Mfr.id == mfr_row['Mfr_ID']).count() == 0:
                # Check for unique ID -some id's from API are doubled and not unique!So we put processed IDS into list ids
                if mfr_row['Mfr_ID'] not in ids:
                    type_vehicle = False
                    ids.append(mfr_row['Mfr_ID'])
                    # Here is the algo for setting VehicleType field. The logic is that we loop through all VehicleTypes
                    # and look for IsPrimary = True field.
                    if len(mfr_row['VehicleTypes']) != 0:
                        for vehicle_type in mfr_row['VehicleTypes']:
                            if vehicle_type['IsPrimary'] == True:
                                type_vehicle = vehicle_type['Name']
# Sometimes even if vehicle type is set, no primary key is defined - NHTSA data consistency bug
# So we check that after iterating we have vehilce
# type set. If not = > manually set to 'no primary key'.
# The same value is assigned when no VehicleType info is present
                    if not type_vehicle:
                        type_vehicle = 'No primary type'
# Get current user, and update records with that user
                    mfr_line = Mfr(id=mfr_row['Mfr_ID'],
                                   country=mfr_row['Country'],
                                   commonname=mfr_row['Mfr_CommonName'],
                                   name=mfr_row['Mfr_Name'],
                                   vehicle_type=type_vehicle,
                                   user_id=login_session['user_id'])
                    sql_session.add(mfr_line)
                    new_records += 1
            sql_session.commit()
        error_txt = None
        return new_records, total_records, error_txt
Example #6
0
 def fill_models_db(login_session, year=2016, ids=None):
     # Check if IDS is a list, otherwise exit
     if not isinstance(ids, list):
         print 'Ids is not list'
         return None
     Model.metadata.bind = engine
     # Delete the model_db table and create a new one
     # Delete the following two lines if no table recreation needed.
     Model.__table__.drop(checkfirst=True)
     Model.__table__.create(checkfirst=True)
     # If list of ID's is empty:  either populate models for all makes or do nothing.
     # The first choice is commented out, for the sake of speed.
     # Else use ids list to find models to populate model_db table
     if len(ids) == 0:
         #            mfr = sql_session.query(Mfr).all() - This will go to populate all makes
         return ("No models selected - Nothing to add")
     else:
         mfr = sql_session.query(Mfr).filter(Mfr.id.in_(ids)).all()
     count = 0
     for entry in mfr:
         # Try to get info from NHTSA website API. If not successful, then skip the model
         try:
             # due to bugs in NHTSA database some records don't have short name in this case
             # try to substitute full name. NHTSA model unique ids is all messy, so need to use
             # just mfr name when querying their api
             # so try to plug the first part of the long name and hope that it will work.
             if not entry.commonname:
                 entry.commonname = entry.name.split(' ')[0]
             model_data = Model.getModeldata(year, entry.commonname.lower())
             for row in model_data:
                 model_id = row['Model_ID']
                 #Check if this model_id is present in db, if Yes => skip the record
                 if sql_session.query(Model).filter_by(
                         id=model_id).count() == 0:
                     url_link = ''
                     model_name = row['Model_Name']
                     # Get URL to pic from flickr.com
                     url_link = Model.getModelPicLink(
                         entry.commonname.lower(), model_name)
                     model_line = Model(id=model_id,
                                        name=model_name,
                                        mfr_id=entry.id,
                                        pic_url=url_link,
                                        dealership='placeholder',
                                        price=0,
                                        user_id=login_session['user_id'])
                     sql_session.add(model_line)
                     print('Added model with Id(no commitment made yet): ' +
                           str(model_id) + '.' + entry.commonname + ' ' +
                           model_name)
                     count += 1
         except:
             return ('Error raised. MFR ID:' + str(entry.id) + '.' +
                     'MFR Name:' + entry.name)
     sql_session.commit()
     return ('All commits added successfully. %s models added succesfully' %
             count)
Example #7
0
def mfr_delete(mfr_id):
    if not mfr_id:
        return 'Error. No record to delete. Please go back'
    if 'username' not in login_session:
        flash('Please login to be able to delete content')
        return redirect(url_for('mainpage', mfr=mfr_id))
    mfr_delete_record = sql_session.query(Mfr).filter(Mfr.id == mfr_id).one()
    if mfr_delete_record.user_id != login_session['user_id']:
        flash("You are not the original creator! You don't have permission to delete the record")
        return redirect(url_for('mainpage', mfr=mfr_id))
    sql_session.delete(mfr_delete_record)
    sql_session.commit()
    flash('Record successfully deleted')
    return redirect(url_for('mainpage'))
Example #8
0
def mfr_edit(mfr_id):
# return ("<script>function myFunction() {alert('You are not authorized to edit this restaurant." +
# " Please create your own restaurant in order to edit.');}</script><body onload='myFunction()''>")
    if not mfr_id:
        return 'Error. No record to edit. Please go back'
    if 'username' not in login_session:
        flash('Please login to be able to edit content')
        return redirect(url_for('mainpage', mfr=mfr_id))
    mfr_edit_record = sql_session.query(Mfr).filter(Mfr.id == mfr_id).one()
    if mfr_edit_record.user_id != login_session['user_id']:
        flash("You are not the original creator! You don't have permission to edit the record")
        return redirect(url_for('mainpage', mfr=mfr_id))
    if request.method == 'POST':
        values = request.form
        try:
            new_name = values['mfr_full_name']
            new_country = values['mfr_country']
            new_commonname = values['mfr_commonname']
            new_vehicle_type = values['mfr_vehicle_type']
        except:
            return ('Error accesing form value. Please <a href="/" > click here </a>'
                    ' to go to main menu')
        if not new_name or not new_country or not new_vehicle_type:
            error = 'All fields except short name must be filled in'
            return render_template('edit_mfr.html', record=mfr_edit_record, error=error,
                                   record_name=new_name, record_country=new_country,
                                   record_commonname=new_commonname,
                                   record_vehicle_type=new_vehicle_type)
        mfr_edit_record.name = new_name
        mfr_edit_record.country = new_country
        mfr_edit_record.commonname = new_commonname
        mfr_edit_record.vehicle_type = new_vehicle_type
        try:
            sql_session.commit()
            flash('successfully updated record ID: %s' % mfr_edit_record.id)
            return redirect(url_for('mainpage', mfr=mfr_id))
        except:
            return 'Error updating database. Please try again later'
    else:
        return render_template('edit_mfr.html', record=mfr_edit_record)