Python config.config() Examples
The following are 30
code examples of config.config().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
config
, or try the search function
.
Example #1
Source File: __init__.py From CTask with GNU General Public License v3.0 | 7 votes |
def create_app(config_name): app = Flask(__name__) #app.config['JSON_AS_ASCII'] = False # 进行app配置 把自己的config设定导入到app中 app.config.from_object(config[config_name]) # 初始化app配置 config[config_name].init_app(app) db.init_app(app) db.app = app # 初始化apscheduler scheduler.init_app(app) scheduler.start() from .main import main as main_blueprint app.register_blueprint(main_blueprint) from .job import main as job_blueprint app.register_blueprint(job_blueprint,url_prefix='/v1/cron/job') return app
Example #2
Source File: __init__.py From papers with MIT License | 7 votes |
def create_app(env): app = Flask(__name__) app.config.from_object(config[env]) # Start api/v1 Blueprint api_bp = Blueprint('api', __name__) api = Api(api_bp) api.add_resource(auth.AuthLogin, '/auth/login') api.add_resource(auth.AuthRegister, '/auth/register') api.add_resource(files.CreateList, '/users/<user_id>/files') api.add_resource(files.ViewEditDelete, '/users/<user_id>/files/<file_id>') app.register_blueprint(api_bp, url_prefix="/api/v1") # End api/v1 Blueprint return app
Example #3
Source File: OP_1_Backup.py From OP_Manager with MIT License | 6 votes |
def loadStateToOPZ(self, localPath): OPZStatePath = config["OP_Z_Mounted_Dir"] print("Load local to OPZ") print(localPath) print(OPZStatePath) for root, dirs, files in os.walk(OPZStatePath): for f in files: print("remove", f) os.unlink(os.path.join(root, f)) for d in dirs: print("remove Dir", d) shutil.rmtree(os.path.join(root, d)) print("OPZ Dir Cleared") print("Copying to OPZ") copytree(localPath, OPZStatePath) print("Finished Copying to OPZ")
Example #4
Source File: __init__.py From Flashcards with MIT License | 6 votes |
def create_app(config_name): app = Flask(__name__) app.config.from_object(config[config_name]) config[config_name].init_app(app) bootstrap.init_app(app) mail.init_app(app) moment.init_app(app) db.init_app(app) login_manager.init_app(app) pagedown.init_app(app) if not app.debug and not app.testing and not app.config['SSL_DISABLE']: from flask_sslify import SSLify sslify = SSLify(app) from .main import main as main_blueprint app.register_blueprint(main_blueprint) from .auth import auth as auth_blueprint app.register_blueprint(auth_blueprint, url_prefix='/auth') return app
Example #5
Source File: alarms.py From BatteryMonitor with GNU General Public License v2.0 | 6 votes |
def scanalarms(self,batdata): # self.timedate = localtime() # print (self.timedate.tm_hour) for i in config['alarms']: if not self.alarmtriggered[i]: exec(config['alarms'][i][1]) # log.debug('{}{}{}'.format(self.test,batdata.maxcellv,batdata.lastmaxcellv)) if self.test: # sys.stderr.write('Alarm 1 triggered') log.info('alarm {} triggered'.format(i)) self.alarmtriggered[i]=True exec(config['alarms'][i][2]) if self.alarmtriggered[i]: exec(config['alarms'][i][3]) if self.test: log.info('alarm {} reset'.format(i)) self.alarmtriggered[i]=False exec(config['alarms'][i][4])
Example #6
Source File: __init__.py From jbox with MIT License | 6 votes |
def create_app(config_name): app = Flask(__name__) app.config.from_object(config[config_name]) config[config_name].init_app(app) bootstrap.init_app(app) moment.init_app(app) db.init_app(app) login_manager.init_app(app) from .main import main as main_blueprint app.register_blueprint(main_blueprint) from .auth import auth as auth_blueprint app.register_blueprint(auth_blueprint, url_prefix='/auth') app.register_blueprint(auth_blueprint, url_prefix='/qrcode') from .api_1_0 import api as api_1_0_blueprint app.register_blueprint(api_1_0_blueprint, url_prefix='/v1') from .plugins import plugins as plugins_blueprint app.register_blueprint(plugins_blueprint, url_prefix='/plugins') return app
Example #7
Source File: OP_1_Connection.py From OP_Manager with MIT License | 6 votes |
def check_OP_1_Connection(): connected = Image.new('1', (128, 64)) draw = ImageDraw.Draw(connected) draw.text((0, 25), "Connecting.....", font=getFont(), fill='white') displayImage(connected) # if is_connected(): if do_mount("OP1"): connected = Image.new('1', (128, 64)) draw = ImageDraw.Draw(connected) draw.text((0, 25), "Connected", font=getFont(), fill='white') displayImage(connected) return True else: connected = Image.new('1', (128, 64)) draw = ImageDraw.Draw(connected) draw.text((0, 25), "No Connection!", font=getFont(), fill='white') displayImage(connected) config["USB_Mount_Path"] = "" config["OP_1_Mounted_Dir"] = "" time.sleep(1) return False
Example #8
Source File: getbms.py From BatteryMonitor with GNU General Public License v2.0 | 6 votes |
def getbmsdat(self,port,command): """ Issue BMS command and return data as byte data """ """ assumes data port is open and configured """ for i in range(5): try: port.write(command) reply = port.read(4) # raise serial.serialutil.SerialException('hithere') break except serial.serialutil.SerialException as err: errfile=open(config['files']['errfile'],'at') errfile.write(time.strftime("%Y%m%d%H%M%S ", time.localtime())+str(err.args)+'\n') errfile.close() # print (reply) x = int.from_bytes(reply[3:5], byteorder = 'big') # print (x) data = port.read(x) end = port.read(3) # print (data) return data
Example #9
Source File: summary.py From BatteryMonitor with GNU General Public License v2.0 | 6 votes |
def writesummary(self): """ Write summary file """ for section in summaryfile.sections(): for option in summaryfile.options(section): summaryfile.set(section, option, str(self.summary[section][option])) of = open(config['files']['summaryfile'],'w') summaryfile.write(of) of.close() # def writehour(self, data): # hoursummaryfile=open('/media/75cc9171-4331-4f88-ac3f-0278d132fae9/hoursummary','a') # hoursummaryfile.write(data) # hoursummaryfile.close() # logsummary.set('alltime', 'maxvoltages') = round(max(literal_eval(logsummary.get('currentday','maxvoltages')),literal_eval(logsummary.get(),2) # logsummary.set('alltime', 'minvoltages') = round(min(literal_eval(logsummary.get('currentday','minvoltages')),batdata.batvoltsav[8]),2) # logsummary.set('alltime', 'ah') = round(max(literal_eval(logsummary.get('currentday','ah'))[1], batdata.soc/1000),2) # logsummary.set('alltime', 'ah') = round(min(literal_eval(logsummary.get('currentday','ah'))[0], batdata.soc/1000),2) # logsummary.set('alltime', 'current') = round(max(literal_eval(logsummary.get('alltime','current'))[1], batdata.currentav[-3]/1000),2) # logsummary.set('alltime', 'current') = round(min(literal_eval(logsummary.get('alltime','current'))[0], batdata.currentav[-3]/1000),2)
Example #10
Source File: bms.py From BatteryMonitor with GNU General Public License v2.0 | 6 votes |
def findbms(self): """Scan ports to find BMS port""" self.bmsport="" for dev in glob.glob(config['Ports']['bmsport']): for i in range(2): try: self.openbms(dev) reply=self.getbmsdat(self.port,b'\x05\x00') if reply.decode('ascii','strict')==self.sn: self.bmsport=dev break except serial.serialutil.SerialException: pass finally: self.port.close() if self.bmsport!="": break if self.bmsport=="": raise Exception("Couldn't find BMS hardware name {}".format(self.sn))
Example #11
Source File: upload.py From Auto_Record_Matsuri with MIT License | 6 votes |
def upload_video(video_dict, user_config): upload_way_dict = {'bd': BDUpload, 's3': S3Upload} upload_way = upload_way_dict.get(config['upload_by']) uploader = upload_way() ddir = get_ddir(user_config) uploader.upload_item(f"{ddir}/{video_dict['Title']}", video_dict['Title']) if config['upload_by'] == 'bd': share_url = uploader.share_item(video_dict['Title']) if config['enable_mongodb']: db = Database(user_map(video_dict['User'])) db.insert(video_dict['Title'], share_url, video_dict['Date']) elif config['upload_by'] == 's3': if config['enable_mongodb']: db = Database(user_map(video_dict['User'])) db.insert(video_dict['Title'], f"gets3/{quote(video_dict['Title'])}", video_dict['Date']) else: raise RuntimeError(f'Upload {video_dict["Title"]} failed') bot(f"[下载提示] {video_dict['Title']} 已上传, 请查看https://matsuri.design/", user_config)
Example #12
Source File: summary.py From BatteryMonitor with GNU General Public License v2.0 | 6 votes |
def __init__(self): self.currenttime = time.localtime() printtime = time.strftime("%Y%m%d%H%M%S ", self.currenttime) self.logfile = open(config['files']['logfile'],'at',buffering=1) self.sampletime = time.time() self.prevtime = time.localtime() self.summary=loadsummary() # summary = open('/media/75cc9171-4331-4f88-ac3f-0278d132fae9/summary','w') # pickle.dump(hivolts, summary) # pickle.dump(lowvolts, summary) # summary.close() if self.summary['hour']['timestamp'][0:10] != printtime[0:10]: self.summary['hour'] = deepcopy(self.summary['current']) if self.summary['currentday']['timestamp'][0:8] != printtime[0:8]: self.summary['currentday'] = deepcopy(self.summary['current']) if self.summary['monthtodate']['timestamp'][0:6] != printtime[0:6]: self.summary['monthtodate'] = deepcopy(self.summary['current']) if self.summary['yeartodate']['timestamp'][0:4] != printtime[0:4]: self.summary['yeartodate'] = deepcopy(self.summary['current'])
Example #13
Source File: youtube.py From Auto_Record_Matsuri with MIT License | 6 votes |
def start_temp_daemon(): db = Database('Queues') while True: event = [] for target_url in db.select(): p = YoutubeTemp(target_url) event.append(p) p.daemon = True p.start() is_running = True while is_running: has_running = False for p in event: if p.is_alive(): has_running = True if not has_running: is_running = False logger.info('A check has finished.') sleep(config['sec'])
Example #14
Source File: OP_1_Connection.py From OP_Manager with MIT License | 6 votes |
def check_OP_Z_Connection(): connected = Image.new('1', (128, 64)) draw = ImageDraw.Draw(connected) draw.text((0, 25), "Connecting.....", font=getFont(), fill='white') displayImage(connected) if do_mount("OPZ"): connected = Image.new('1', (128, 64)) draw = ImageDraw.Draw(connected) draw.text((0, 25), "Connected", font=getFont(), fill='white') displayImage(connected) time.sleep(1) return True else: connected = Image.new('1', (128, 64)) draw = ImageDraw.Draw(connected) draw.text((0, 25), "No Connection!", font=getFont(), fill='white') displayImage(connected) config["USB_Mount_Path"] = "" time.sleep(1) return False
Example #15
Source File: OP_1_Connection.py From OP_Manager with MIT License | 6 votes |
def autoMountUnmontThread(): while 1: print("Unmount Checking Thread") # if config["OP_1_Mounted_Dir"] == "": # if do_mount("OP1"): # print("============ Thread OP1 Mounted ==============") # else: # print("============ Thread Waiting OP1 ==============") # if config["OP_Z_Mounted_Dir"] == "": # if do_mount("OPZ"): # print("============ Thread OPZ Mounted ==============") # else: # print("============ Thread Waiting OPZ ==============") # Device Mounted check for unmount if config["OP_1_Mounted_Dir"] != "": if not os.listdir(config["OP_1_Mounted_Dir"]): unmountdevice(config["OP_1_Mounted_Dir"]) config["OP_1_Mounted_Dir"] = "" print("============ Thread OP1 Auto Unmount==============") if config["OP_Z_Mounted_Dir"] != "": if not os.listdir(config["TargetOpZMountDir"]): unmountdevice(config["OP_Z_Mounted_Dir"]) config["OP_z_Mounted_Dir"] = "" print("============ Thread OPZ Auto Unmount==============") time.sleep(3)
Example #16
Source File: preprocessors.py From recaptcha-cracker with GNU General Public License v3.0 | 6 votes |
def colour_images(paths): for path in paths: if os.path.isfile(path) and os.path.getsize(path) > 0: filename, ext = os.path.splitext(path) image_size = "_{0}".format(config['image_size']) if image_size in filename: try: image = Image.open(path) if image.mode != "RGB": image = image.convert("RGB") image.save(filename + ext) except OSError: print("OSError caused by file at {0}".format(path)) continue # if OSError: # cannot identify image file occurs despite above checks, skip the image
Example #17
Source File: pip.py From BatteryMonitor with GNU General Public License v2.0 | 6 votes |
def findpip(self): """Scan ports to find PIP port""" self.pipport="" for dev in glob.glob(config['Ports']['pipport']): for i in range(2): try: self.openpip(dev) self.sendcmd("QID",18) if self.reply[1:15].decode('ascii','strict')==str(self.sn): self.pipport=dev break except serial.serialutil.SerialException: pass finally: self.port.close if self.pipport!="": break if self.pipport=="": raise serial.serialutil.SerialException("Couldn't find PIP sn {}".format(self.sn))
Example #18
Source File: run.py From Auto_Record_Matsuri with MIT License | 6 votes |
def gen_process(self): if config['youtube']['enable']: for user_config in config['youtube']['users']: y = Youtube(user_config) self.events_multi.append(y) if config['twitcasting']['enable']: for user_config in config['twitcasting']['users']: t = Twitcasting(user_config) self.events_multi.append(t) if config['openrec']['enable']: for user_config in config['openrec']['users']: o = Openrec(user_config) self.events_multi.append(o) if config['mirrativ']['enable']: for user_config in config['mirrativ']['users']: m = Mirrativ(user_config) self.events_multi.append(m) if config['bilibili']['enable']: for user_config in config['bilibili']['users']: b = Bilibili(user_config) self.events_multi.append(b)
Example #19
Source File: demandmanager.py From BatteryMonitor with GNU General Public License v2.0 | 6 votes |
def solaravailable(batdata): """Returns max amount of surpus solar energy available without using battery Power Calculates the difference between amount of power being consumed vesus power that could be consumed to get battery current=IBatZero""" ibatminuteav=batdata.ibatminute/batdata.ibatnuminmin batdata.ibatminute = 0.0 batdata.ibatnuminmin = 0 iavailable=(IBatZero-ibatminuteav) soc=1-batdata.socadj/config['battery']['capacity'] iavailable=iavailable+config['battery']['maxchargerate']* \ (soc-config['battery']['targetsoc'])*20 pwravailable=iavailable*batdata.batvoltsav[config['battery']['numcells']+1] # print (iavailable,soc,pwravailable) return pwravailable
Example #20
Source File: preprocessors.py From recaptcha-cracker with GNU General Public License v3.0 | 6 votes |
def resize_images(paths): for path in paths: if os.path.isfile(path) and os.path.getsize(path) > 0: filename, ext = os.path.splitext(path) image_size = "_{0}".format(config['image_size']) new_filename = filename + image_size + ext if not os.path.exists(new_filename) or os.path.getsize(new_filename) == 0: # if the file hasn't been resized # or the resized version is corrupt (i.e. zero size) if image_size not in filename: try: image = Image.open(path) image = image.resize(config['image_size_tuple']) image.save(filename + image_size + ext) except OSError: print("OSError caused by file at {0}".format(path)) continue # if OSError: # cannot identify image file occurs despite above checks, skip the image
Example #21
Source File: video_process.py From Auto_Record_Matsuri with MIT License | 6 votes |
def process_video(video_dict, user_config): """ 处理直播视频,包含bot的发送,视频下载,视频上传和存入数据库 :param video_dict: 含有直播视频数据的dict :param user_config: 用户配置 :return: None """ assert 'bot_notice' in user_config assert 'download' in user_config bot(f"[直播提示] {video_dict['Provide']}{video_dict.get('Title')} 正在直播 链接: {video_dict['Target']} [CQ:at,qq=all]", user_config) ddir = get_ddir(user_config) check_ddir_is_exist(ddir) logger = logging.getLogger('run.precess_video') logger.info(f'{video_dict["Provide"]} Found A Live, starting downloader') video_dict['Title'] = AdjustFileName(video_dict['Title']).adjust(ddir) if video_dict["Provide"] == 'Youtube': downloader(r"https://www.youtube.com/watch?v=" + video_dict['Ref'], video_dict['Title'], config['proxy'], ddir, user_config, config['youtube']['quality']) else: downloader(video_dict['Ref'], video_dict['Title'], config['proxy'], ddir, user_config) if config['enable_upload']: v = VideoUpload(video_dict, user_config) v.start()
Example #22
Source File: nn.py From recaptcha-cracker with GNU General Public License v3.0 | 6 votes |
def train_network(self, learning_rate, decay_rate, start_epoch=None): # weights_path = "weights/{0}-rerun-test.h5".format(learning_rate) # log_path = "logs/{0}-rerun-test".format(learning_rate) tensorboard = keras.callbacks.TensorBoard(log_dir=config['log_path'], histogram_freq=0, write_graph=True, write_images=False) checkpointer = keras.callbacks.ModelCheckpoint(filepath=config['weights_path'], verbose=1, save_best_only=True) self.model.fit_generator(self.next_train_batch(chunk_size=16), samples_per_epoch=int(self.train_size/5), nb_epoch=self.num_epochs, validation_data=self.next_validation_batch(chunk_size=32), nb_val_samples=int(self.validation_size/5), callbacks=[checkpointer, tensorboard]) # learning_rate = 0.001 # decay_rate = 0.001 # neural_net = NeuralNetwork(learning_rate, decay_rate)
Example #23
Source File: manager.py From flask-restful-example with MIT License | 6 votes |
def run(): """ 生产模式启动命令函数 To use: python3 manager.py run """ app.logger.setLevel(app.config.get('LOG_LEVEL', logging.INFO)) service_config = { 'bind': app.config.get('BIND', '0.0.0.0:5000'), 'workers': app.config.get('WORKERS', cpu_count() * 2 + 1), 'worker_class': 'gevent', 'worker_connections': app.config.get('WORKER_CONNECTIONS', 10000), 'backlog': app.config.get('BACKLOG', 2048), 'timeout': app.config.get('TIMEOUT', 60), 'loglevel': app.config.get('LOG_LEVEL', 'info'), 'pidfile': app.config.get('PID_FILE', 'run.pid'), } StandaloneApplication(app, service_config).run()
Example #24
Source File: OP_1_Connection.py From OP_Manager with MIT License | 5 votes |
def update_Current_Storage_Status(): currentStorageStatus["sampler"] = getFileCount(config["OP_1_Mounted_Dir"] + "/synth") currentStorageStatus["synth"] = getFileCount(config["OP_1_Mounted_Dir"] + "/drum") currentStorageStatus["drum"] = getFileCount(config["OP_1_Mounted_Dir"] + "/drum") return currentStorageStatus["sampler"], currentStorageStatus["synth"], currentStorageStatus["drum"] # ======== OPZ Mount/Unmount Helper Functions ===========
Example #25
Source File: OP_1_Connection.py From OP_Manager with MIT License | 5 votes |
def unmount_OP_1(): if getMountPath("OP1") != "": unmountDisplay = Image.new('1', (128, 64)) draw = ImageDraw.Draw(unmountDisplay) draw.text((30, 25), "Ejecting!", font=getFont(), fill='white') displayImage(unmountDisplay) unmountdevice(config["OP_1_Mounted_Dir"]) config["OP_1_Mounted_Dir"] = "" config["USB_Mount_Path"] = "" unmountDisplay = Image.new('1', (128, 64)) draw = ImageDraw.Draw(unmountDisplay) draw.text((30, 25), "Ejected", font=getFont(), fill='white') displayImage(unmountDisplay) time.sleep(1) return True elif os.path.isdir(config["OP_Z_Mounted_Dir"]): unmountdevice(config["OP_Z_Mounted_Dir"]) unmountDisplay = Image.new('1', (128, 64)) draw = ImageDraw.Draw(unmountDisplay) draw.text((15, 25), "Ejected", font=getFont(), fill='white') displayImage(unmountDisplay) time.sleep(1) return True else: unmountDisplay = Image.new('1', (128, 64)) draw = ImageDraw.Draw(unmountDisplay) draw.text((15, 25), "No Device to Eject", font=getFont(), fill='white') displayImage(unmountDisplay) time.sleep(1) return False # ============= OP1 Helper tools =================
Example #26
Source File: OP_1_Backup.py From OP_Manager with MIT License | 5 votes |
def copyToLocal(self): op1TapePath, op1AlbumPath = config["OP_1_Mounted_Dir"] + "/tape", config["OP_1_Mounted_Dir"] + "/album" # currentTimeFolder = savePaths["Local_Projects"] + "/" + self.getTime() currentTimeFolder = savePaths["Local_Projects"] + "/" + self.getLatestProjectName(savePaths["Local_Projects"]) forcedir(currentTimeFolder + "/album") forcedir(currentTimeFolder + "/tape") try: copy_tree(op1AlbumPath, currentTimeFolder + "/album") copy_tree(op1TapePath, currentTimeFolder + "/tape") except: # Connection broken, remove created folder shutil.rmtree(currentTimeFolder)
Example #27
Source File: OP_1_Connection.py From OP_Manager with MIT License | 5 votes |
def do_mount(device): if getMountPath(device) == "": try: print("-- device not mounted") mountpath = getmountpath(device) config["USB_Mount_Path"] = mountpath print (mountpath) if device == "OP1" and mountpath != "": print(config["TargetOp1MountDir"]) # config["TargetOp1MountDir"] = mountpath os.system("sudo mkdir -p " + config["TargetOp1MountDir"]) os.system("sudo chmod 0777 " + config["TargetOp1MountDir"]) mountdevice(config["USB_Mount_Path"], config["TargetOp1MountDir"]) elif device == "OPZ" and mountpath != "": print(config["TargetOpZMountDir"]) # config["TargetOp1MountDir"] = mountpath os.system("sudo mkdir -p " + config["TargetOpZMountDir"]) os.system("sudo chmod 0777 " + config["TargetOpZMountDir"]) mountdevice(config["USB_Mount_Path"], config["TargetOpZMountDir"]) except: return False return False else: return True # ======== OP1 Mount/Unmount Helper Functions ===========
Example #28
Source File: OP_1_Backup.py From OP_Manager with MIT License | 5 votes |
def copyOnlyTapesToLocal(self): op1TapePath, op1AlbumPath = config["OP_1_Mounted_Dir"] + "/tape", config["OP_1_Mounted_Dir"] + "/album" # currentTimeFolder = savePaths["Local_Projects"] + "/" + self.getTime() currentTimeFolder = savePaths["Local_Projects"] + "/" + self.getLatestProjectName(savePaths["Local_Projects"]) forcedir(currentTimeFolder + "/tape") try: copy_tree(op1TapePath, currentTimeFolder + "/tape") except: shutil.rmtree(currentTimeFolder)
Example #29
Source File: OP_1_Backup.py From OP_Manager with MIT License | 5 votes |
def loadProjectToOP1(self, localProjectPath): shutil.rmtree(config["OP_1_Mounted_Dir"] + "/tape") forcedir(config["OP_1_Mounted_Dir"] + "/tape") op1TapePath = config["OP_1_Mounted_Dir"] + "/tape" copy_tree(localProjectPath + "/tape", op1TapePath) if isdir(localProjectPath + "/album"): shutil.rmtree(config["OP_1_Mounted_Dir"] + "/album") forcedir(config["OP_1_Mounted_Dir"] + "/album") op1AlbumPath = config["OP_1_Mounted_Dir"] + "/album" copy_tree(localProjectPath + "/album", op1AlbumPath)
Example #30
Source File: UPS_Battery_Module.py From OP_Manager with MIT License | 5 votes |
def readVoltage(): if config["OP_1_Mounted_Dir"] == "RaspiUPS": return readVoltageRaspiUPS() if config["OP_1_Mounted_Dir"] == "ADS1115": return readVoltageADS1115() # return 4.2 #default max voltage