开发者

Using multiple databases with Elixir

I would like to provide database for my program that uses elixir for ORM. Right now the database file (I am using SQLite) must be hardc开发者_开发技巧oded in metadata, but I would like to be able to pass this in argv. Is there any way to do this nice?

The only thing I thought of is to:

from sys import argv

metadata.bind = argv[1]

Can I set this in the main script and it would be used in all modules, that define any Entities?


I have some code that does this in a slightly nicer fashion than just using argv

from optparse import OptionParser

parser = OptionParser()
parser.add_option("-u", "--user", dest="user",
                  help="Database username")
parser.add_option("-p", "--password", dest="password",
                  help="Database password")
parser.add_option("-D", "--database", dest="database", default="myDatabase",
                  help="Database name")
parser.add_option("-e", "--engine", dest="engine", default="mysql",
                  help="Database engine")
parser.add_option("-H", "--host", dest="host", default="localhost",
                  help="Database host")

(options, args) = parser.parse_args()

def opt_hash(name):
    global options
    return getattr(options, name)

options.__getitem__ = opt_hash

metadata.bind = '%(engine)s://%(user)s:%(password)s@%(host)s/%(database)s' % options

Note that the part using opt_hash is a bit of a hack. I use it because OptionParser doesn't return a normal hash, which is what is really needed for the niceness of the bind string I use in the last line.


Your question seems to be more related to general argument parsing in python than with elixir.

Anyway, I had a similar problem, and I have solved it by using different configuration files and parsing them with the configparse module in python.

For example, I have two config files, and each of them describes the db url, username, password, etc.. of one database. When I want to switch to another configuration, I pass an option like --configfile guest to the script (I use argparse for the command line interface), then the script looks for a config file called guest.txt, and reads all the information there.

This is a lot safer, because if you pass a metadata string as a command line argument you can have some security issues, and moreover it is a lot longer to type.

By the way, you can also find useful to write a Makefile to store the most common options.

e.g. cat >Makefile

debug_db:
    ipython connect_db.py -config guest -i

connect_root:
    ipython connect_db.py -config db1_root -i

connect_db1: 
    ipython connect_db.py -config db1 -i

and on the command line, you only have to type 'make debug_db' or 'make connect_db1' to execute a rule.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜