Python model 模块,db() 实例源码

我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用model.db()

项目:game_recommendations    作者:ceorourke    | 项目源码 | 文件源码
def user_profile(user_id):
    """Show user profile"""

    user_info = User.query.filter_by(user_id=user_id).first()
    account_created = user_info.account_created
    account_created = str(account_created)[:11]
    system_info = UserSystem.query.filter_by(user_id=user_id).all()
    rating_info = (db.session.query(Game.name, Rating.score, Game.game_id)
                             .join(Rating).filter(Rating.user_id==user_id)
                             .all())
    num_games =  (db.session.query(func.count(Rating.user_id))
                            .filter(Rating.user_id == user_id)
                            .first())
    num_games = int(num_games[0])

    return render_template("user_profile.html", user_info=user_info,
                                                system_info=system_info,
                                                rating_info=rating_info,
                                                account_created=account_created,
                                                user_id=user_id,
                                                num_games=num_games)
项目:game_recommendations    作者:ceorourke    | 项目源码 | 文件源码
def game_rating():
    """Update or add game rating to database"""

    rating = request.form.get("rating")
    game_id = request.form.get("game_id")
    current_user = session["user_id"]

    existing_rating = Rating.query.filter_by(user_id=current_user, game_id=game_id).first()

    if existing_rating is None:
        new_rating = Rating(user_id=current_user, game_id=game_id,score=rating)

        db.session.add(new_rating)
        db.session.commit()

    else:
        existing_rating.score = rating
        db.session.commit()

    return jsonify({"rating": rating})
项目:spc    作者:whbrewer    | 项目源码 | 文件源码
def load_apps():
    """load apps into myapps global dictionary"""
    global myapps, default_app
    # Connect to DB
    result = db().select(apps.ALL)
    myapps = {}
    for row in result:
        name = row['name']
        appid = row['id']
        preprocess = row['preprocess']
        postprocess = row['postprocess']
        input_format = row['input_format']
        try:
            print 'loading: %s (id: %s)' % (name, appid)
            myapps[name] = app_instance(input_format, name, preprocess, postprocess)
            myapps[name].appid = appid
            myapps[name].input_format = input_format
        except:
            exc_type, exc_value, exc_traceback = sys.exc_info()
            print traceback.print_exception(exc_type, exc_value, exc_traceback)
            print 'ERROR: LOADING: %s (ID: %s) FAILED TO LOAD' % (name, appid)
    default_app = name # simple soln - use last app read from DB
    return True
项目:spc    作者:whbrewer    | 项目源码 | 文件源码
def get_stats():
    root.authorized()
    params = {}

    # number of jobs in queued, running, and completed states
    params['nq'] = db(jobs.state=='Q').count()
    params['nr'] = db(jobs.state=='R').count()
    params['nc'] = db(jobs.state=='C').count()

    params['cpu'] = psutil.cpu_percent()
    params['vm'] = psutil.virtual_memory().percent
    params['disk'] = psutil.disk_usage('/').percent
    params['cid'] = request.query.cid
    params['app'] = request.query.app

    return template("stats", params)
项目:sfparks    作者:cvlong    | 项目源码 | 文件源码
def process_registration():
    """Add new user to database and log them in."""

    email = request.form.get('email')
    password = request.form.get('password')

    # instantiate a user object with the information provided
    new_user = User(email=email, 
                    password=password)

    # add user to db session and commit to db
    db.session.add(new_user)
    db.session.commit()

    # add user to the session; redirect to homepage
    session['user'] = new_user.user_id
    session['waypoints'] = []

    flash("You're logged in.")
    return redirect('/')
项目:MeetingMetrics_Hackathon    作者:jabrabec    | 项目源码 | 文件源码
def query_recurring_meetings():
    """Helper function used by query database for recurring meetings"""

    dicto = {}
    # labels = []
    # data = []

    meetings = Meeting.query.filter_by(recurring_id=1).all()

    # meetings = db.session.query(
    #                             Meeting.meeting_title,
    #                             Meeting.meeting_time,
    #                             # Rating.score).all()
    #                             Rating.score).filter_by(Meeting.recurring_id=1)
# for mtg in meetings:
#     print mtg.meeting_title
#     for rating in mtg.rating:
#         print rating.score

    for mtg in meetings:
        title = meeting_title
        dicto[mtg.meeting_time] = dicto.get(mtg.rating.score)

    return
项目:insomnia-app    作者:k-wiz    | 项目源码 | 文件源码
def integer_type_data(user_id, start_date, end_date, column_name):
    """Returns a tuple of lists, one list of dates as strings, and one list of 
    data points as integers. column_name should be an object with attribute
    column_name, e.g. Entry.stress_level."""

    data_points = sorted(db.session.query(Entry.date, column_name).filter\
        (Entry.user_id == user_id, Entry.date >= start_date, 
        Entry.date <= end_date).all())

    dates = []
    scores = []

    for item in data_points:
        date = "%s/%s" % (item[0].month, item[0].day)
        dates.append(date)

        score = item[1]
        scores.append(score)

    return dates, scores
项目:insomnia-app    作者:k-wiz    | 项目源码 | 文件源码
def hours_sleep_data(user_id, start_date, end_date):
    """Returns a tuple of lists, one list of dates as strings,
    and one list of hours_sleep data points as integers."""

    data_points = sorted(db.session.query(Entry.date, Entry.minutes_asleep).filter
        (Entry.user_id == user_id, Entry.date>= start_date, Entry.date <= 
        end_date).all())

    dates = []
    hours_sleep_list = []

    for item in data_points:
        date = "%s/%s" % (item[0].month, item[0].day)
        dates.append(date)

        hours_sleep = item[1]  / 60
        hours_sleep_list.append(hours_sleep)

    return dates, hours_sleep_list
项目:insomnia-app    作者:k-wiz    | 项目源码 | 文件源码
def insom_factors(user_id, column_name):
    """Returns the percentage co-occurrence between insomnia(T/F) 
    and another column with T/F values. column_name should be a table object
    with attribute column_name."""

    query_list = db.session.query(Entry.insomnia, column_name).filter\
    (Entry.user_id == user_id).order_by('date').all()

    insom_list = []
    mens_list = []

    for item in query_list:
        insom_list.append(item[0])
        mens_list.append(item[1])

    co_occurrence = calculate_similarity(insom_list, mens_list)

    return co_occurrence
项目:hb-final-project    作者:kjlundsgaard    | 项目源码 | 文件源码
def invite_user():
    """Allows user to invite other member to group by email"""

    email = request.form.get('invite')
    user = User.query.filter_by(email=email).first()
    group_id = request.form.get('group_id')
    group = Group.query.filter_by(group_id=group_id).first()
    if user:
        user_search = UserGroup.query.filter_by(user_id=user.user_id, group_id=group_id).first()
        if user_search:
            flash("User is already in this group")
        else:
            new_user = UserGroup(user_id=user.user_id, group_id=group_id)
            db.session.add(new_user)
            db.session.commit()
            flash("Added new user " + email + " to " + group.group_name)
    else:
        flash("No such user")

    return redirect('/')
项目:hb-final-project    作者:kjlundsgaard    | 项目源码 | 文件源码
def delete_list():
    """Allows user to remove a list from a group"""

    list_id = request.form.get('list_id')

    list_item = List.query.get(list_id)

    restaurants_lists = RestaurantList.query.filter_by(list_id=list_id).all()

    db.session.delete(list_item)
    for rl in restaurants_lists:
        db.session.delete(rl)
    db.session.commit()

    flash("Removed " + list_item.list_name)
    return jsonify(result='success')
项目:hb-final-project    作者:kjlundsgaard    | 项目源码 | 文件源码
def add_restaurant_to_faves():
    """Adds a restaurant to a user's favorites list"""

    restaurant_id = request.form.get('rest_id')
    user_id = session.get('user')

    get_fave_restaurant = Fave.query.filter_by(restaurant_id=restaurant_id, user_id=user_id).first()

    if get_fave_restaurant:
        Fave.query.filter_by(fave_id=get_fave_restaurant.fave_id).delete()
        db.session.commit()
    else:
        fave_restaurant = Fave(restaurant_id=restaurant_id, user_id=user_id)
        db.session.add(fave_restaurant)
        db.session.commit()

    return jsonify(result="success", id=restaurant_id)
项目:hb-final-project    作者:kjlundsgaard    | 项目源码 | 文件源码
def return_restaurants():
    """Gives response to browser of restaurants in db for given list"""

    list_id = request.form.get('list_id')
    item_id = request.form.get('id')
    restaurants_lists = RestaurantList.query.filter_by(list_id=list_id, visited=False).all()

    restaurants = []
    for item in restaurants_lists:
        restaurant = Restaurant.query.filter_by(restaurant_id=item.restaurant_id).first()

        restaurants.append({'restaurant_name': restaurant.restaurant_name,
                            'yelp_rating': restaurant.yelp_rating,
                            'latitude': restaurant.latitude,
                            'longitude': restaurant.longitude,
                            'restaurant_id': restaurant.restaurant_id})

    print restaurants
    return jsonify(status="success", results=restaurants, id=item_id)
项目:Spent    作者:emilydowgialo    | 项目源码 | 文件源码
def remove_budget(id):
    """ Remove a budget from the database """

    # This is the budget object we are working with
    budget_at_hand = Budget.query.filter_by(id=id).first()

    # This is the user id of the user in the session
    user_id = session.get('id')

    # Check to make sure the budget is associated with the logged in user
    if user_id == budget_at_hand.budget_userid:

        # Deletes the budget item from the budget table
        db.session.delete(budget_at_hand)
        db.session.commit()

    # Redirect the user to their dashboard
    return redirect(url_for('dashboard', id=user_id))
项目:planty    作者:agnaite    | 项目源码 | 文件源码
def process_login():
    """Processes user input and either logs user in if input is in database"""

    # gets the user input from the username field and looks it up in the database
    username = request.form.get('username')
    user = User.query.filter_by(username=username).first()

    # if username entered exists in db, gets the password entered and compares
    # it to the one in the database
    if user:
        # if password is correct, adds user to the current session and redirects to home page
        if bcrypt.hashpw(request.form.get('password').encode('utf-8'), user.password.encode('utf-8')).decode() == user.password:
            session['logged_in'] = user.user_id
            print 'logged in'
            return jsonify(session)
        # if password is incorrect, redirects to login page
        else:
            return 'error'
    # if username is not in the database, redirects to the registration form
    else:
        return 'error'
项目:planty    作者:agnaite    | 项目源码 | 文件源码
def update_user():
    """Saves updated user info."""

    user_id = request.form.get('id')
    user_to_update = User.query.get(int(user_id))

    if bcrypt.hashpw(request.form.get('password').encode('utf-8'), user_to_update.password.encode('utf-8')).decode() == user_to_update.password:
        if request.form.get('email'):
            user_to_update.email = request.form.get('email')
        if request.form.get('phone'):
            user_to_update.phone = request.form.get('phone')
    else:
        return "bad password"

    db.session.commit()

    return "ok"


# PlantUser Routes *********************************
项目:planty    作者:agnaite    | 项目源码 | 文件源码
def add_reminder():
    """Adds a watering reminder for a particular PlantUser"""

    user_id = int(request.form.getlist('user_id')[0].encode('utf-8'))

    if User.query.get(user_id).phone:
        plant_id = int(request.form.getlist('plant_id')[0].encode('utf-8'))
        days = request.form.getlist('days')[0].encode('utf-8')

        plant_user = PlantUser.query.filter(PlantUser.user_id == user_id, PlantUser.plant_id == plant_id).first()
        plant_user.watering_schedule = days

        db.session.commit()

        return 'ok'
    else:
        return 'phone number missing'
项目:planty    作者:agnaite    | 项目源码 | 文件源码
def show_plant_details(plant_id):
    """Show individual plant's page"""

    found_plant = Plant.query.get(plant_id)

    if not found_plant.image:
        found_plant.image = "/static/img/placeholder-image.png"

        db.session.commit()

    found_plant = found_plant.__dict__

    if '_sa_instance_state' in found_plant:
        del found_plant['_sa_instance_state']

    return jsonify(found_plant)
项目:planty    作者:agnaite    | 项目源码 | 文件源码
def process_new_plant():
    """Gets the user input from new plant form and adds to the database"""

    # if user did not add image url, get one from flickr
    name = request.form.get('name')
    image = request.form.get('image')

    if not image:
        image = get_flickr_image(name)

    # gets plant info from angular's data passed in and creates new Plant instance
    new_plant = Plant(name=name,
                      species=request.form.get('species'),
                      image=image,
                      water=request.form.get('water'),
                      sun=request.form.get('sun'),
                      humidity=request.form.get('humidity'),
                      temperature=request.form.get('temp'))

    # adds plant to the database and saves
    db.session.add(new_plant)
    db.session.commit()

    # returns plant ID to angular's callback
    return str(new_plant.plant_id)
项目:planty    作者:agnaite    | 项目源码 | 文件源码
def update_plant():
    """Updates plant"""

    plant = Plant.query.get(request.form.get('plant_id'))

    plant.name = request.form.get('name')
    plant.species = request.form.get('species')
    plant.image = request.form.get('image')
    plant.water = request.form.get('water')
    plant.sun = request.form.get('sun')
    plant.humidity = request.form.get('humidity')
    plant.temperature = request.form.get('temperature')

    db.session.commit()

    return 'plant updated'
项目:Calendar-Analytics    作者:maheskett    | 项目源码 | 文件源码
def get_team_events(selected_calendars, startdate, enddate):
    """Queries db for selected calendars and date range,
    returns list of event objects."""

    startdate = to_datetime(startdate)
    enddate = to_datetime(enddate)

    events = set()
    evts = db.session.query(CalEvent, Event).join(Event).all()
    for cal in selected_calendars:
        for calevent, event in evts:
            if cal.lower() in calevent.calendar_id and event.start > startdate and event.end < enddate:
                events.add(event)

    events = list(events)
    return [event.serialize() for event in events]
项目:game_recommendations    作者:ceorourke    | 项目源码 | 文件源码
def check_for_new_games():
    """Make an API call and compare new games with existing db"""

    platforms = [130, 48, 49, 37, 46, 41, 5, 47, 56, 4, 21, 19, 18, 58, 20, 22, 33, 24,
            87, 7, 8, 9, 38, 45, 11, 12, 36, 92, 14, 6, 13, 64, 29, 35, 32, 23, 34,
            39, 86, 51, 15, 13 ,79, 80, 119, 120, 135, 136]
    to_add = {}
    # get the new list of games per platform
    systems_json = igdb.platforms({
        'ids':platforms,
        'fields' : 'games'
    })

    print type(systems_json[0])
    # get the existing list of games per platform
    existing_file = open('seed_data/systemsfile2.json')
    existing = existing_file.read()
    existing = json.loads(existing)
    # compare this list to the existing list
    for system in systems_json:
        for existing_systems in existing:
            if system['id'] == existing_systems['id']:
                for game in system['games']:
                    if game not in existing_systems['games']:
                        if system['id'] in to_add:
                            to_add[system['id']].append(game)
                        else:
                            to_add[system['id']] = [game]
            else:
                print "No differences"


    get_new_games(to_add)
    existing_file.close()
    # overwrite the old file with the new information
    with open('seed_data/systemsfile2.json', 'w') as fp:
            json.dump(systems_json, fp)
项目:game_recommendations    作者:ceorourke    | 项目源码 | 文件源码
def register_process():
    """Get information from registration form."""

    username = request.form.get("username")
    email = request.form.get("email")
    password = request.form.get("password")
    systems = request.form.getlist("systems")
    account_created = datetime.now()

    existing_username = User.query.filter_by(username=username).first()
    existing_email = User.query.filter_by(email=email).first()

    # check if the username is in use
    if existing_username is None and existing_email is None:
        #check if the email is in use
        new_user = User(username=username, email=email, password=password, 
                        account_created=account_created)

        db.session.add(new_user)
        db.session.commit()
        get_user_rating(games)

        for system in systems:
            # add each system to the database for the specific user
            system_id = db.session.query(System.system_id).filter(System.name==system).first()
            new_user_system = UserSystem(user_id=new_user.user_id, system_id=system_id)

            db.session.add(new_user_system)
            db.session.commit()

        flash("Successfully registered " + username + "!")
        return redirect("/")

    else:
        flash("Username or email already in use")
        # TODO probably handle this in AJAX on the form and be more specific
        # as to whether it was the username or email that failed

    return redirect("/")
项目:spc    作者:whbrewer    | 项目源码 | 文件源码
def get_status(jid):
    # following headers are needed because of CORS
    response.headers['Access-Control-Allow-Origin'] = '*'
    response.headers['Access-Control-Allow-Methods'] = 'GET, POST, PUT, OPTIONS'
    response.headers['Access-Control-Allow-Headers'] = 'Origin, Accept, Content-Type, X-Requested-With, X-CSRF-Token'
    resp = db(jobs.id==jid).select(jobs.state).first()
    if resp is None: return 'X'
    else: return resp.state
项目:spc    作者:whbrewer    | 项目源码 | 文件源码
def execute():
    app = request.forms['app']
    user = request.forms['user']
    cid = request.forms['cid']
    desc = request.forms['desc']
    np = request.forms['np']
    appmod = pickle.loads(request.forms['appmod'])
    # remove the appmod key
    del request.forms['appmod']
    appmod.write_params(request.forms, user)

    # if preprocess is set run the preprocessor
    try:
        if appmod.preprocess:
            run_params, _, _ = appmod.read_params(user, cid)
            base_dir = os.path.join(user_dir, user, app)
            process.preprocess(run_params, appmod.preprocess, base_dir)
        if appmod.preprocess == "terra.in":
            appmod.outfn = "out"+run_params['casenum']+".00"
    except:
        return template('error', err="There was an error with the preprocessor")

    # submit job to queue
    try:
        priority = db(users.user==user).select(users.priority).first().priority
        uid = users(user=user).id
        jid = sched.qsub(app, cid, uid, np, priority, desc)
        return str(jid)
        #redirect("http://localhost:"+str(config.port)+"/case?app="+str(app)+"&cid="+str(cid)+"&jid="+str(jid))
    except OSError:
        return "ERROR: a problem occurred"
项目:spc    作者:whbrewer    | 项目源码 | 文件源码
def get_status(jid):
    resp = db(jobs.id==jid).select(jobs.state).first()
    if resp is None: return 'X'
    else: return resp.state
项目:spc    作者:whbrewer    | 项目源码 | 文件源码
def execute():
    app = request.forms['app']
    user = request.forms['user']
    cid = request.forms['cid']
    desc = request.forms['desc']
    np = request.forms['np']
    appmod = pickle.loads(request.forms['appmod'])
    # remove the appmod key
    del request.forms['appmod']

    appmod.write_params(request.forms, user)

    # if preprocess is set run the preprocessor
    try:
        if appmod.preprocess:
            run_params, _, _ = appmod.read_params(user, cid)
            base_dir = os.path.join(user_dir, user, app)
            process.preprocess(run_params, appmod.preprocess, base_dir)
        if appmod.preprocess == "terra.in":
            appmod.outfn = "out"+run_params['casenum']+".00"
    except:
        return template('error', err="There was an error with the preprocessor")

    # submit job to queue
    try:
        priority = db(users.user==user).select(users.priority).first().priority
        uid = users(user=user).id
        jid = sched.qsub(app, cid, uid, np, priority, desc)
        return str(jid)
        #redirect("http://localhost:"+str(config.port)+"/case?app="+str(app)+"&cid="+str(cid)+"&jid="+str(jid))
    except OSError:
        return "ERROR: a problem occurred"
项目:MeetingMetrics_Hackathon    作者:jabrabec    | 项目源码 | 文件源码
def query_meetings():
    """Helper function used by query database for all meetings"""

    sql_query = """SELECT * FROM meetings"""

    # perform db query and get all results
    cursor = db.session.execute(sql_query)
    results = cursor.fetchall()

    return results
项目:happyfridays    作者:jessicaraepetersen    | 项目源码 | 文件源码
def clear():
    """Clears flask session and SQL tables once user is done ."""

    session.clear()
    db.session.query(Track).delete()
    db.session.query(Playlist).delete()
    db.session.query(UserAlbum).delete()
    db.session.query(Album).delete()
    db.session.query(Artist).delete()
    db.session.query(User).delete()
    db.session.commit()
    print "------User's session & data cleared from DB------"
    return redirect('/')
项目:happyfridays    作者:jessicaraepetersen    | 项目源码 | 文件源码
def add_to_playlist():
    """Add album to user's Spotify playlist from dropdown menu."""

    token = session['token']
    user_id = session['user_id']
    playlist_id = request.form.get('playlist_id')
    album_id = request.form.get('album_id')


    # Query SQL db for track URIs, which are needed to add entire album to playlist
    tracks = db.session.query(Track).join(Track.albums).filter_by(album_id=album_id).all()
    list_of_track_uris = []

    for track in tracks:
        list_of_track_uris.append(track.album_track_uri)
    # uses the Spotipy method to add album to Spotify user's playlist
    if token:
        sp = spotipy.Spotify(auth=token)
        sp.user_playlist_add_tracks(user_id, playlist_id, list_of_track_uris)
    #The user selects a playlist to add an album to. This queries the name of the
    # playlist to include in the flash-like message.
    playlist = Playlist.query.filter_by(playlist_id=playlist_id).one()
    playlist_name = str(playlist.playlist_name)
    #The user selects a playlist to add an album to. This queries the name of the
    # album to include in the flash-like message.
    album = Album.query.filter_by(album_id=album_id).one()
    album_name = album.album_name
    # return playlist_name and album_name for flash-like message
    return jsonify({'playlist_name': playlist_name, 'album_name': album_name})
项目:insomnia-app    作者:k-wiz    | 项目源码 | 文件源码
def first_entry(user_id):
    """Returns date of user's first entry as a datetime object."""

    first_entry = db.session.query(Entry.date).filter(Entry.user_id == user_id).\
    order_by('date').first()

    return first_entry[0]
项目:insomnia-app    作者:k-wiz    | 项目源码 | 文件源码
def last_entry(user_id):
    """Returns date of user's last entry as a datetime object."""

    last_entry = db.session.query(Entry.date).filter(Entry.user_id == user_id).\
    order_by(desc('date')).first()

    return last_entry[0]



# NOTE: Generalize and rename function.
项目:insomnia-app    作者:k-wiz    | 项目源码 | 文件源码
def calculate_avg_sleep(user_id, start_date, end_date):
    """Calculates user's average hours of sleep per night from start_date
    to end_date."""

    avg_sleep = db.session.query(func.avg(Entry.minutes_asleep)).filter(Entry.user_id\
     == user_id, Entry.date >= start_date, Entry.date <= end_date)
    avg_sleep = int(avg_sleep[0][0])/60.0
    return avg_sleep
项目:insomnia-app    作者:k-wiz    | 项目源码 | 文件源码
def calculate_avg(user_id, start_date, end_date, column_name):
    """Calculates average of field with column_name from start_date to end_date."""

    avg = db.session.query(func.avg(column_name)).filter\
                        (Entry.user_id == user_id, Entry.date >= start_date, \
                            Entry.date <= end_date)
    avg = avg[0][0]
    return avg
项目:insomnia-app    作者:k-wiz    | 项目源码 | 文件源码
def calculate_median_sleep(user_id, start_date, end_date):
    """Calculates user's all-time median hours of sleep per night."""

    minutes_asleep_tups = db.session.query(Entry.minutes_asleep).filter\
                            (Entry.user_id == user_id, Entry.date >= start_date,\
                            Entry.date <= end_date).order_by('minutes_asleep').all()

    minutes_asleep_lst = []
    for item in minutes_asleep_tups:
        minutes_asleep_lst.append(item[0])

    median_sleep = median(minutes_asleep_lst) / 60
    return median_sleep
项目:insomnia-app    作者:k-wiz    | 项目源码 | 文件源码
def frequency_insomnia_type(user_id, start_date, end_date, insom_type):
    """Returns count of occurrence of insom_type from start_date to end_date."""

    frequency_type = db.session.query(Entry.insom_type, db.func.count\
                            (Entry.insom_type)).filter(Entry.user_id == user_id,\
                            Entry.date >= start_date, Entry.date <= end_date, \
                            Entry.insom_type == insom_type).\
                            group_by(Entry.insom_type).all()

    if len(frequency_type) != 0:
        return frequency_type[0][1]
    else:
        return 0
项目:insomnia-app    作者:k-wiz    | 项目源码 | 文件源码
def dashboard():
    """Display user's dashboard."""

    # Retrieve form data. 
    user_id = session["user_id"]
    date = datetime.now()
    date = date.replace(hour=0, minute=0, second=0, microsecond=0)
    minutes_asleep = int(request.form.get("hours_sleep")) * 60
    insomnia = convert_to_boolean(request.form.get("insomnia"))
    insom_type = request.form.get("insom_type")
    insom_severity = int(request.form.get("insom_severity"))
    alcohol = convert_to_boolean(request.form.get("alcohol"))
    caffeine = convert_to_boolean(request.form.get("caffeine"))
    menstruation = convert_to_boolean(request.form.get("menstruation"))
    bedtime = datetime.strptime((request.form.get("bedtime")), '%H:%M')
    stress_level = int(request.form.get("stress_level"))
    activity_level = int(request.form.get("activity_level"))


    # Create new record in db if no existing record with user_id and date;
    # otherwise, update current record. 
    create_or_update_record(user_id, date, minutes_asleep, insomnia, insom_type,
                            insom_severity, alcohol, caffeine, menstruation,
                            bedtime, stress_level, activity_level)



    # Pass calculated data to template
    return render_template("dashboard.html")


##########################################################################
项目:hb-final-project    作者:kjlundsgaard    | 项目源码 | 文件源码
def sign_up_user():
    """Signs up new user"""

    email = request.form.get("email")
    password = request.form.get("password")
    fname = request.form.get("fname")
    lname = request.form.get("lname")

    user = User.query.filter_by(email=email).first()
    # if user already exists, checks password and logs them in if correct. If not, prompts
    # for password again
    if user:
        if user.verify_password(password):
            session['user'] = user.user_id
            flash("You are now logged in")
            return redirect('/')
            # return redirect('/users/' + str(user.user_id))
        else:
            flash("Password incorrect - There is already a user with this email")
            return redirect('/')
    else:
        #instantiates new user and passes user_id to session
        user = User(email=email, password=password, fname=fname, lname=lname)
        db.session.add(user)
        db.session.commit()
        session['user'] = user.user_id
        flash("Your account has been created")
        return redirect('/')
项目:hb-final-project    作者:kjlundsgaard    | 项目源码 | 文件源码
def add_new_group():
    """Allows user to create a new group"""

    group_name = request.form.get('group')
    user_id = session.get('user')

    new_group = Group(group_name=group_name)
    db.session.add(new_group)
    db.session.commit()

    new_user_group = UserGroup(group_id=new_group.group_id, user_id=user_id)
    db.session.add(new_user_group)
    db.session.commit()

    return redirect('/')
项目:hb-final-project    作者:kjlundsgaard    | 项目源码 | 文件源码
def add_new_list():
    """Allows user to add a new list"""

    list_name = request.form.get('list')
    group_id = request.form.get('group_id')

    new_list = List(list_name=list_name, group_id=group_id)
    db.session.add(new_list)
    db.session.commit()

    return redirect('/lists/' + str(new_list.list_id))
项目:hb-final-project    作者:kjlundsgaard    | 项目源码 | 文件源码
def add_restaurant():
    """Allows user to add restaurant to a list"""

    item_id = request.form.get('id')
    restaurant_name = request.form.get('restaurant_name')
    yelp_rating = request.form.get('yelp_rating')
    latitude = request.form.get('latitude')
    longitude = request.form.get('longitude')
    list_id = request.form.get('list_id')
    address = request.form.get('address')
    categories = request.form.get('categories')
    neighborhoods = request.form.get('neighborhoods')
    link = request.form.get('url')

    # check if restaurant already in db
    get_restaurant = Restaurant.query.filter_by(restaurant_name=restaurant_name, latitude=latitude, longitude=longitude).first()
    if get_restaurant:
        # check if already part of list then add if no
        get_restaurant_list = RestaurantList.query.filter_by(restaurant_id=get_restaurant.restaurant_id, list_id=list_id).first()
        if get_restaurant_list:
            flash("Restaurant is already part of list")
        else:
            new_restaurant_list = RestaurantList(restaurant_id=get_restaurant.restaurant_id, list_id=list_id)
            db.session.add(new_restaurant_list)
            db.session.commit()
    # if restaurant is not already in db, add it and add to RestaurantList
    else:
        new_restaurant = Restaurant(restaurant_name=restaurant_name, yelp_rating=yelp_rating, latitude=latitude, longitude=longitude, address=address, categories=categories, neighborhoods=neighborhoods, link=link)
        db.session.add(new_restaurant)
        db.session.commit()
        # need this line because we just added the restaurant to db and need to get the id to add to RestaurantList
        restaurant_info = Restaurant.query.filter_by(restaurant_name=restaurant_name, latitude=latitude, longitude=longitude).first()
        new_restaurant_list = RestaurantList(restaurant_id=restaurant_info.restaurant_id, list_id=list_id)
        db.session.add(new_restaurant_list)
        db.session.commit()

    return jsonify(status='success', id=item_id, restaurant_name=restaurant_name, yelp_rating=yelp_rating, latitude=latitude, longitude=longitude)
项目:hb-final-project    作者:kjlundsgaard    | 项目源码 | 文件源码
def leave_group():
    """Allows a user to leave a group"""

    group_id = request.form.get('group_id')
    user_id = session.get('user')

    get_user_group = UserGroup.query.filter_by(group_id=group_id, user_id=user_id).first()

    db.session.delete(get_user_group)
    db.session.commit()

    flash("You have left the group")
    return jsonify(result="success")
项目:hb-final-project    作者:kjlundsgaard    | 项目源码 | 文件源码
def mark_visited():
    """Marks visited as true for restaurants_lists"""

    rest_id = request.form.get('rest_id')
    list_id = request.form.get('list_id')

    restaurant_list = RestaurantList.query.filter_by(restaurant_id=rest_id, list_id=list_id).first()

    restaurant_list.visited = True
    db.session.commit()

    return jsonify(status="success", id=rest_id)
项目:Spent    作者:emilydowgialo    | 项目源码 | 文件源码
def profile_edit():
    """ Edit profile information """

    # Set the value of the user id of the user in the session
    id = session.get('id')

    # Query the database for the user
    user_info = User.query.filter_by(id=id).first()

    # Get information from the forms
    name = request.form.get("profile-name")
    email = request.form.get("profile-email")
    password = request.form.get("new-password")

    # Replace info in the database with new info
    if name:
        user_info.name = name
        db.session.commit()

    if password:
        user_info.password = password
        db.session.commit()

    if email:
        user_info.email = email
        db.session.commit()

    name_info = {
        'name': name,
        'email': email
    }

    # Return jsonified budget info to submit-new-account-info.js
    return jsonify(name_info)
项目:Spent    作者:emilydowgialo    | 项目源码 | 文件源码
def remove_expenditure(id):
    """ Remove an expenditure from the database """

    # This is the expenditure object we are working with
    expenditure_at_hand = Expenditure.query.filter_by(id=id).first()

    # Deletes the expenditure item from the expenditure table
    db.session.delete(expenditure_at_hand)
    db.session.commit()

    # Return jsonified id to delete-expenditure.js
    return jsonify({"expenditure_id": id})
项目:pillow-flask    作者:pybites    | 项目源码 | 文件源码
def _store_banner(data):
    banner = Banner.query.filter_by(name=data.name).first()
    # if banner in db, update record, if not add it
    if banner:
        banner.name = data.name
        banner.image_url1 = data.image1
        banner.image_url2 = data.image2
        banner.text = data.text
        banner.background = data.background
    else:
        banner = Banner(data)
        db.session.add(banner)
    db.session.commit()
项目:Stroll-Safely    作者:Munnu    | 项目源码 | 文件源码
def get_position_geohash(points):
    """ This takes points and with these points find out what geohash each falls
        under. Then we could get the crime_index and total_crimes
    """

    # takes in a list as a parameter of [(lat, lng) ... (lat, lng)]
    coords_data = []  # to store the dictionary generated

    # do something like a for loop over here
    for point in points:
        geohash_sql = "SELECT * " + \
                      "FROM nyc_crimes_by_geohash " + \
                      "WHERE geohash=" + \
                      "ST_GeoHash(st_makepoint(%s, %s), 7);" % \
                      (point[0], point[1])

        # execute the raw sql, and there should only be one result... so get that.
        geohash_query = db.engine.execute(geohash_sql).fetchone()

        if geohash_query is None:
            # if the geohash isn't found, need to do something,
            # query PostGIS for the geohash (not in db)
            # then assume that there are no crimes in the area
            geohash_of_point = "SELECT ST_GeoHash(geometry(Point(%s, %s)), 7);" \
                % (point[0], point[1])

            geohash_found = db.engine.execute(geohash_of_point).fetchone()

            geohash_query = [0, geohash_found[0], 0, 0.0]

        geohash_query_data = {
            'geohash': geohash_query[1],
            'total_crimes': geohash_query[2],
            'crime_index': float(geohash_query[3]),
            'point': point
        }
        coords_data.append(geohash_query_data)

    # return something like [{dicte}, {dictw}], or {dict}, based on total pts
    return coords_data
项目:planty    作者:agnaite    | 项目源码 | 文件源码
def process_registration():
    """Processes user registration form"""

    # creates a new user instance
    new_user = User(username=request.form.get('username'),
                    first_name=request.form.get('fname'),
                    last_name=request.form.get('lname'),
                    password=bcrypt.hashpw(request.form.get('password').encode('utf-8'), bcrypt.gensalt()),
                    email=request.form.get('email'),
                    image=request.form.get('image'),
                    phone=request.form.get('phone'),
                    confirmed_at=datetime.now())

    # adds the new user instance to the database and saves

    print new_user

    db.session.add(new_user)
    db.session.commit()

    # logs new user in
    session['logged_in'] = new_user.user_id

    new_user = new_user.__dict__

    if '_sa_instance_state' in new_user:
        del new_user['_sa_instance_state']

    # passes new user's id to angular
    new_user['logged_in'] = session['logged_in']

    return jsonify(new_user)
项目:planty    作者:agnaite    | 项目源码 | 文件源码
def add_plant_to_user():
    """Add a plant to a User's account."""

    user_id = int(request.form.get('userId'))
    plant_id = int(request.form.get('plantId'))

    new_plantuser = PlantUser(user_id=user_id, plant_id=plant_id)

    db.session.add(new_plantuser)
    db.session.commit()

    return 'ok'
项目:planty    作者:agnaite    | 项目源码 | 文件源码
def delete_reminder():
    """Deletes a watering reminder for a particular PlantUser"""

    plant_id = int(request.form.getlist('plant_id')[0].encode('utf-8'))
    user_id = int(request.form.getlist('user_id')[0].encode('utf-8'))

    plant_user = PlantUser.query.filter(PlantUser.user_id == user_id, PlantUser.plant_id == plant_id).first()
    plant_user.watering_schedule = ''

    db.session.commit()

    return 'ok'


# Plant Routes *********************************