• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Python session.query函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Python中model.session.query函数的典型用法代码示例。如果您正苦于以下问题:Python query函数的具体用法?Python query怎么用?Python query使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。



在下文中一共展示了query函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。

示例1: load_user_id

def load_user_id():
    
    g.user_id = session.get('user_id')
    
    if g.user_id != None:
        g.user = db_session.query(User).filter_by(id=g.user_id)
        g.photos = db_session.query(Photo).filter_by(user_id=g.user_id).all()
开发者ID:HarryUp,项目名称:photoproject,代码行数:7,代码来源:Dev.py


示例2: view_movie

def view_movie(id):
    #id = movie.id
    user_id = g.user_id
    if g.user_id:
        movie = Movie.search_movie(id)
        ratings = Rating.search_rating(movie.id, user_id.id)
        beratement = None
        if ratings == None:
            ratings = movie.ratings
            rating_nums = []
            user_rating =None
            for r in ratings:
                rating_nums.append(r.rating)
            avg_rating = float(sum(rating_nums))/len(rating_nums)
            prediction = User.predict_rating(movie.id, user_id.id)
            the_eye = db_session.query(User).filter_by(email="[email protected]").one()
            eye_rating = db_session.query(Rating).filter_by(user_id = the_eye.id, movie_id = id).first()
            if not eye_rating:
                eye_rating = User.predict_rating(movie.id, the_eye.id)
                print eye_rating
            else:
                eye_rating = eye_rating.rating
            if prediction:
                difference = abs(eye_rating - prediction)
                messages = [ "I suppose you don't have such bad taste after all.",
                "I regret every decision that I've ever made that has brought me to listen to your opinion.",
                "Words fail me, as your taste in movies has clearly failed you.",
                "That movie is great. For a clown to watch. Idiot.",]
                beratement = messages[int(difference)]
            return render_template("view_movie.html", movie=movie, average=avg_rating, user_rating=user_rating, prediction=prediction, ratings = ratings, beratement=beratement)
        else:
            return render_template("view_movie.html", movie = movie, ratings=ratings)
    return render_template("")
开发者ID:sgottlieb,项目名称:ratings,代码行数:33,代码来源:judgement.py


示例3: movie

def movie(id):
    if not g.user_id:
        print 'no global user'
        movie = db_session.query(Movie).get(id)
        ratings = movie.ratings
        total = []
        for rating in ratings:
            total.append(rating.rating)
        avg_rating = float(sum(total))/len(total)
        return render_template('movie.html', movie=movie,
                        avg=avg_rating, user_rating=None, prediction=None)

    else:

        movie = db_session.query(Movie).get(id)
        ratings = movie.ratings 
        total = []
        user_rating = None
        for rating in ratings:     
            if rating.user_id == g.user_id:
                user_rating = rating
            total.append(rating.rating)
        avg_rating = float(sum(total))/len(total)

        # predict if no user rating
        prediction = None
        if not user_rating:
            user = db_session.query(User).get(g.user_id)
            prediction = user.predict_rating(movie)
            print "Prediction: ", prediction 

        return render_template('movie.html', movie=movie,
                                avg=avg_rating,
                                user_rating=user_rating,
                                prediction=prediction)
开发者ID:gwongz,项目名称:movie_ratings_app,代码行数:35,代码来源:main.py


示例4: sign_up_form

def sign_up_form():
		## input new user input into database
		email = request.form.get("email")
		password = request.form.get("password")
		username = request.form.get("username")
		first_name = request.form.get("first_name")
		last_name = request.form.get("last_name")
		gender = int(request.form.get("gender"))
		age = int(request.form.get("age"))
		zipcode = request.form.get("zipcode")
		
		hashed_password = hash_password(password, email)

		# create an instance of User with email, password, username, etc. as attributes
		user = User(email=email, password=hashed_password, username=username, first_name=first_name, 
			last_name=last_name, gender=gender, age=age, zipcode=zipcode)
		
		# check for email in db, if not there, add it to db
		if dbsession.query(User).filter_by(email = email).first():
			flash("This email address is already in use. Please try again.")
			return redirect("/sign_up")
		else:
			dbsession.add(user)
			dbsession.commit()
			created_user = dbsession.query(User).filter_by(email = email).first()
			session["login"] = created_user.id
			session["user"] = created_user
			return redirect("/pick_genres")
开发者ID:katereese,项目名称:Videodrome,代码行数:28,代码来源:flask_server.py


示例5: load_rss

def load_rss():
	# query the db: how long is it? Use this number later to empty db of old stories
    exstories = db_session.query(Stories).all()
    last_id = exstories[-1].id
    sources = {"NPR News": 'http://www.npr.org/rss/rss.php?id=1001', "BBC": 'http://feeds.bbci.co.uk/news/rss.xml'}
    for source in sources:
        print source
        # use feedparser to grab & parse the rss feed
        parsed = feedparser.parse(sources[source])
        print "parsed"
        # go through each entry in the RSS feed to pull out elements for Stories
        for i in range(len(parsed.entries)):
            title = parsed.entries[i].title
            url = parsed.entries[i].link
            source = source
            # pull abstract, parse out extra crap that is sometimes included
            abstract = (parsed.entries[i].description.split('<'))[0]
            print abstract

            # connect with db
            story = db_session.Stories(title=title, url=url, abstract=abstract, source=source)
            print "connected with db model??"
            # add story to db
            db_session.add(story)
            print "added story to db"
            # commit
        db_session.commit()
        print "committed"
    # delete from db old stories
    for l in range(1,last_id+1):
        db_session.query(Stories).filter_by(id=l).delete()
    db_session.commit()    
开发者ID:coderkat,项目名称:filtr,代码行数:32,代码来源:clock.py


示例6: post_genres

def post_genres():
	# get logged in user and user genre picks from pick_genres.html
	user_obj = get_current_user()
	genre_ids = [int(gi) for gi in request.form.getlist('genres')]

	# modifying the collection that we're itering over is no bueno
	genres_in_db = dbsession.query(Genre).all()
	for g in genres_in_db:
		if g in user_obj.genres:
			user_obj.genres.remove(g)
	try:
		print "Committing..\n\n"
		dbsession.commit()
	except:
		print "\n\n\nRolling back uh oh\n\n\n"
		dbsession.rollback()

	for gi in genre_ids:
		genre_obj = dbsession.query(Genre).filter_by(id=gi).first()
		user_obj.genres.append(genre_obj)
	try:
		dbsession.commit()
		cache.set(session["user"].id, None, timeout=0)
	except:
		dbsession.rollback()
	return redirect("/wall")
开发者ID:katereese,项目名称:Videodrome,代码行数:26,代码来源:flask_server.py


示例7: input_match_terms

def input_match_terms():
    """
    This allows the user to enter and edit the match percent and max
    salary percent match of their 401k match.
    """
    if g.logged_in is True:
        # If user selects that they do not have a 401k match, skip
        # all 401k match-related questions.
        match_401k = m_session.query(model.User).filter_by(
            id=g.user.id).first().company_match
        if match_401k == "Yes":
            if g.inputs is True:
                match_percent = m_session.query(model.User).filter_by(
                    id=g.user.id).first().match_percent
                match_salary = m_session.query(model.User).filter_by(
                    id=g.user.id).first().match_salary
            else:
                match_percent = match_salary = 0
            return render_template(
                "input_match_terms.html", match_percent=match_percent,
                match_salary=match_salary)
        else:
            match_percent = match_salary = 0
            update_user = m_session.query(model.User).filter_by(
                id=g.user.id).update({model.User.match_percent: match_percent,
                                      model.User.match_salary: match_salary})
            m_session.commit()
            return redirect("/input/risk_tolerance")
    else:
        return redirect("/login")
开发者ID:Iker-Jimenez,项目名称:inbestment,代码行数:30,代码来源:controller.py


示例8: view_categories

def view_categories():
	# get all categories of type "goods"
	goods = db_session.query(Category).filter_by(cat_type=1).all()
	#get all categories of type "services"
	services = db_session.query(Category).filter_by(cat_type=2).all()
	return render_template("view_categories.html",
							goods=goods, services=services)
开发者ID:jesslattif,项目名称:BarterApp,代码行数:7,代码来源:server.py


示例9: one_party

def one_party():
    parties = session.query(Party).limit(5).all()
    guests = session.query(Guest).limit(5).all()
    q = {'parties': [party.as_dict() for party in parties]}, \
        {'guests': [guest.as_dict() for guest in guests]}
    # print "------------------------\n", q, "\n------------------------"
    return q
开发者ID:mxcapo,项目名称:brainstorming,代码行数:7,代码来源:api.py


示例10: load_globalcounts

def load_globalcounts(list_of_wordcounts):
    """
    Adds wordcounts for all unique words. There should only be one row per unique word.
    """
    # i = 0

    for localcount_dict in list_of_wordcounts:
        # if i < 5:
        for word, count in localcount_dict.iteritems():
            item = session.query(GlobalCount).filter(GlobalCount.term == word).first()
            if item:
                print "%r is already in globalcounts. Updating count..." % word
                # update the global count for this word, because we have added new songs with more occurrences of this word
                q = session.query(LocalCount.term, func.sum(LocalCount.count))
                q = q.group_by(LocalCount.term)
                q = q.filter(LocalCount.term == word)
                results = q.all()

                # print "Current count for %r is %d" % (item.term, item.count)
                item.count = results[0][1]
                print "Updating %r's count to %d" % (item.term, item.count)
                session.commit()

            else:
                print "%r not in globalcounts table, creating new row" % word
                qq = session.query(LocalCount.term, func.sum(LocalCount.count))
                qq = qq.group_by(LocalCount.term)
                qq = qq.filter(LocalCount.term == word)
                resultsresults = qq.all()

                countcount = resultsresults[0][1]
                new_row = GlobalCount(term = word, count = countcount)
                session.add(new_row)
                # you must commit before you query the same word/item again!
                session.commit()
开发者ID:magshi,项目名称:golem,代码行数:35,代码来源:seed.py


示例11: add_page_pair_to_database

def add_page_pair_to_database(from_page, to_page, limit):

    with db_lock:
        cou = session.query(Page.id).filter(Page.url == from_page).scalar()
        cou1 = session.query(Page.id).filter(Page.url == to_page).scalar()

        if cou is None:
            new_page_from = Page(url=from_page, text="", rank=0)
            session.add(new_page_from)
            session.flush()
            id0 = new_page_from.id
        else:
            id0 = cou

        if cou1 is None:
            allowed = limit < 1 or limit > session.query(Page).count()
            if not allowed:
                return
            new_page_to = Page(url=to_page, text="", rank=0)
            session.add(new_page_to)
            session.flush()
            id1 = new_page_to.id
        else:
            id1 = cou1

        new_relation = Relation(page_id = id0, destination_id = id1)
        # print(new_relation.page_id.id)
        session.add(new_relation)
        session.commit()
开发者ID:bodya3d,项目名称:medojed,代码行数:29,代码来源:crawler.py


示例12: view_movie

def view_movie(id):
    #get is a function for a Query object
    movie = db_session.query(Movie).get(id)
    rating_objs = movie.ratings
    rating_values = []
    user_rating = None #user_rating will become user_rating object

    for r in rating_objs:
        if r.user_id == g.user_id:
            user_rating = r     
            # getting the whole rating object for the user's rating (will find out why later)
        rating_values.append(r.rating)

    # you want to make as few calls to the database as possible
    average_rating = float(sum(rating_values)/len(rating_values))

    # Prediction code: only predict if the user hasn't rated it.
    user = db_session.query(User).get(g.user_id)
    prediction = None
    if not user_rating:
        prediction = user.predict_rating(movie)
    # End prediction

    return render_template("movie.html", movie=movie, 
            average=average_rating, user_rating=user_rating,
            prediction=prediction)

    return render_template("movie.html", movie=movie, average=average_rating, user_rating=user_rating, prediction=prediction)
开发者ID:moonlimb,项目名称:ratings,代码行数:28,代码来源:critiquing.py


示例13: join_carpool

def join_carpool(trip, user):
    # Creates new TripPassenger object; returns appropriate message.

    carpool = db_session.query(model.Trip).filter_by(id=trip).first()
    driver = get_user_by_id(carpool.trip_driver)
    if user.id == carpool.trip_driver:
        return "You cannot join a carpool where you are the driver."

    if carpool.seats_available > 0:
        carpool_contact = driver.first_name + ", email: " + driver.email
        new_passenger = model.TripPassenger(trip_id=trip, passenger_id=user.id)
        seats_available = carpool.seats_available - 1
        db_session.query(model.Trip).filter_by(id=carpool.id).update({"seats_available": seats_available})
        db_session.add(new_passenger)
        db_session.commit()

        # Sends email to driver, confirming new passenger.
        message = (
            user.first_name
            + " "
            + user.last_name
            + " (email: "
            + user.email
            + ") has joined your carpool to "
            + carpool.event_name
            + " on "
            + carpool.departure_date
            + "."
        )
        send_email("inStep carpool addition", driver.email, "[email protected]", message)
        response = "You have been added to the carpool. The driver is " + carpool_contact
        return response
    else:
        return "That carpool is full."
开发者ID:jgrist,项目名称:dancefinder,代码行数:34,代码来源:controller.py


示例14: show_random_user_ratings

def show_random_user_ratings():
    """return a list of movies and ratings given by this user"""
    our_range = dbsesh.query(model.User.id).all()
    # print our_range

    clean_list =[]

    for i in range(len(our_range)):
        clean_list.append(our_range[i][0])

    # print clean_list

    users_to_show = []

    for i in range(10):
        random_user = random.choice(clean_list)
        users_to_show.append(random_user)

    user_objects = []
    for uid in users_to_show:
        user_object = dbsesh.query(model.User).get(uid)
        user_objects.append(user_object)

    print len(user_objects)
    return (user_objects)
开发者ID:k8k,项目名称:HBRatings,代码行数:25,代码来源:dbfx.py


示例15: movie_profile

def movie_profile():
	user = get_current_user()
	id = request.args.get("id")
	if not id:
		return redirect("/wall")

	movie_info = dbsession.query(Media).options(joinedload('genres')).get(id)
	if not movie_info:
		# movie wasn't found
		flash("This movie does not exist. Please try again.")
		return redirect("/wall")

	# FIXME: fix this workaround for utf-8 decoding weirdness in flask/jinja
	if movie_info.director:
		movie_info.director = movie_info.director.decode('utf-8', 'ignore')
	if movie_info.actors:
		movie_info.actors = movie_info.actors.decode('utf-8', 'ignore')
	if movie_info.plot:
		movie_info.plot = movie_info.plot.decode('utf-8', 'ignore')

	ratings = dbsession.query(Rating).filter(Rating.rating !=0).options(joinedload('user')).filter_by(movie_id = id).all()
	avg_rating = average_rating(ratings)

	# get rating of currently logged in user
	current_user_rating = None
	for rating in ratings:
		if rating.user == user:
			current_user_rating = rating
			break

	return render_template("movie_prof.html", movie=movie_info, ratings=ratings, avg_rating = avg_rating, user=user, current_user_rating = current_user_rating)
开发者ID:katereese,项目名称:Videodrome,代码行数:31,代码来源:flask_server.py


示例16: delete_item

def delete_item():
	user = db_session.query(User).get(g.user_id)
	item = db_session.query(Item).get(request.args.get("id"))
	db_session.delete(item)
	db_session.commit()
	flash("item deleted", "info")
	return redirect(url_for('manage_items'))
开发者ID:jesslattif,项目名称:BarterApp,代码行数:7,代码来源:server.py


示例17: show_existing_inputs

def show_existing_inputs():
    """
    This shows the user's current saved inputs and allows them
    to either move on or edit it.
    """
    if g.logged_in is True:
        if g.inputs is True:
            user_assets = m_session.query(model.UserBanking).filter_by(
                user_id=g.user.id).first()
            total_assets = user_assets.inputted_assets + \
                user_assets.checking_amt + user_assets.savings_amt + \
                user_assets.IRA_amt + user_assets.comp401k_amt + \
                user_assets.investment_amt
            risk_prof = m_session.query(model.RiskProfile).filter_by(
                id=g.user.risk_profile_id).first()
            return render_template(
                "profile_inputs.html",
                assets=utils.format_currency(total_assets),
                income=utils.format_currency(g.user.income),
                company_401k=g.user.company_401k,
                company_match=g.user.company_match,
                match_percent=utils.format_percentage(g.user.match_percent),
                match_salary=utils.format_percentage(g.user.match_salary),
                risk_profile=risk_prof.name)
        else:
            flash("Our financial data on you is incomplete. \
                    Please input now.")
            return redirect("/input/banking")
    else:
        return redirect("/login")
开发者ID:Iker-Jimenez,项目名称:inbestment,代码行数:30,代码来源:controller.py


示例18: input_match_401k

def input_match_401k():
    """
    This allows the user to enter and edit if their company has a 401k
    match.
    """
    if g.logged_in is True:
        # If user selects that they do not have a company 401k, skip
        # all 401k-related questions.
        comp_401k = m_session.query(model.User).filter_by(
            id=g.user.id).first().company_401k
        if comp_401k == "Yes":
            if g.inputs is True:
                match_401k = m_session.query(model.User).filter_by(
                    id=g.user.id).first().company_match
            else:
                match_401k = 0
            return render_template(
                "input_match_401k.html", match_401k=match_401k)
        else:
            match_401k = "No"
            match_percent = match_salary = 0
            update_user = m_session.query(model.User).filter_by(
                id=g.user.id).update({model.User.company_match: match_401k,
                                      model.User.match_percent: match_percent,
                                      model.User.match_salary: match_salary})
            m_session.commit()
            return redirect("/input/risk_tolerance")
    else:
        return redirect("/login")
开发者ID:Iker-Jimenez,项目名称:inbestment,代码行数:29,代码来源:controller.py


示例19: save_assets

def save_assets():
    """
    Pulls assets from user input (as a post request), save to
    database, and routes to next question (/results will perform
    the calculations).
    """
    form = AssetsForm(request.form)
    if form.validate_on_submit():
        assets = float(request.form["assets"])

        # Checks that user's assets are getting updated each time they change
        # their input, and not getting added to the database.
        user_assets = m_session.query(model.UserBanking).filter_by(
            user_id=g.user.id).first()
        if user_assets is not None:
            update_assets = m_session.query(model.UserBanking).filter_by(
                user_id=g.user.id).update(
                {model.UserBanking.inputted_assets: assets})
        else:
            new_account = model.UserBanking(
                user_id=g.user.id, inputted_assets=assets, checking_amt=0,
                savings_amt=0, IRA_amt=0, comp401k_amt=0, investment_amt=0)
            m_session.add(new_account)
        m_session.commit()
        return redirect("/input/income")
    else:
        flash("Please enter an integer. No commas or symbols.")
        return redirect("/input/assets")
开发者ID:Iker-Jimenez,项目名称:inbestment,代码行数:28,代码来源:controller.py


示例20: calc_percent_change_all

def calc_percent_change_all(ticker_list, session):
    """
    This function calculates the percent change since 4/10/2007 for all
    loaded tickers and saves that value to the new_change column in the
    database.

    All values are being benchmarked against 4/10/2007, which is the latest
    inception date for all of the funds for apples-to-apples since-inception
    comparison.
    """
    ticker_id = 0

    for ticker_data in range(len(ticker_list)):
        ticker_id = ticker_id + 1
        ticker = m_session.query(model.Price).filter_by(
                    ticker_id=ticker_id).all()

        old_close_price = float(m_session.query(model.Price).filter_by(
                    date="2007-04-10",
                    ticker_id=ticker_id).first().close_price)
        new_index = 0

        for daily_ticker_price in ticker:
            new_close_price = float(ticker[new_index].close_price)
            difference = round((new_close_price - old_close_price) /
                               old_close_price, 4)
            ticker[new_index].percent_change = difference
            new_index = new_index + 1
    session.commit()
开发者ID:Iker-Jimenez,项目名称:inbestment,代码行数:29,代码来源:seed.py



注:本文中的model.session.query函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python testfile.TestFile类代码示例发布时间:2022-05-27
下一篇:
Python session.commit函数代码示例发布时间:2022-05-27
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap