在routeDataBase Django中使用request.cookies

时间:2014-07-09 19:05:51

标签: python django

是否可以在Django的路由数据库中使用cookie,还是有其他方式?

middlewares.py

class DefinedRouteDataBase(object):

    def process_request(self, request):
        if request.method == 'POST':
            request.COOKIES['token'] = request.POST['token']
            print ('Middlewares:', str(request.COOKIES['token']))
        return None

RouterDataBases.py

class DatabaseAppsRouter(object):

def db_for_read(self, model, **hints):
    print('Router R:')
    #HERE FAIL :(
    return request.COOKIES['token']

def db_for_write(self, model, **hints):
     print ('Router W:')
     return 'default'

def allow_relation(self, obj1, obj2, **hints):
    return None

def allow_syncdb(self, db, model):
    return True

1 个答案:

答案 0 :(得分:0)

根本不可能。数据库路由器无法访问请求(他们不接收此类数据)。

我能想到的唯一(和丑陋)解决方案是使用threading.local,您可以在中间件(DefinedRouteDataBase)中初始化:

#in mymoduleforthisuglysolution.py
from threading import local

mylocal = local()

#in your middleware definition file
from mymoduleforthisuglysolution import mylocal

class DefinedRouteDataBase(object):

    def process_request(self, request):
        #if request.method == 'POST':
        #    request.COOKIES['token'] = request.POST['token']
        #    print ('Middlewares:', str(request.COOKIES['token']))
        mylocal.request = request
        return None

#in your router definition file
from mymoduleforthisuglysolution import mylocal

class DatabaseAppsRouter(object):

    def db_for_read(self, model, **hints):
        print('Router R:')
        return mylocal.request.COOKIES['token'] if mylocal.request else 'default'

    def db_for_write(self, model, **hints):
        print ('Router W:')
        return 'default'

    def allow_relation(self, obj1, obj2, **hints):
        return None

    def allow_syncdb(self, db, model):
        return True

这个解决方案很难看,如果你使用GEvent就行不通(因为每个请求都在greenlet而不是单独的线程中),但这是我能想到的唯一解决方案,因为没有连接路径路由器和请求之间。

一个问题:为什么要将数据库密钥存储在cookie中?这将是危险的危险xD。