global object access across the session in web2py?
I'm new to webdev, these days plan for writing a boradgame with web2py.
When start to coding, I found that I can't use global variables easily.
for demo purpose, I want a python list object access by many players, I use sqlite to make it work.
the database, (using DAL('sqlite:memory:')
won't work), so I try the file way, it works as my thought:
memdb = DAL('sqlite://storage.sqlite')
memdb.define_table('room', Field('card_on_desk', 'blob'))
create a room:
roomid = memdb.room.insert(card_on_desk=pickle.dumps(list()))
memdb.commit()
change the room's card_on_desk field:
record = memdb.room(roomid)
cards = pickle.loads(record.card_on_desk)
cards.append(','.join(c))
memdb(memdb.room.id==roomid).update(card_on_desk=pickle.dumps(cards))
memdb.commit()
Some gurus said there is a cache.ram() way, 开发者_如何学PythonI want to know how to do the above stuff.
wait for your answers.
S.Lott mention that I did not describe what happens when using DAL('sqlite:memory:'):
using sqlite:memory
instead of 'sqlite://storage.sqlite', the memdb insert is alright in a http request, but nothing saves, everytime you I call memdb.room.insert()
returns the times I called and when the request is finish, nothing saved in memory, memdb.room(1) always return None.
Anthony's advice is more useful, I'll try to use that way, bit hard to do so.
If you do not need to persist the information, then you can use the session
session.myvariable
if you need to persist and you want to speed up things with cache, then you can cache the select:
def cache_db_select():
logs = db().select(db.log.ALL, cache=(cache.ram, 60))
return dict(logs=logs)
精彩评论