def __init__(self): self.db = Database() self.esi = ESI() self.config = Config() self.admins = self.config.getConfig()["settings"]["admins"] self.lastUpdate = 0 self.isRefreshing = False self.corpCache = 0 self.corpAssets = [] self.itemTranslations = {} self.divisions = [] self.assetNames = {} self.officeFlags = {} self.priceUpdateCache = 0 self.bpCache = 0 self.bps = {} self.industryJobs = [] self.translations = set() self.itemTranslations = {} self.prices = {} self.production = {} self.structures = {} self.contracts = {} self.miningInfo = {} self.toProduce = {} self.accepted_groups = [ 12 # cargo containers ]
def __init__(self): ## set priviate values self.config = Config(workpath) self.pid = os.getpid() self.pname = 'WebApp.py' ## logger initial self.loggerInit() ## lock initial self.lockObj = Lock(self.pname, self.pid, self.config.LOCK_DIR, self.config.LOCK_FILE, self.logger) ## debug output self.logger.debug('WebApp Initial Start') self.logger.debug('[SYS_LISTEN_IP][%s]' % (self.config.SYS_LISTEN_IP)) self.logger.debug('[SYS_LISTEN_PORT][%s]' % (self.config.SYS_LISTEN_PORT)) self.logger.debug('[SYS_DEBUG][%s]' % (self.config.SYS_DEBUG)) self.logger.debug('[LOCK_DIR][%s]' % (self.config.LOCK_DIR)) self.logger.debug('[LOCK_FILE][%s]' % (self.config.LOCK_FILE)) self.logger.debug('[LOG_DIR][%s]' % (self.config.LOG_DIR)) self.logger.debug('[LOG_FILE][%s]' % (self.config.LOG_FILE)) self.logger.debug('[LOG_LEVEL][%s]' % (self.config.LOG_LEVEL)) self.logger.debug('[LOG_MAX_SIZE][%s]' % (self.config.LOG_MAX_SIZE)) self.logger.debug('[LOG_BACKUP_COUNT][%s]' % (self.config.LOG_BACKUP_COUNT)) self.logger.debug('WebApp Initial Done')
def get_config(self, key): ini = Config('..\conf\dataSource.ini') dict_item = {} list = ini.get_item_by_section(key) for k, v in list: dict_item[k] = v return dict_item
def connect(self): config = Config().getConfig() self.conn = MySQLdb.connect(host=config['mysql']['host'], port=config['mysql']['port'], user=config['mysql']['user'], passwd=config['mysql']['pass'], db=config['mysql']['db']) self.conn.autocommit(True) self.conn.set_character_set('utf8')
def __init__(self): ini = Config('../conf/dataSource.ini') dict_item = {} list = ini.get_item_by_section('rabbit-mq') for k, v in list: dict_item[k] = v credentials = pika.PlainCredentials(dict_item['username'], dict_item['password']) #注意用户名及密码 self.connection = pika.BlockingConnection( pika.ConnectionParameters(dict_item['host'], dict_item['port'], dict_item['vhost'], credentials))
def __get_user_v(self): _v = Config(self.__TMP_FILE__) if _v.get('time') is not None and self.__diff_date( _v.get('time')) >= 0: return _v.get('v') else: v = self.__get_v() if v is not False: _v.set({"v": v, "time": time.time()}) if _v.save() is True: return _v.get('v') raise ValueError('Get v Error')
def __init__( self , configFile , visible = True ) : self.configFile = configFile self.config = Config( self.configFile ) self.config.fetch( ) self.visible = visible self.password = None self.__prepareConfig( ) self.controller = Controller( self ) self.controller.configure( )
def setup(self): #allure.environment(host="172.6.12.27", test_vars=paras) #调试单个case使用该路径 cf = Config() url_base = cf.url_base self.data = {\ 'userLid': '12614789456ceshijinbishangxian11', 'lessonLid': '4e746cee84d24ea8bf354ceb722cabac'} self.url = url_base + 'api/app/v1/lesson/report/generateLessonReport' self.headers = {"Content-type":"application/json"} self.assertion = Assertions() self.request = RequestBase()
class MySQL: ini = Config('E:\python_code\ApiAutoTest\conf\dataSource.ini') dict_item = {} list_item = ini.get_item_by_section('mysql') for k, v in list_item: dict_item[k] = v ''' 1、_xxx 不能用于’from module import *’ 以单下划线开头的表示的是protected类型的变量。即保护类型只能允许其本身与子类进行访问。 2、__xxx 双下划线的表示的是私有类型的变量。只能是允许这个类本身进行访问了。连子类也不可以 3、__xxx___ 定义的是特列方法。像__init__之类的 ''' def connect(self): db = pymysql.connect(host=self.dict_item['mysql_host'], port=int(self.dict_item['mysql_port']), user=self.dict_item['mysql_username'], password=self.dict_item['mysql_password'], database=self.dict_item['mysql_database'], charset=self.dict_item['mysql_charset']) return db # 插入、删除、更新数据,不带参数 def update(self, sql): cursor = self.connect().cursor() try: cursor.execute(sql) self.connect().commit() except: self.connect().rollback() # 插入、删除、更新数据,带参数 def update(self, sql, params): cursor = self.connect().cursor() try: cursor.execute(sql, params) self.connect().commit() except: self.connect().rollback() # 查询数据 def query(self, sql): cursor = self.connect().cursor() try: cursor.execute(sql) result = cursor.fetchall() except: print("Error: unable to fetch data") return result
def t_bird(): print("launch bird") current_path = pathlib.Path(__file__).parent.absolute() config = Config(f'{current_path}/config.json') bird = Bird(config.Api_Key, config.Api_Secret, config.Access_Token, config.Access_Token_Secret) while TWITTER: runing = fan.is_fan_running() last_run = fan.get_last_run() temperature = fan.get_current_temperature() message = f"Fan running: {runing}, Current Temperature: {temperature}°C, last run: {last_run}" bird.twitter(message) print(message) time.sleep(30 * 60) # w8 N * 60 sec
def _initialize_config(self): """ Load the configuration file Load the configuration file ('Allitebook.ini') if possible. Otherwise, create one with the default value if it doesn't already exists. Args: Returns: Config: instance of the config class containing the config values """ config = Config.Config('Allitebook.ini') config.set_default_value('url', None) config.set_default_value('query', None) config.set_default_value('current_pages', 0) config.set_default_value('total_pages', 0) return config
def __init__(self): self.db = Database() self.config = Config() self.scopes = self.config.getConfig()["settings"]["esiScopes"] self.esi_app = App.create( url=self.config.getConfig()["settings"]["esiURL"], ) self.security = EsiSecurity( app=self.esi_app, redirect_uri=self.config.getConfig()["settings"]["esiCallback"], client_id=self.config.getConfig()["settings"]["esiClientID"], secret_key=self.config.getConfig()["settings"]["esiSecretKey"], headers={ 'User-Agent': self.config.getConfig()["settings"]["esiCustomHeader"] }) self.client = EsiClient( security=self.security, retry_requests=True, headers={ 'User-Agent': self.config.getConfig()["settings"]["esiCustomHeader"] })
def __init__(self): self.config = Config() self.env = Environment(loader=FileSystemLoader( searchpath="templates/mail"))
def __init__(self): self.config = Config().getConfig()
createTable = """ DROP TABLE IF EXISTS `users`; CREATE TABLE `users` ( `id` int(11) NOT NULL AUTO_INCREMENT,\ `user` varchar(128) NOT NULL, `pass` varchar(128) NOT NULL, `email` varchar(128) NULL, `created` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, `updated` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, PRIMARY KEY (ID) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 ROW_FORMAT=COMPACT; """ config = Config().getConfig() db = MySQLdb.connect(host=config['mysql']['host'], port=config['mysql']['port'], user=config['mysql']['user'], passwd=config['mysql']['pass'], db=config['mysql']['db']) db.autocommit(True) cursor = db.cursor() user = raw_input("Username: "******"Email: ") passw = getpass.getpass("Password: "******"Confirm password: "******"Passwords do not match!") exit
#!/usr/bin/env python3 from flask import Flask, abort, send_file from gtts import gTTS from pydub import AudioSegment from pydub.utils import which from lib.Config import Config from lib.KeyValueStore import KeyValueStore as KVS import hashlib, os app = Flask(__name__) cfg = Config(os.path.dirname(__file__) + '/config.json') history = KVS() FILE_ROOT = os.path.dirname(__file__) + '/mp3_files/' def initialize(): if not os.path.isdir(FILE_ROOT): print("created dir: {}".format(FILE_ROOT)) os.makedirs(FILE_ROOT) def add_to_history(text_hash, file_name, lang, text): history.add_key(text_hash, file_name) history.add_attribute(text_hash, "lang", lang) history.add_attribute(text_hash, "text", text) #link = '<div class="link"><a href='+cfg.server_host+":"+str(cfg.public_port)+"/tts/"+lang+"/"+urllib.parse.quote(text)+">"+lang+" - " +text+"</a></div>"
def __init__(self): self.db = Database() self.config = Config().getConfig() self.key = self.config['server_settings']['app_key']
import sys from flask import Flask from flask_restful import Api from flask_login import LoginManager from flask_wtf.csrf import CSRFProtect from flask_sqlalchemy import SQLAlchemy ## initial workpath valus workpath = os.path.abspath(os.path.join(os.path.dirname(__file__), os.pardir)) sys.path.append('%s' % (workpath)) ## import priviate pkgs from lib.Config import Config ## load config config = Config(workpath) MARIADB_HOST = config.MARIADB_HOST MARIADB_PORT = config.MARIADB_PORT MARIADB_USER = config.MARIADB_USER MARIADB_PASSWORD = config.MARIADB_PASSWORD MARIADB_DATABASE = config.MARIADB_DATABASE ## initial some global values db = SQLAlchemy() login_manager = LoginManager() csrf = CSRFProtect() ## getApp func def getApp(name): ## init flask
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # vi send_msg.py #!/usr/bin/env python import pika import json from lib.Config import Config from lib.rabbitMq_login import rabbitMq_login ini = Config('../conf/dataSource.ini') credentials = pika.PlainCredentials('omp_test', '!QAZ@WSX') #注意用户名及密码 connection = pika.BlockingConnection(pika.ConnectionParameters( '10.165.196.104', 5672, '/omp_test_host', credentials)) channel = connection.channel() arguments = {"x-message-ttl":604800000} channel.queue_declare(queue='p4p_adv_audit_queue.yml',durable='True',arguments=arguments) body_dict = {"agentId":1007, "agentName":"北京派瑞威行广告有限公司(luye)", "channel":2, "credentials":[ { "cid":1, "isPerpetual":1, "name":"组织机构代码证", "relationId":1793, "status":0,
import os, time import requests from selenium import webdriver from behave import given, then, when from lib.Config import Config from support.Case_1_Page import Case_1_Page from support.SkyEng_Login_Page import SkyEng_Login_Page from selenium.common.exceptions import TimeoutException from selenium.webdriver.common.keys import Keys cf = Config() cs = Case_1_Page() lg = SkyEng_Login_Page() skyengprod = cf.get_config('config/config.ini', 'links', 'skyengprod') skyengstaging = cf.get_config('config/config.ini', 'links', 'skyengstaging') @then(u'I select New Student') def step_impl(context): cs.new_student(context) time.sleep(3) print(cs.new_student_mode_title(context)) assert cs.new_student_mode_title(context) == "New Student mode" @then(u'I select options General English, Beginner, 1st lesson') def step_impl(context): cs.mode_general(context) cs.mode_level_beginner(context) time.sleep(2) cs.mode_lesson_1(context)
import os import sys from lib.Log import Log from lib.DDNS import DDNS from lib.Config import Config if __name__ == '__main__': # initial val BASE_PATH = os.path.abspath(os.path.dirname(__file__)) # read config configObj = Config(BASE_PATH) logObj = Log(configObj) logger = logObj.get_logger() #debug print logger.debug('DOMAIN_DOMAIN {}'.format(configObj.DOMAIN_DOMAIN)) logger.debug('DOMAIN_PREFIX {}'.format(configObj.DOMAIN_PREFIX)) logger.debug('DOMAIN_TYPE {}'.format(configObj.DOMAIN_TYPE)) logger.debug('DOMAIN_TTL {}'.format(configObj.DOMAIN_TTL)) logger.debug('LOG_PATH {}'.format(configObj.LOG_PATH)) logger.debug('LOG_FILE {}'.format(configObj.LOG_FILE)) logger.debug('LOG_MAX_SIZE {}'.format(configObj.LOG_MAX_SIZE)) logger.debug('LOG_BACKUP_COUNT {}'.format(configObj.LOG_BACKUP_COUNT)) # initial ddnsObj ddnsObj = DDNS(configObj, logger) ddnsObj.run() # success exit sys.exit(configObj.SUCCESS_EXIT)
import rospy from sensor_msgs.msg import Image from std_msgs.msg import String, Float32, Int32, Float32MultiArray, Bool from cv_bridge import CvBridge from lhu_irc.msg import Line import cv2 import numpy as np from lib.Config import Config from lib.cardriver import CarDriver from lib.lanedetect import LaneDetect import time config = Config() config = config.get() bridge = CvBridge() cd = CarDriver("/car_steer_tmp", "/car_steer_tmp") ld = LaneDetect(config) frame = None obstacle = 0 ss_status = False #----------------------------- MAIN ---------------------------------# rospy.init_node('run_lane_detect', anonymous=True) def callback_stream(ros_data): global bridge, frame
class RedisApi: ini = Config('E:\python_code\ApiAutoTest\conf\dataSource.ini') dict_item = {} list_item = ini.get_item_by_section('redis') print(list_item) for k, v in list_item: dict_item[k] = v def __init__(self): host = self.dict_item['redis_host'] port = self.dict_item['redis_port'] password = self.dict_item['redis_password'] self.pool = redis.ConnectionPool(host=host, port=port, password=password) def connect(self): self.redis = redis.Redis(connection_pool=self.pool) return self.redis def disconnect(self): return self.pool.disconnect() ''' String 操作 ''' # 在redis中设置值 def set(self, key, value, ttl=None): if not isinstance(key, str): print("the type of key is not string") self.redis.set(key, value, ttl) # 获取值 def get(self, key): if not isinstance(key, str): print("the type of key is not string") if not self.connect().exists(key): print("the key is not exists") val = self.redis.get(key) return val # 批量设置值 def mset(self, **kwags): self.redis.mset(**kwags) # 批量获取值 def mget(self, keys): self.redis.mget(keys) # 设置新值,打印原值 def getset(self, key, value): if not isinstance(key, str): print("the type of key is not string") old_value = self.redis.getset(key, value) return old_value # 根据字节获取子序列 def getrange(self, key, start, end): if not isinstance(key, str): print("the type of key is not string") self.redis.getrange(key, start, end) def keys(self): flag = self.connect().keys() return flag ''' Hash操作 ''' # 根据key获取value def hget(self, name, key): if not isinstance(name, str): print("the type of key is not string") if not self.redis.exists(name): print("the name is not exists") val = self.redis.hget(name, key) return val