| | 606 | |
| | 607 | |
| | 608 | == fox's method == |
| | 609 | First write a config file with passwords ad secret keys. Save it somewhere. |
| | 610 | This is the external_config.py |
| | 611 | {{{ |
| | 612 | #!python |
| | 613 | from ConfigParser import ConfigParser, NoOptionError |
| | 614 | |
| | 615 | class ExternalConfig(object): |
| | 616 | """ |
| | 617 | Wrapper for ConfigParser |
| | 618 | Reads a section from a config file and provides an object with the |
| | 619 | properties and the values defined in the config. |
| | 620 | """ |
| | 621 | def __init__(self, conf_file, section): |
| | 622 | """ |
| | 623 | Reads the section "section" from the config "conf_file" |
| | 624 | """ |
| | 625 | self._conf_file = conf_file |
| | 626 | self._section = section |
| | 627 | |
| | 628 | self._config = ConfigParser() |
| | 629 | self._config.read(self._conf_file) |
| | 630 | |
| | 631 | self._index = len(self._config.options(self._section)) |
| | 632 | |
| | 633 | def __getattr__(self, name): |
| | 634 | """ |
| | 635 | Read the property from the config |
| | 636 | """ |
| | 637 | if name.startswith('_'): |
| | 638 | return self.__dict__[name] |
| | 639 | try: |
| | 640 | value = self._config.get(self._section, name) |
| | 641 | if value.isdigit(): |
| | 642 | return int(value) |
| | 643 | elif value in ('True', 'False'): |
| | 644 | return value == 'True' |
| | 645 | else: |
| | 646 | return value |
| | 647 | except NoOptionError: |
| | 648 | raise AttributeError |
| | 649 | |
| | 650 | def __getitem__(self, name): |
| | 651 | """ |
| | 652 | Read the property from the config |
| | 653 | """ |
| | 654 | return self.__getattr__(name) |
| | 655 | |
| | 656 | def __iter__(self): |
| | 657 | """ |
| | 658 | __iter__ method |
| | 659 | """ |
| | 660 | return self |
| | 661 | |
| | 662 | def next(self): |
| | 663 | """ |
| | 664 | next method |
| | 665 | """ |
| | 666 | if self._index == 0: |
| | 667 | raise StopIteration |
| | 668 | self._index -= 1 |
| | 669 | return self._config.options(self._section)[self._index] |
| | 670 | }}} |
| | 671 | |
| | 672 | This is production_settings.py |
| | 673 | {{{ |
| | 674 | #!python |
| | 675 | from external_config import ExternalConfig |
| | 676 | import sys |
| | 677 | |
| | 678 | _filename = "" # add your config file |
| | 679 | _section = "mysection" # add your config section |
| | 680 | _this_module = sys.modules[__name__] |
| | 681 | _config = ExternalConfig(_filename, _section) |
| | 682 | |
| | 683 | __all__ = [] |
| | 684 | |
| | 685 | for key in _config: |
| | 686 | __all__.append(key) |
| | 687 | value = _config[key] |
| | 688 | setattr(_this_module, key, value) |
| | 689 | |
| | 690 | }}} |
| | 691 | |
| | 692 | Now importig * from production_settings.py will import data from the config file |