def __init__(self): resources.init('BuddyUp', 'dewey') brain_pickle = resources.user.read('config.py') if brain_pickle: self.brain = pickle.load(brain_pickle) else: self.brain = Brain()
def from_db(): db = args.grouped['--db'][0] output = args.grouped['--out'][0] out = SqliteOutput(output) if db == 'mssql': import pymssql as db resources.init('baancomplete', 'baancomplete') if args.grouped.has_key('--use-config'): host = resources.user.read('host') user = resources.user.read('user') database = resources.user.read('database') else: host = raw_input('sql server: ') user = raw_input('username: '******'database name: ') resources.user.write('host', host) resources.user.write('user', user) resources.user.write('database', database) password = getpass() conn = db.connect(host=host, user=user, password=password, database=database, as_dict=True) read_write_tablefields(conn, out) out.close()
def redpill(args): resources.init(VENDOR, PACKAGE) config = load_config() if args['-S']: if not ( args['<package>'] or args['--refresh'] or args['--sysupgrade'] ): puts(colored.red('No packages to sync, exiting...')) sys.exit(1) if args['--refresh']: refresh() if args['--sysupgrade']: sysupgrade() if args['<package>']: install(args['<package>']) elif args['--subscribe']: subscribe(config, args['<repository>']) save_config(config)
def load_or_create_user(username): resources.init('Kickflip', 'Kickflip') config_json = resources.user.read('config.json') if not config_json: resources.user.write('config.json', json.dumps({}, sort_keys=True)) config_json = resources.user.read('config.json') settings = json.loads(config_json) if not settings.has_key('username'): settings['username'] = username resources.user.write('config.json', json.dumps(settings, sort_keys=True)) if not settings.has_key('user_access_key'): user = kickflip.create_user(username) settings['username'] = user['name'] settings['user_access_key'] = user['aws_access_key'] settings['user_secret_access_key'] = user['aws_secret_key'] settings['user_uuid'] = user['uuid'] resources.user.write('config.json', json.dumps(settings, sort_keys=True)) kickflip.set_aws_keys(settings['username'], settings['user_access_key'], settings['user_secret_access_key']) kickflip.set_uuid(settings['user_uuid']) return settings['username'], settings['user_uuid'], settings[ 'user_access_key'], settings['user_secret_access_key']
def __init__(self, name, description, command_info, version, default_action=None, dynamic_action=None, store=None): self.name = name self.description = description self.command_info = command_info self.version = version self.store = store resources.init(__author__, self.name) if self.store: # path = os.path.expanduser('~/.'+self.name) # if XDG_DATA_HOME: path = os.path.join(XDG_DATA_HOME, self.name, self.name) path = resources.user.read('path.ini') or path path_dir = os.path.dirname(path) if not os.path.exists(path_dir): os.makedirs(path_dir) # TODO: make this more general self.store.setPath(path) self.store.bootstrap() self.default_action = default_action or self.display_info self.dynamic_action = dynamic_action or self.display_info define_command(name='help', short='h', fn=self.cmd_help, usage='help <command>', help='Display help for a command.')
def read_config(): resources.init("Microsoft", "Dukaan") contents = resources.user.read('config.ini') if contents: d = json.loads(contents) for k in d: config[k] = d[k] else: Printer.info("Configuration is empty. Run 'dukaan init' to save common settings to configuration file.")
def __init__(self): resources.init('yenbekbay', 'mudl') self.config = ConfigParser() if not os.path.exists(resources.user.path): os.makedirs(resources.user.path) self.config_path = os.path.join(resources.user.path, 'config.ini') self.config.read(self.config_path) if not self.config.has_section('general'): self.config.add_section('general') self.iterator = 0
def _get_config(self, in_do_config=False): ''' Reads the configuration ''' resources.init('obmarg', 'synchg') self.config = ConfigParser() contents = resources.user.read(self.ConfigFileName) if not contents: if not in_do_config: print "Could not find config file" self.do_config() else: self.config.readfp(resources.user.open(self.ConfigFileName))
def genopts(parser): fn = 'config.yaml' resources.init('kubecharm', 'kfc') rpath = path(resources.user.path) / fn if not rpath.exists(): resources.user.write(fn, '---\njenkins: {}\n') parser.add_argument( '--config', default=yaml_load(rpath), help='The configuration file to use for the kfc commands.', type=yaml_load )
def __init__(self): resources.init('sidebar', 'dewey') brain_pickle = resources.user.read('sidebar_config.ini') if brain_pickle: self.brain = pickle.loads(brain_pickle) else: self.brain = Brain() # Check for dewey.yml. if os.path.isfile("dewey.yml"): self.local = yaml.load(open("dewey.yml")) else: self.local = None
def main(*args) -> None: resources.init('jacklaxson', 'austere') j = resources.user.read("config.json") light_browser = json.loads(j)['light_browser'] use_light = False # check for steam games running overlay = [x for x in psutil.process_iter() if "gameoverlayui" in x.name()] if len(overlay) > 0: # all of the gameoverlayui's have the pid game_pid = int(overlay[0].cmdline()[2]) logger.info("Detected game %s", psutil.Process(pid=game_pid).name()) use_light = True # check for big picture games # they're direct descendants of steam elif len(overlay) == 0: for proc in psutil.process_iter(): if proc.name() == "steam": z = list(filter(lambda x: x.name() not in ['steamwebhelper','steam','sh', 'SteamChildMonit'], proc.children(recursive=True))) if len(z) == 1: logger.info("Detected game %s", z[0]) use_light = True elif len(z) == 0: logger.info("Found no games running in big picture mode") else: logger.error("Found more than one potential game process, this behavior is undefined") logger.info(z) elif proc.name() == 'Battle.net.exe': z = list(filter(lambda x: x.name() not in ['Battle.net Helper.exe', 'CrashMailer_64.exe'], proc.children(recursive=True))) if len(z) == 1: logger.info("Detected game %s", z[0]) use_light = True else: logger.info(z) logger.info("battlenet children: %s", proc.children(recursive=True)) # check if we're almost out of memory elif psutil.virtual_memory().percent > 90: use_light = True # check battery info if use_light: if platform.system() == "Windows": pass else: subprocess.call([light_browser, sys.argv[1]]) else: if platform.system() == "Windows": subprocess.call(['powershell.exe', '-Command', 'start {}'.format(sys.argv[1])]) else: subprocess.call(['x-www-browser', sys.argv[1]]) logger.debug(args)
def get_or_create_dotfile(): resources.init("George Erickson", "fetchr") config = resources.user.read("config.yaml") if not config: config = pkgutil.get_data("fetchr", "data/config.yaml") print config resources.user.write("config.yaml", config) try: return yaml.load(config) except yaml.parser.ParserError as e: puts(colored.red("Misconfigured config file, check %s" % config_path)) with indent(4): puts(str(e)) sys.exit(1)
def genopts(parser): resources.init('cf-charmers', 'raindance') parser.add_argument('-p', '--releasepath', action='store', help="path to cf-release", type=path, default=path('.').abspath() / 'cf-release') parser.add_argument('-i', '--index', action='store', help="URL of compiled package index", default=s3_url(default_bucket)) #@@ calculated latest release parser.add_argument('-n', '--release-number', action='store', default='180', help="Release number")
def config() -> None: resources.init('jacklaxson', 'austere') j = resources.user.read("config.json") if j == None: path = pick_browser() else: light_browser = json.loads(j)['light_browser'] print("Your default lightweight browser is: %s" % light_browser) z = prompt.query( 'Change your lightweight browser? [y/n]', validators=[validators.OptionValidator(["y", "n"])]).lower() if z == "y": path = pick_browser() else: path = light_browser d = {"light_browser": path} resources.user.write('config.json', json.dumps(d))
def main(): # First parameter is 'company' name, hence duplicate arguments resources.init('sshmenu', 'sshmenu') # For the first run, create an example config if resources.user.read('config.json') is None: example_config = { 'targets': [ { 'host': '*****@*****.**', 'friendly': 'This is an example target' } ] } resources.user.write('config.json', json.dumps(example_config)) puts('I have created a new configuration file, please edit and run again:') puts(resources.user.path + '/config.json') else: config = json.loads(resources.user.read('config.json')) display_menu(config['targets'])
def create_config(): def IsNotEmpty(s): return s != "" resources.init("Microsoft", "Dukaan") resource_provider_namespace = utility.get_input("Resource Provider namespace [e.g. contoso]: ", IsNotEmpty) resource_type = utility.get_input("Resource Type [e.g. monitoring]: ", IsNotEmpty) subscription_id = utility.get_input("Subscription ID [e.g. my_subscription]: ", IsNotEmpty) resource_name = utility.get_input("Resource Name [e.g. my_resource]: ", IsNotEmpty) purchase_plan = utility.get_input("Base Plan Name [e.g. free]: ", IsNotEmpty) upgrade_plan = utility.get_input("Upgrade Plan Name [e.g. gold]: ", IsNotEmpty) config['resource_provider_namespace'] = resource_provider_namespace config['resource_type'] = resource_type config['subscription_id'] = subscription_id config['resource_name'] = resource_name config['purchase_plan'] = purchase_plan config['upgrade_plan'] = upgrade_plan resources.user.write('config.ini', json.dumps(config))
def main(): # First parameter is 'company' name, hence duplicate arguments resources.init('sshmenu', 'sshmenu') # For the first run, create an example config if resources.user.read('config.json') is None: example_config = { 'targets': [{ 'host': '*****@*****.**', 'friendly': 'This is an example target' }] } resources.user.write('config.json', json.dumps(example_config)) puts( 'I have created a new configuration file, please edit and run again:' ) puts(resources.user.path + '/config.json') else: config = json.loads(resources.user.read('config.json')) display_menu(config['targets'])
def load_keys(read_cli=False): resources.init('Kickflip', 'Kickflip') config_json = resources.user.read('config.json') if not config_json: resources.user.write('config.json', json.dumps({}, sort_keys=True)) config_json = resources.user.read('config.json') settings = json.loads(config_json) # Nuke the settings if reading from CLI. if read_cli: settings = {} if not settings.has_key('client_id') or read_cli: settings['client_id'] = raw_input("What is your client ID? ").strip() resources.user.write('config.json', json.dumps(settings, sort_keys=True)) if not settings.has_key('client_secret') or read_cli: settings['client_secret'] = raw_input("What is your client secret? ") resources.user.write('config.json', json.dumps(settings, sort_keys=True)) return settings['client_id'], settings['client_secret']
def main(*argv): resources.init("Praxa", getenv('INSTANCE_NAME', "Praxa")) if not isdir(resources.user.path): makedirs(resources.user.path) arguments = list(argv) if not arguments: from sys import argv arguments = argv[1:] parser = ArghParser() parser.add_help = True parser.add_commands([dump, load], namespace="env", title="Environment Manipulation") parser.add_commands([vexec]) # the default if len(arguments): if arguments[0] not in ('env', 'dump', 'load', 'exec'): arguments.insert(0, 'exec') parser.dispatch(argv=arguments) return 0
def main(): global config_name # Check arguments parser = argparse.ArgumentParser( prog='sshmenu', description='A convenient tool for bookmarking ' 'hosts and connecting to them via ssh.') parser.add_argument('-c', '--configname', default='config', help='Specify an alternate configuration name.') args = parser.parse_args() # Get config name config_name = '{configname}'.format(configname=args.configname) # First parameter is 'company' name, hence duplicate arguments resources.init('sshmenu', 'sshmenu') # If the config file doesn't exist, create an example config if resources.user.read(config_name) == None: example_config = { 'targets': [{ 'host': '*****@*****.**', 'friendly': 'This is an example target', 'options': [] }, { 'command': 'mosh', 'host': '*****@*****.**', 'friendly': 'This is an example target using mosh', 'options': [] }] } resources.user.write(config_name, json.dumps(example_config, indent=4)) update_targets() display_menu()
def load_or_create_user(username): resources.init('Kickflip', 'Kickflip') config_json = resources.user.read('config.json') if not config_json: resources.user.write('config.json', json.dumps({}, sort_keys=True)) config_json = resources.user.read('config.json') settings = json.loads(config_json) if not settings.has_key('username'): settings['username'] = username resources.user.write('config.json', json.dumps(settings, sort_keys=True)) if not settings.has_key('user_access_key'): user = kickflip.create_user(username) settings['username'] = user['name'] settings['user_access_key'] = user['aws_access_key'] settings['user_secret_access_key'] = user['aws_secret_key'] settings['user_uuid'] = user['uuid'] resources.user.write('config.json', json.dumps(settings, sort_keys=True)) kickflip.set_aws_keys(settings['username'], settings['user_access_key'], settings['user_secret_access_key']) kickflip.set_uuid(settings['user_uuid']) return settings['username'], settings['user_uuid'], settings['user_access_key'], settings['user_secret_access_key']
# -*- coding: utf-8 -*- import csv from clint import resources from utils import oauth_login, base_url, bank_id, account_id resources.init('openbankproject', 'evmakesgeo') key_file = resources.user.read('config.ini') openbank = oauth_login(base_url, key_file) # Parse cords from csv reader = csv.reader(open('static/ireland_points.csv')) firstline = True csv_data = [] for row in reader: if firstline: #skip first line firstline = False continue csv_data.append((row[0], row[1])) # Get transactoin ids response = openbank.get( "{}obp/v1.2.1/banks/{}/accounts/{}/owner/transactions".format( base_url, bank_id, account_id)) transactions = [each['id'] for each in response.json()['transactions']][0:len(csv_data)] # Create for a list of transactions id geo metadata for index, transaction in enumerate(transactions):
'api_url': 'https://api.github.com', 'screen_width': t.winfo_screenwidth(), 'screen_height': t.winfo_screenheight(), 'repo_store': os.path.abspath('%s/repositories' % CURRENT_DIR), 'gource_options': ['gource', '--load-config', os.path.abspath('%s/config/gourceconfig.ini' % CURRENT_DIR)], 'git_log_options': ['git', 'log', '--pretty=format:user:%aN%n%ct', '--reverse', '--raw', '--encoding=UTF-8', '--no-renames'], 'sound_file': os.path.abspath('%s/audio/happykids.wav' % CURRENT_DIR) } DEFAULTS.update({ 'max_gources': DEFAULTS.get('rows') * DEFAULTS.get('columns') }) OPTS = dict() resources.init('ff0000', 'Battlestar Goursica') class RepoGoneError(Exception): pass def debugger(msg): if logging.getLogger().getEffectiveLevel() == logging.DEBUG: try: puts(msg) except UnicodeDecodeError, e: debugger(colored.red('%s' % e)) def initial_xmonad_layout():
import click_log import os import sys import configparser import ipaddress import pynetbox import json import logging from tools.arin.payloads import CustomerPayload, NetPayload, NetBlockPayload, TicketedRequestPayload from tools.arin import Arin from tools.googlemaps import GeocodeResult from tools.googlemaps.googlemaps import GeocodeResultError logger = logging.getLogger(__name__) click_log.basic_config(logger) resources.init('connectit', 'netbox-cli') config = configparser.ConfigParser() def write_config(): try: with resources.user.open('config.ini', mode='w') as configFile: config.write(configFile) except IOError: pass class ContextObject: def __init__(self, ctx): self.ctx = ctx self.secret = None
from clint import resources import json resources.init('thomasballinger', 'trello-card-updater') #being used as though they have in-memory caches class LocalStorage(object): def __init__(self, name): object.__setattr__(self, 'res', getattr(resources, name)) def __getattr__(self, att): s = self.res.read(att) if s is None: return None data = json.loads(s) return data def __setattr__(self, att, data): s = json.dumps(data) self.res.write(att, s) def __getitem__(self, key): return getattr(self, key) def __setitem__(self, key, value): setattr(self, key, value) class LocalObfuscatedStorage(LocalStorage): """Of questionable use, but should avoid indexing""" def __getattr__(self, att): s = self.res.read(att) if s is None: return None data = json.loads(s.encode('rot13')) return data
from clint import resources import json resources.init('thomasballinger', 'trello-card-updater') #being used as though they have in-memory caches class LocalStorage(object): def __init__(self, name): object.__setattr__(self, 'res', getattr(resources, name)) def __getattr__(self, att): s = self.res.read(att) if s is None: return None data = json.loads(s) return data def __setattr__(self, att, data): s = json.dumps(data) self.res.write(att, s) def __getitem__(self, key): return getattr(self, key) def __setitem__(self, key, value): setattr(self, key, value) class LocalObfuscatedStorage(LocalStorage): """Of questionable use, but should avoid card names being indexed""" def __getattr__(self, att): s = self.res.read(att) if s is None: return None data = json.loads(s.encode('rot13')) return data
import logging logger = logging.getLogger(__name__) import urllib.request, urllib.error, urllib.parse from clint import resources from PIL import Image import requests resources.init('kfdm', 'radio-growl') def image_cache(url): if url is None: return None data = None logger.info('Looking up %s', url) image_name = url.split('/').pop() with resources.cache.open(image_name, 'a+b') as f: logger.info('Opening %s', f.name) f.seek(0) data = f.read() if len(data) is 0: logger.info('Downloading: %s', url) data = requests.get(url).read() f.write(data) f.flush() if not f.name.endswith('.ico'): logger.info('Resizing: %s', image_name) img = Image.open(f.name) img = img.resize((150, 150), Image.ANTIALIAS) img.save(f.name)
#!/usr/bin/env python # -*- coding: utf-8 -*- import sys import os sys.path.insert(0, os.path.abspath('..')) from clint import resources resources.init('kennethreitz', 'clint') lorem = 'Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.' print '%s created.' % resources.user.path resources.user.write('lorem.txt', lorem) print 'lorem.txt created' assert resources.user.read('lorem.txt') == lorem print 'lorem.txt has correct contents' resources.user.delete('lorem.txt') print 'lorem.txt deleted' assert resources.user.read('lorem.txt') == None print 'lorem.txt deletion confirmed'
AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. """ import os import json import argparse from clint import resources from clint.textui import prompt, puts, puts_err, validators, colored from .journal import Journal, Entry resources.init('myles', 'py-dayone') def setup(args): if args.get('path', None): path = args.get('path') else: path = prompt.query("Path to your DayOne journal.", validators=[validators.PathValidator()]) path = os.path.abspath(path) if not os.path.exists(path): puts_err(colored.red("%s does not exist." % path)) return False
""" legit.bootstrap ~~~~~~~~~~~~~~~ This module boostraps the Legit runtime. """ from clint import resources from clint.textui import colored import crayons import configparser from .settings import legit_settings resources.init('kennethreitz', 'legit') try: config_file = resources.user.open('config.ini', 'r') except OSError: resources.user.write('config.ini', '') config_file = resources.user.open('config.ini', 'r') # Load existing configuration. config = configparser.ConfigParser() config.read_file(config_file) # Populate if needed. if not config.has_section('legit'): config.add_section('legit') modified = False
import logging import sys from clint import resources from slugify import slugify import docker from taomn import display from taomn.elements.network import Network from taomn.elements.service import Service from taomn.elements.volume import Volume from taomn.environments import environments logger = logging.getLogger('taomn') resources.init('tao', 'taomn') class Configuration: """docstring for Configuration.""" def __init__(self, name: str = None, net: str = None, pkey: str = None, start: bool = False, docker_url: str = None, api: bool = False) -> None: self.networks = {} self.services = {} self.volumes = {} self.name = name self.net = net
Episode = namedtuple('Episode', 'title, description, url') """ try: import cPickle as pickle except ImportError: import pickle """ import pickle # imports, see requirements.txt import podcastparser # get `podcastparser` with pip import soco # get `soco` with pip from clint import resources # get `clint` with pip from clint.textui import puts, colored, indent # get `clint` with pip resources.init('lurtgjort.no', 'SonoPod') class Library(object): def __init__(self): #'Read from cache' logging.info('read lib from %r', resources.user) try: self.podcasts = [Podcast(**e) for e in pickle.loads(resources.user.read('podcasts.db'))] except TypeError as e: #new library #logging.exception(e) self.podcasts = [] logging.info('init podcasts Library, currently: %r', self.podcasts) def save(self):
SOFTWARE. """ import re import os import datetime import configparser from operator import attrgetter import iso8601 import requests from tzlocal import get_localzone from clint import resources resources.init('myles', 'twtxt') __all__ = ['TwTxt', 'Source', 'Tweet'] url_regex = re.compile('http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\(\),]|' '(?:%[0-9a-fA-F][0-9a-fA-F]))+') mention_regex = re.compile(r'@<(?:(?P<name>\S+?)\s+)?(?P<url>\S+?://.*?)>') short_mention_regex = re.compile(r'@(?P<name>\S+)') class TwTxt(object): def __init__(self, config_path=None): if config_path: self.config_path = config_path else: self.config_path = os.path.join(resources.user.path, 'config')
import ConfigParser import clint.textui.colored from clint import resources from clint.textui import colored from .settings import settings resources.init('kennethreitz', 'legit') try: config_file = resources.user.open('config.ini', 'r') except IOError: resources.user.write('config.ini', '') config_file = resources.user.open('config.ini', 'r') # Load existing configuration. config = ConfigParser.ConfigParser() config.readfp(config_file) # Pouplate if needed.
os.path.abspath('%s/config/gourceconfig.ini' % CURRENT_DIR) ], 'git_log_options': [ 'git', 'log', '--pretty=format:user:%aN%n%ct', '--reverse', '--raw', '--encoding=UTF-8', '--no-renames' ], 'sound_file': os.path.abspath('%s/audio/happykids.wav' % CURRENT_DIR) } DEFAULTS.update( {'max_gources': DEFAULTS.get('rows') * DEFAULTS.get('columns')}) OPTS = dict() resources.init('ff0000', 'Battlestar Goursica') class RepoGoneError(Exception): pass def debugger(msg): if logging.getLogger().getEffectiveLevel() == logging.DEBUG: try: puts(msg) except UnicodeDecodeError, e: debugger(colored.red('%s' % e)) def initial_xmonad_layout():
BASE_CONFIG = {"startup_check": False} class ClassProperty(property): def __get__(self, cls, owner): return self.fget.__get__(None, owner)() class Config(object): _config = None @ClassProperty @classmethod def config(cls): if cls._config is None: config = resources.user.read(CONFIG_FILE) if config is None: config = BASE_CONFIG cls.commit() else: config = json.loads(config) cls._config = config return cls._config @classmethod def commit(cls): resources.user.write(CONFIG_FILE, json.dumps(cls.config)) resources.init('Arzaroth', 'CelesiaSunrise')
# -*- coding: utf-8 -*- """ pen.settings - some global variables """ import os from clint import resources resources.init('cwoebker', 'pen') PEN_FILE = resources.user.read('path.ini') if not PEN_FILE: PEN_FILE = os.path.expanduser('~/.pen')
def main(): """Main console script entrypoint for densli app Returns an integer exit code 0 for success, 1 for error(s). """ parser = OptionParser(usage="""usage: %prog [options] thing method""") parser.add_option("-u", "--username", dest="username", help="SD username" ", overrides config file.") parser.add_option("-p", "--password", dest="password", help="SD password" ", overrides config file.") parser.add_option("-a", "--account", dest="account", help="SD account" ", overrides config file.") parser.add_option("-q", "--quiet", dest="quiet", help="Don't output" " feedback to stdout.", action="store_true") parser.add_option("-s", "--spark", dest="spark", help="Generate a text" " based sparkline graph from metrics.getRange results.", action="store_true") parser.add_option("-P", "--postback", dest="postback", help="Flag STDIN" " piped data as being a metric postback, so send as raw" " JSON in the POST field 'postback'.", action="store_true") parser.add_option("-t", "--timeago", dest="timeago", help="Take a relative" " time offset from NOW and use that as the range for" " a metrics.getRange call. Accepts [Nd[ay]] [Nh[our]]" " [Nm[in[utes]]] [Ns[ec[ond]]] in any combination, e.g." " 1h 20sec, 5min, 2day 15s, 12 minutes etc.") parser.add_option("-d", "--data", dest="data", help="Data to send to" " the API. Multiple data values are excepted. Values" " should be in name/value pairs, e.g. name=value", action="append", default=[]) (options, args) = parser.parse_args() resources.init('ServerDensity', 'Densli') # Allow the user to override the location for config files with an # environment variable config_path = os.getenv('DENSLI_HOME', False) if config_path: if not options.quiet: show_info(['Using "%s" from DENSLI_HOME env var..' % (config_path,)]) resources.user.path = os.path.expanduser(config_path) resources.user._exists = False resources.user._create() config = resources.user.read('config.json') # If we couldn't load a config, create a default config file but warn # the user as it won't work without editing if config is None: with open(os.path.join( os.path.dirname(__file__), 'config.json')) as json_fp: resources.user.write('config.json', json_fp.read()) fp = resources.user.open('config.json') show_error(['No config.json found..', 'Initialised basic config.json at: %s' % (os.path.abspath(fp.name),), 'Edit this file and fill in your SD API details.', 'Remember to remove the "enabled" field or set it to' ' true.']) fp.close() return 1 # Load JSON and handle decoding errors try: config = json.loads(config) except Exception, e: show_error(['Error parsing JSON from config file:'], e) return 1
# -*- coding: utf-8 -*- # TODO: add secret key to url (or POST?) # also look at invalid signature error message (oauth) or if that is part of missing secret key # (scala obp importer has it working) #import json from clint import resources from utils import oauth_login, base_url resources.init('openbankproject', 'evmakesgeo') key_file = resources.user.read('config.ini') # key file in a place like: /Users/simonredfern/Library/Application\ Support/evmakesgeo/config.ini print "key file is: %s" % key_file openbank = oauth_login(base_url, key_file) # Load a json file for sandbox creation. with open('/Users/simonredfern/Documents/OpenBankProject/DATA/BNPP/OBP-sandbox-bnpp-fr_compact.json') as data_file: #data = json.load(data_file) data=data_file.read().replace('\n', '') url = "{}obp/vsandbox/v1.0/data-import".format(base_url) print 'url is: %s' % url #print 'data is: %s' % data headers = { 'content-type': 'application/json', 'Accept': 'application/json'
"startup_check": False, } class ClassProperty(property): def __get__(self, cls, owner): return self.fget.__get__(None, owner)() class Config(object): _config = None @ClassProperty @classmethod def config(cls): if cls._config is None: config = resources.user.read(CONFIG_FILE) if config is None: config = BASE_CONFIG else: config = json.loads(config) cls._config = config cls.commit() return cls._config @classmethod def commit(cls): resources.user.write(CONFIG_FILE, json.dumps(cls.config)) resources.init('Arzaroth', 'CelesiaSunrise')
import logging import sys from clint import resources from slugify import slugify import docker from tmnd import display from tmnd.elements.network import Network from tmnd.elements.service import Service from tmnd.elements.volume import Volume from tmnd.environments import environments logger = logging.getLogger('tmnd') resources.init('tomochain', 'tmnd') class Configuration: """docstring for Configuration.""" def __init__(self, name: str = None, net: str = None, pkey: str = None, start: bool = False, docker_url: str = None, api: bool = False) -> None: self.networks = {} self.services = {} self.volumes = {} self.name = name self.net = net
def open_config(path): if path is None: resources.init('Universe', 'redcliff') return resources.user.open('config.json', 'r') else: return open(path, 'r')