def init_app(app): # 初始化日志 from vanaspyhelper.LoggerManager import init_global_logger # 要么传入配置路径,要么获取当前目录的上一级 `os.path.dirname(basedir)` current_dir_parent = os.path.dirname(basedir) if 'APP_LOG_DIR' in app.config: log_dir = app.config['APP_LOG_DIR'] else: log_dir = current_dir_parent if 'APP_LOG_LEVEL' in app.config: log_level = app.config['APP_LOG_LEVEL'] else: log_level = "error" from konfig import Config # 初始化 aes c = Config(app.config['SECURITY_CONF_PATH']) global aes aes = AESTool(key=c.get_map('AES').get('AES_SECRET_KEY')) # 初始化 client_id ,client_secret app.config.update(c.get_map('CLIENT_DATA')) # 初始化日志对象 init_global_logger(log_dir, level=log_level, log_prefix="VanasRSC")
def load_into_settings(filename, settings): """Load config file contents into a Pyramid settings dict. This is a helper function for initialising a Pyramid settings dict from a config file. It flattens the config file sections into dotted settings names and updates the given dictionary in place. You would typically use this when constructing a Pyramid Configurator object, like so:: def main(global_config, **settings): config_file = global_config['__file__'] load_info_settings(config_file, settings) config = Configurator(settings=settings) """ filename = os.path.expandvars(os.path.expanduser(filename)) filename = os.path.abspath(os.path.normpath(filename)) config = Config(filename) # Konfig keywords are added to every section when present, we have to # filter them out, otherwise plugin.load_from_config and # plugin.load_from_settings are unable to create instances. konfig_keywords = ['extends', 'overrides'] # Put values from the config file into the pyramid settings dict. for section in config.sections(): setting_prefix = section.replace(":", ".") for name, value in config.get_map(section).iteritems(): if name not in konfig_keywords: settings[setting_prefix + "." + name] = value # Store a reference to the Config object itself for later retrieval. settings['config'] = config return config
def load_into_settings(filename, settings): """Load config file contents into a Pyramid settings dict. This is a helper function for initialising a Pyramid settings dict from a config file. It flattens the config file sections into dotted settings names and updates the given dictionary in place. You would typically use this when constructing a Pyramid Configurator object, like so:: def main(global_config, **settings): config_file = global_config['__file__'] load_info_settings(config_file, settings) config = Configurator(settings=settings) """ filename = os.path.expandvars(os.path.expanduser(filename)) filename = os.path.abspath(os.path.normpath(filename)) config = Config(filename) # Put values from the config file into the pyramid settings dict. for section in config.sections(): setting_prefix = section.replace(":", ".") for name, value in config.get_map(section).iteritems(): settings[setting_prefix + "." + name] = value # Store a reference to the Config object itself for later retrieval. settings['config'] = config return config
def _is_authorized_app(client_id: str, grant_type: str) -> str: """ 验证 service 的 client、grant_type。 配置参考 setting.yaml :param client_id: service id :param grant_type: 客户端授权凭证 :return: client_secret: service secret key """ from konfig import Config # 获取所有的 client id 对应的 client serct c = Config(current_app.config['SECURITY_CONF_PATH']) try: clients_map = c.get_map('CLIENT_LIST') except: raise ClientConfigNotFound( "无法获取服务端 Client 配置.请研发人员核实. PATH : {}".format( current_app.config['SECURITY_CONF_PATH'])) secret_key = clients_map.get(client_id) if not secret_key: raise NotSupportServiceError( "未知的 Service ID : [{}]. 请核实!".format(client_id)) if not compare_digest(current_app.config['JWT_GRANT_TYPE'], grant_type): raise GrantTypeError( "unKnow `grant_type` . Plz get it from your app development. '{}' . " .format(grant_type)) return secret_key
def main(): parser = argparse.ArgumentParser(description='Marteau Server') parser.add_argument('config', help='Config file', nargs='?') parser.add_argument('--version', action='store_true', default=False, help='Displays Marteau version and exits.') parser.add_argument('--log-level', dest='loglevel', default='info', choices=LOG_LEVELS.keys() + [key.upper() for key in LOG_LEVELS.keys()], help="log level") parser.add_argument('--log-output', dest='logoutput', default='-', help="log output") parser.add_argument('--host', help='Host', default='0.0.0.0') parser.add_argument('--port', help='Port', type=int, default=8080) args = parser.parse_args() if args.version: print(__version__) sys.exit(0) if args.config is None: parser.print_usage() sys.exit(0) # configure the logger configure_logger(logger, args.loglevel, args.logoutput) # loading the config file config = Config(args.config) # loading the app & the queue global_config = {} if config.has_section('marteau'): settings = config.get_map('marteau') else: settings = {} # check is redis is running if not redis_available(): raise IOError('Marteau needs Redis to run.') # loading the fixtures plugins for fixture in settings.get('fixtures', []): import_string(fixture) logger.info('Loaded plugins: %s' % ', '.join(get_fixtures())) app = webapp(global_config, **settings) try: httpd = SocketIOServer((args.host, args.port), app, resource="socket.io", policy_server=False) logger.info('Hammer ready, at http://%s:%s. Where are the nails ?' % (args.host, args.port)) httpd.serve_forever() except KeyboardInterrupt: sys.exit(0) finally: logger.info('Bye!')
def test_reader(self): config = Config(self.file_one) # values conversion self.assertEquals(config.get('one', 'foo'), 'bar') self.assertEquals(config.get('one', 'num'), -12) self.assertEquals(config.get('one', 'not_a_num'), "12abc") self.assertEquals(config.get('one', 'st'), 'o=k') self.assertEquals(config.get('one', 'lines'), [1, 'two', 3]) self.assertEquals(config.get('one', 'env'), 'some stuff') # getting a map map = config.get_map() self.assertEquals(map['one.foo'], 'bar') map = config.get_map('one') self.assertEquals(map['foo'], 'bar') del os.environ['__STUFF__'] self.assertEquals(config.get('one', 'env'), 'some stuff') # extends self.assertEquals(config.get('three', 'more'), 'stuff') self.assertEquals(config.get('one', 'two'), 'a')
def create_app(): """ Create the app object and return it """ app = Flask(__name__) # Load application settings settings = os.environ.get("FLASK_SETTINGS", SETTINGS) if settings is not None: c = Config(settings) print(c) app.config.update(c.get_map('flask')) from users.views import user # Register the blueprints to app app.register_blueprint(user) db.init_app(app) return app
from flask import Flask, render_template, request, url_for, session, redirect, flash from flask_bcrypt import Bcrypt import os from flask_pymongo import PyMongo import requests import urllib.parse #끌어오기 import opgg_crawling from time import sleep #받아오기 속도조절 from konfig import Config cc = Config("./conf.ini") api_conf = cc.get_map("api") app_conf = cc.get_map("app") db_conf = cc.get_map("db") app = Flask(__name__) #DB와 비밀번호는 환경변수에서 가져온다. app.config['SECRET_KEY'] = app_conf['SECRET_KEY'] app.config['MONGO_URI'] = db_conf['MONGO_URI'] apikey = api_conf['LOL_API_KEY'] mongo = PyMongo(app) bcrypt = Bcrypt(app) @app.route('/') def index(name=None): tip_List = mongo.db.tip_List get_tips = tip_List.find().sort([['_id', -1]]).limit(10) tip_lists = []
from flask import Flask, Blueprint from flask_restful import Api from konfig import Config from myservice.views.home import Home from myservice.views.hello import Hello # Load application settings _HERE = os.path.dirname(__file__) _SETTINGS = os.path.join(_HERE, 'settings.ini') # Load environment settings load_dotenv() configuration = Config(_SETTINGS) app = Flask(__name__) app.config.update(configuration.get_map('SomeSettingsSection')) app.config["DEBUG"] = os.getenv('DEBUG') # You need to declare necessary configuration to initialize flask-profiler as follows: app.config["flask_profiler"] = { "enabled": app.config["DEBUG"], "storage": { "engine": "sqlite" }, "basicAuth": { "enabled": True, "username": "******", "password": "******" }, "ignore": [ "^/static/.*"
from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC from konfig import Config from bs4 import BeautifulSoup from time import sleep import contextlib config = Config('../conf.ini') path = config.get_map("path") user_info = config.get_map("user") driver = webdriver.Chrome(path['DRIVER_PATH']) # 웹 자원 로드를 위해 3초까지 기다려준다. driver.implicitly_wait(3) # github에 로그인하기 driver.get('https://github.com/login') driver.find_element_by_id('login_field').send_keys(user_info['ID']) driver.find_element_by_id('password').send_keys(user_info['PASSWD']) driver.find_element_by_name('commit').click() driver.implicitly_wait(3) driver.get('https://github.com/' + user_info['NAME'])
def main(): parser = argparse.ArgumentParser(description='Marteau Server') parser.add_argument('config', help='Config file', nargs='?') parser.add_argument('--version', action='store_true', default=False, help='Displays Marteau version and exits.') parser.add_argument('--log-level', dest='loglevel', default='info', choices=LOG_LEVELS.keys() + [key.upper() for key in LOG_LEVELS.keys()], help="log level") parser.add_argument('--log-output', dest='logoutput', default='-', help="log output") parser.add_argument('--host', help='Host', default='0.0.0.0') parser.add_argument('--port', help='Port', type=int, default=8080) args = parser.parse_args() if args.version: print(__version__) sys.exit(0) if args.config is None: parser.print_usage() sys.exit(0) # configure the logger configure_logger(logger, args.loglevel, args.logoutput) # loading the config file config = Config(args.config) # loading the app & the queue global_config = {} if config.has_section('marteau'): settings = config.get_map('marteau') else: settings = {} # check is redis is running if not redis_available(): raise IOError('Marteau needs Redis to run.') # loading the fixtures plugins for fixture in settings.get('fixtures', []): import_string(fixture) logger.info('Loaded plugins: %s' % ', '.join(get_fixtures())) app = webapp(global_config, **settings) try: httpd = SocketIOServer((args.host, args.port), app, resource="socket.io", policy_server=False) logger.info('Hammer ready, at http://%s:%s. Where are the nails ?' % (args.host, args.port)) httpd.serve_forever() except KeyboardInterrupt: sys.exit(0) finally: logger.info('Bye!')
import requests from konfig import Config from bs4 import BeautifulSoup as bs config = Config('../conf.ini') login_info = config.get_map("user") user_info = { 'login': login_info['ID'], 'password': login_info['PASSWD'] } with requests.Session() as session: login_req = session.post('https://sso.ajou.ac.kr/jsp/sso/ip/login_meta_form.jsp', data=user_info) if login_req.status_code != 200: raise Exception('로그인 실패했습니다. 오류코드: {code} '.format(code=login_req.status_code)) # js 로 생성하는 듯 하다 아무것도 안나옴.. notices = session.get('https://eclass2.ajou.ac.kr/ultra/course') soup = bs(notices.text, 'html.parser') subjects = soup.select('h4') print(subjects)
on top of ConfigParser, which automates the conversion of simple types like integers and Booleans. """ from flask import Flask from konfig import Config ''' Adds prod_settings configuration to Flask's configuration object. The values have been stored in app.config.py.json ''' app = Flask(__name__) app.config.from_object('prod_settings.Config') print(app.config) ''' Since Flask exposes its configuration via app.config, it's pretty simple to load additional options from a YAML file, or any other text-based file. (see prod_settings.ini) Many Flask extensions exist to load the configuration from an INI file, but using the standard library ConfigParser is trivial. There's one major caveat from using INI files: variables values are all strings, and your application needs to take care of converting them to the right type. ''' c = Config('prod_setting.ini') app.config.update(c.get_map('flask')) print(app.config)