I must provide database for my program that utilizes elixir for ORM. At this time the database file (I'm using SQLite) should be hardcoded in metadata, but I must have the ability to pass this in argv. Can there be any method of doing this nice?
The only real factor I figured of would be to:
from sys import argv metadata.bind = argv
Can One set this within the primary script and it might be used in most modules, that comprise any Organizations?
I've some code that performs this inside a slightly better fashion than simply 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
Observe that the part using opt_hash is a little of the hack. I personally use it because OptionParser does not return an ordinary hash, that is what's really required for the niceness from the bind string I personally use within the last line.
Your question appears to become more associated with general argument parsing in python compared to elixir.
Anyway, I'd an identical problem, and that i have solved it by utilizing different configuration files and parsing all of them with the configparse module in python.
For instance, I've two config files, and all of them describes the db url, username, password, etc.. of 1 database. When I wish to change to another configuration, I pass a choice like --configfile guest towards the script (I personally use argparse for that command line interface), then your script searches for a config file known as guest.txt, and reads all the details there.
This can be a lot safer, if you pass a metadata string like a command line argument you could have some security issues, and furthermore it's a lot longer to type.
Incidentally, there are also helpful to create a Makefile to keep the most typical 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
as well as on the command line, you just type 'make debug_db' or 'make connect_db1' to carry out a rule.