如何编写一个支持多个数据库的python应用程序 [英] How to write a python application that support multiple databases

查看:462
本文介绍了如何编写一个支持多个数据库的python应用程序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用python(2.7),django,用mongodb.I想创建一个支持多个数据库(monogdb,oracle,Mysql等)的应用程序。如果我们选择oracle在前端数据应该保存

I am using python(2.7),django,with mongodb.I want to create an application that support multiple databases(monogdb,oracle,Mysql,etc).Means if we select oracle on the front end the data should be save in oracle like that.Is there any way to write that app.

推荐答案

Django支持多个数据库,所以你需要的是一些代码来处理它们之间的切换。

Django supports multiple databases so all you need is some code to handle switching between them.

如果你已经阅读了文档,你会看到Django允许你提供自己的自定义router类,决定用于任何给定查询的数据库:

< a href =https://docs.djangoproject.com/en/1.6/topics/db/multi-db/#using-routers =nofollow> https://docs.djangoproject.com/en/1.6 / topics / db / multi-db /#using-routers

If you have read the docs you will see that Django allows you to supply your own custom 'router' class which decides which database to use for any given query:
https://docs.djangoproject.com/en/1.6/topics/db/multi-db/#using-routers

因为你说你想选择哪个db前端您网站的用户可以选择不同的数据库后端。这提出了一个问题,因为db路由器不知道当前http请求和用户。

Since you say you want to select which db "on the front end" then presumably each user of your site could choose a different database backend. This presents a problem because the db router knows nothing about the current http request and user.

我建议你使用这个ThreadLocal中间件来存储当前请求对象,所以你可以通过您的自定义路由器访问它:

https://github.com/jedie/django-tools/blob/master/django_tools/middlewares/ThreadLocal.py

I suggest you use this 'ThreadLocal' middleware to store the current request object so you can access it from your custom router:
https://github.com/jedie/django-tools/blob/master/django_tools/middlewares/ThreadLocal.py

假设您储存用户选择的后端会话 request.session ['db_name'] - 您的路由器将如下所示:

Let's say you save the user's chosen backend in the session as request.session['db_name'] - your router would look something like this:

from django_tools.middlewares import ThreadLocal

class RequestRouter(object):
    def db_for_read(self, model, **hints):
        request = ThreadLocal.get_current_request()
        return request.session.get('db_name', 'default')

    def db_for_write(self, model, **hints):
        request = ThreadLocal.get_current_request()
        return request.session.get('db_name', 'default')

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

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

这篇关于如何编写一个支持多个数据库的python应用程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆