Get the App
SLTechnology News&Howtos  ›  Database  › 

How to use MongoDB to implement session Storage of web.py

Shulou Source: shulou.com Published: 2022-05-31 17:45:24 09月15日 Update

This article will explain in detail how to use MongoDB to achieve session storage in web.py. The editor thinks it is very practical, so I share it with you as a reference. I hope you can get something after reading this article.

Web.py is a python web development framework, since it involves web development, then it is inevitable to use session, while the traditional session storage is basically the default on disk, of course, considering the expansion of web front-end computers, we often need to rewrite sessionhandler to customize session storage.

Fromweb.sessionimportStore

Importtime

ClassMongoStore (Store):

Def__init__ (self,db,collection_name):

Self.collection= db[collection _ name]

Def__contains__ (self,key):

Data=self.collection.find_one ({'session_id':key})

Returnbool (data)

Def__getitem__ (self,key):

Now=time.time ()

S=self.collection.find_one ({'session_id':key})

Ifnots:

RaiseKeyError

Else:

S.update ({'attime':now})

Returns

Def__setitem__ (self,key,value):

Now=time.time ()

Value ['attime'] = now

S=self.collection.find_one ({'session_id':key})

How to use MongoDB to implement session Storage of web.py

Ifs:

Value=dict (map (lambdax: (str (x [0]), x [1]), [(kMagnev) for (kmagin v) invalue.iteritems () ifknotin ['_ id']])

S.update (* * value)

Self.collection.save (s)

Else:

Self.collection.insert (value)

Def__delitem__ (self,key):

Self.collection.remove ({'session_id':key})

Defcleanup (self,timeout):

Timeout=timeout/ (24.0 / 60 / 60) # timedeltatakesnumdaysasarg

Last_allowed_time=time.time ()-timeout

Self.collection.remove ({'attime': {' $lt':last_allowed_time}})

Then replace the declaration of using disk for storage in app, using the

Session=web.session.Session (app,MongoStore (db,'sessions'))

Replace:

Session=web.session.Session (app,web.session.DiskStore ('sessions')).

This is the end of this article on "how to use MongoDB to achieve session storage in web.py". I hope the above content can be of some help to you, so that you can learn more knowledge. if you think the article is good, please share it out for more people to see.

Tags: Storage articles more disk Development good practical inevitable traditional content Front end articles Framework knowledge reference help related Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Shulou Technology macOS vpn OPPO Reno MySQL