def connect_database(): engine = create_engine( 'mysql://' + config.get("HOME", "DATABASE_USER") + ':' + config.get("HOME", "DATABASE_PASSWORD") + '@' + config.get("HOME", "DATABASE_HOST") + ':' + config.get("HOME", "DATABASE_PORT") + '/' + config.get("HOME", "DATABASE_NAME"), echo=False) return engine
def update_document(data): remote = urllib2.urlopen(config.get(CONFIG_KEY, "url"), timeout=config.getint(CONFIG_KEY, "timeout")) whois_data = json.loads(remote.read()) try: if config.get(CONFIG_KEY, "overwrite_open"): # DEPRECATED if not data.get("state"): data["state"] = {} data["state"] = {"open": len(whois_data["users"]) > 0} except ConfigParser.NoOptionError: pass if config.get(CONFIG_KEY, "update_open"): if not data.get("state"): data["state"] = {} data["state"]["open"] = len(whois_data["users"]) > 0 or data["state"].get("open", False) if not data.get("sensors"): data["sensors"] = {} if not data["sensors"].get("people_now_present"): data["sensors"]["people_now_present"] = [] people_data = {"value": len(whois_data["users"])} if len(whois_data["users"]) > 0: people_data["names"] = whois_data["users"] data["sensors"]["people_now_present"].append(people_data) return data
def create_db(): print("Start creation of database") engine = create_engine( 'mysql://' + config.get("HOME", "DATABASE_USER") + ':' + config.get("HOME", "DATABASE_PASSWORD") + '@' + config.get( "HOME", "DATABASE_HOST") + ':' + config.get("HOME", "DATABASE_PORT") + '/', echo=False) engine.execute("CREATE DATABASE IF NOT EXISTS %s;" % config.get("HOME", "DATABASE_NAME")) engine.execute("USE %s" % config.get("HOME", "DATABASE_NAME")) Users.metadata.create_all(engine) return engine
def update_document(data): remote = urllib2.urlopen(config.get(CONFIG_KEY, 'url'), timeout=config.getint(CONFIG_KEY, 'timeout')) current_date = datetime.datetime.now() if not data.get('events'): data['events'] = [] components = vobject.readOne(remote) for event in components.contents['vevent']: # could be datetime or just date e_date = event.dtstart.value if type(e_date) is datetime.date: e_date = datetime.datetime.combine(e_date, datetime.time(0, 0)) else: e_date = e_date.replace(tzinfo=None) # compare with timezone data removed if e_date < current_date: continue data['events'].append({ 'name': event.summary.value, 'type': 'calendarevent', 'timestamp': int(time.mktime((event.dtstart.value.timetuple()))), 'extra': event.description.value, }) return data
def RetrievePassword(self, request, context): template = config.get('TEMPLATE_RETRIEVE_PASSWORD') msg = template.format(code=request.code, minute=request.minute) sms = Sms(tel=request.tel, msg=msg, sender=request.sender, type=Sms.TYPE.RetrievePassword) db.session.add(sms) db.session.commit() do_send_sms.apply_async(args=[sms.id]) return sms_pb2.SmsReply(uuid=sms.uuid)
def Captcha(self, request, context): template = config.get('TEMPLATE_CAPTCHA') msg = template.format(code=request.code, minute=request.minute) sms = Sms(tel=request.tel, msg=msg, sender=request.sender, type=Sms.TYPE.Captcha) db.session.add(sms) db.session.commit() do_send_sms.apply_async(args=[sms.id]) return sms_pb2.SmsReply(uuid=sms.uuid)
def VerifyPhone(self, request, context): template = config.get('TEMPLATE_VERIFY_PHONE') msg = template.format(code=request.code, minute=request.minute, company=request.company) sms = Sms(tel=request.tel, msg=msg, sender=request.sender, type=Sms.TYPE.VerifyPhone) db.session.add(sms) db.session.commit() do_send_sms.apply_async(args=[sms.id]) return sms_pb2.SmsReply(uuid=sms.uuid)
def update_document(data): remote = urllib2.urlopen(config.get(CONFIG_KEY, 'url'), timeout=config.getint(CONFIG_KEY, 'timeout')).read() remote = json.loads(remote) if not data.get('sensors'): data['sensors'] = {} lights_data = {} if config.get(CONFIG_KEY, 'update_open'): is_open = False if config.get(CONFIG_KEY, 'update_open_keys') == '*': keys_which_we_care_about = remote.keys() else: keys_which_we_care_about = config.get(CONFIG_KEY, 'update_open_keys').split(',') for key in keys_which_we_care_about: if remote[key]: is_open = True break if not data.get('state'): data['state'] = {} data['state']['open'] = is_open or data['state'].get('open', False) if not data['sensors'].get('ext_lights'): data['sensors']['ext_lights'] = [] lights = {} for key, val in config.items(CONFIG_KEY): if key.startswith('name_'): lights[val] = remote[key[5:]] data['sensors']['ext_lights'].append(lights) return data
def update_document(data): remote = urllib2.urlopen(config.get(CONFIG_KEY, 'url'), timeout=config.getint(CONFIG_KEY, 'timeout')).read() if not data.get('sensors'): data['sensors'] = {} lights_data = {} if config.get(CONFIG_KEY, 'update_open'): is_open = False i = 0 for m in config.get(CONFIG_KEY, 'update_open_lightmask'): if m == '1' and remote[i] == '1': is_open = True break i += 1 if not data.get('state'): data['state'] = {} data['state']['open'] = is_open or data['state'].get('open', False) if not data['sensors'].get('ext_lights'): data['sensors']['ext_lights'] = [] lights = {} for key, val in config.items(CONFIG_KEY): if key.startswith('name_'): lights[val] = remote[int(key[5:])] == '1' data['sensors']['ext_lights'].append(lights) return data
def update_document(data): remote = urllib2.urlopen(config.get(CONFIG_KEY, 'url'), timeout=config.getint(CONFIG_KEY, 'timeout')) remote = json.load(remote) if not data.get('sensors'): data['sensors'] = {} if not data['sensors'].get('temperature'): data['sensors']['temperature'] = [] if not data['sensors'].get('humidity'): data['sensors']['humidity'] = [] if not data['sensors'].get('radiation'): data['sensors']['radiation'] = {} data['sensors']['radiation']['beta_gamma'] = [] if not data['sensors'].get('barometer'): data['sensors']['barometer'] = [] temp = { 'value': '%.2f' % (float(remote[0]['datapoints'][0][0])), 'unit': '°C', 'location': 'Hardroom', } pressure = { 'value': '%.2f' % (float(remote[1]['datapoints'][0][0])), 'unit': 'hPA', 'location': 'Hardroom', } hum = { 'value': '%.2f' % (float(remote[2]['datapoints'][0][0])), 'unit': '%', 'location': 'Hardroom', } rad = { 'value': '%.2f' % (float(remote[3]['datapoints'][0][0])), 'unit': 'µSv/h', 'location': 'Hardroom', } data['sensors']['temperature'].append(temp) data['sensors']['barometer'].append(pressure) data['sensors']['humidity'].append(hum) data['sensors']['radiation']['beta_gamma'].append(rad) return data
def update_document(data): remote = urllib2.urlopen(config.get(CONFIG_KEY, 'url'), timeout=config.getint(CONFIG_KEY, 'timeout')) if not data.get('sensors'): data['sensors'] = {} if not data['sensors'].get('temperature'): data['sensors']['temperature'] = [] sensor = { 'value': float(remote.read()), 'unit': '°C', 'location': 'Inside', } data['sensors']['temperature'].append(sensor) return data
def do_send_sms(sms_id, retries=5): sms = get_or_none(Sms, sms_id) if not sms: return provider = get_provider(sms) if not provider: extra = dict(sms_id=sms_id, retries=retries, provider=provider) logger.error("Got a invalid provider", exc_info=True, extra=extra) return record = SmsRecord(sms_id=sms.id, provider_id=provider.id) result = send_sms(sms.tel, sms.msg, sms.sender, provider) if not result: retries -= 1 countdown = config.get('EXPIRE_TIME_FOR_FAILED_SEND_SMS') do_send_sms.apply_async(args=[sms_id, retries], countdown=countdown) if provider.param_msg_id in result: record.message_id = result[provider.param_msg_id] elif provider.param_error in result: record.error = result[provider.param_error] db.session.add(record) db.session.commit() check_sms_status_task.apply_async(args=[record.id])
from application.controller import success from application.logger import get_controller_logger from application import config from fastapi import APIRouter, UploadFile, File from util.common import md5hash app_name = config.get('APP_NAME') router = APIRouter() LOGGER = get_controller_logger('BASE') @router.get('/health') def health_check(): return success({ 'name': app_name, 'hash': md5hash(app_name), }) @router.post('/upload') async def upload_file(file: UploadFile = File(...)): filename = file.filename content = await file.read() decoded_content = content.decode('utf-8') LOGGER.info('Received file %s:\n%s' % ( filename, decoded_content )) return success({
from fastapi import FastAPI from application import router, config, logger from application.util import pfmt import sys from typing import Dict, Any import pprint """ USE os.getenv() TO GET ENV VARS IN dev.cfg OR prod.cfg """ env: str = config.get('ENV') app_name: str = config.get('APP_NAME') description: str = config.get('DESCRIPTION') version: str = config.get('VERSION') debug: bool = config.get_bool('DEBUG') fastapi_cfg: Dict[str, Any] = { 'debug': env != 'prod', 'title': app_name, 'description': description, 'version': version, 'is_debug': debug } # init app app = FastAPI(**fastapi_cfg) router.register_controllers(app) router.register_middlewares(app) LOGGER = logger.get_application_logger()