python - how to use multiple optional arguements in find() pymong -


i want create function makes use of pymongos find function,but user parameter.

class servicelog(document):     # session_id = sessionstart.pk     creation_date = datetimefield(required=true)     log_level = stringfield(required=true)     tag = stringfield(required=true)     message = stringfield(required=true)     db.service_log.ensure_index(u'log_level', 1)     db.service_log.ensure_index(u'tag', 1)       def log(self, loglevel, tag, message, sid):         logging.basicconfig(level=logging.debug)         time = asctime()         servicelog(creation_date=time,                    log_level=loglevel,                    tag=tag,                    message=message,                    session_id=sid).save()      def listlog(self, loglevel, tag, message, sid, lim_num, sk_num):         db.log.find(creation_date=time,                     log_level=loglevel,                     tag=tag,                     message=message,                     session_id=sid).skip(sk_num).limit(lim_num) 

how can change listlog user can input number of parameters match?

you use **kwargs, little tweaking.

for example:

def listlog(self, sk_num=0, lim_num=0, **kwargs):     db.log.find(kwargs).skip(sk_num).limit(lim_num) 

this code following:

  1. defines method 2 optional parameters have default values: sk_num , lim_num.

  2. the **kwargs shorthand "take many keyword arguments want, , place them dict called kwargs". read on this.

  3. it using kwargs dict search query in mongodb's find(). means values of arguments passed function must safe , valid mongo query options.

you have change names of parameters match names of mongodb document entries. rather naming method param loglevel, you'd name log_level match collection.


Comments

Popular posts from this blog

java.util.scanner - How to read and add only numbers to array from a text file -

rewrite - Trouble with Wordpress multiple custom querystrings -