简体   繁体   中英

How to pass in custom properties to an ancestor query using Google App Engine with Python without using eval?

I was wondering if anyone could help me out here.

I have this bit of code here, which is retrieving a specified sort option (name/author) and (asc/desc) from my HTML page:

    orderby = self.request.get('orderby',
                               DEFAULT_ORDER_BY)
    arrange = self.request.get('arrange',
                               DEFAULT_ARRANGE)

It then converts it into either a "-" for descending, or "" for ascending:

    if arrange == "desc":
        arrange = "-"
    else:
        arrange = ""

Then I create a string to pass in as a property to my query:

    query_order = arrange + "Game." + orderby

Then I execute my query:

    games_query = Game.query(ancestor=game_key(game_name)).order(eval(query_order))
    games = games_query.fetch(10)

Only problem is, I'm using eval in order to get it to work. I've heard a lot of bad things about it, but can't seem to find another way around it.

Passing it in without eval generates this error:

TypeError: order() expects a Property or query Order; received '-Game.date'

Apologies as I am a bit new to the language, and to programming in general. Any help would be greatly appreciated.

You can use 'getattr' to get the attribute to order by:

reverse = False
if order.startswith('-'):
    reverse = True
    order = order[1:]
if reverse:
    games_query = games_query.order(-getattr(Game, order))
else:
    games_query = games_query.order(getattr(Game, order))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM