def get_active(): try: country = request.args.get('country') city = request.args.get('city') key = country.lower() + '_' + city.lower() state = redis_cli.get(key) if state: data = { "country": country, "city": city, "active": bool(eval(state)), "cache": "hit" } else: wl = Worklog(mysql, app.logger) js = wl.find_location(country, city) if js is None: data = {"mensaje": "Registro no encontrado"} else: redis_cli.set(key, escape(js[2])) data = { "country": js[0], "city": js[1], "active": bool(js[2]), "cache": "miss" } return jsonify(data) except: return jsonify({"mensaje": "Ha ocurrido un error, Verifique el URL."})
def get_location(): try: country = request.args.get('country') city = request.args.get('city') key = str(country) + '-' + str(city) active = redis_cli.get(escape(key)) if active: cache = "hit" country = request.args.get('country') city = request.args.get('city') return jsonify({"active": eval(active), "country":country, "city":city, "redis_cache":cache}) else: cache = "miss" country = request.args.get('country') city = request.args.get('city') wl = Worklog(mysql, app.logger) result = wl.obtain_location(escape(country), escape(city)) if result[0][2].find("True") != -1: active = True else: active = False redis_cli.set(str(key),escape(active)) return jsonify({"active": active, "country":result[0][0], "city":result[0][1], "redis_cache":cache}) except: return jsonify({"message":" Datos no Asociados"})
def put_active(): try: payload = request.get_json() auth = request.headers.get("authorization", None) if not auth: data = {"mensaje": "No ha enviado token"} elif auth != "Bearer 2234hj234h2kkjjh42kjj2b20asd6918": data = {"mensaje": "El token enviado no esta autorizado"} else: wl = Worklog(mysql, app.logger) res = wl.state_location(**payload) if res == 0: data = { "mensaje": "No se actualizo ningun registro", "token": auth, "country": payload['country'], "city": payload['city'], "active": payload['active'] } else: data = { "mensaje": "Registro actualizado satisfactoriamente", "token": auth, "country": payload['country'], "city": payload['city'], "active": payload['active'] } return jsonify(data) except: return jsonify({"mensaje": "Ha ocurrido un error, Verifique el URL."})
def get_active(): #try: country = request.args.get('country') city = request.args.get('city') key = country.lower() + '_' + city.lower() state = redis_cli.get(key) if state: response = { "country": country, "city": city, "active": bool(state), "cache": "hit" } else: wl = Worklog(mysql, app.logger) js = wl.find_location(country, city) if js is None: response = {"mensaje": "Registro no identificado"} else: redis_cli.set(key, escape(js[2])) response = { "country": js[0], "city": js[1], "active": bool(js[2]), "cache": "miss" } return jsonify(response)
def put_location(): try: payload = request.get_json() country = payload['country'] city = payload['city'] key = str(country) + '-' + str(city) auth = request.headers.get("Authorization", None) if not auth: return jsonify({"message": "No se ha enviado el Token"}) elif auth != "Bearer 2234hj234h2kkjjh42kjj2b20asd6918": return jsonify({"message": "Token no Autorizado!"}) else: wl = Worklog(mysql, app.logger) result = wl.update_location(**payload) if result == 1: redis_cli.delete(escape(key)) return jsonify({'result': 'Ok', 'update': payload}) else: return jsonify({ 'result': 'Fail', 'message': 'No se detecto ningun cambio al Actualizar' }) except: return jsonify({ 'result': 'ERROR', 'message': 'Ha ocurrido un error, verifique su request' })
def post_active(): try: payload = request.get_json() wl = Worklog(mysql, app.logger) wl.save_location(**payload) return jsonify({'payload': payload}) except: return jsonify('Error, Verifique URL.')
def post_location(): try: payload = request.get_json() wl = Worklog(mysql, app.logger) wl.save_location(**payload) return jsonify({'result':'Ok', 'Insert': payload}) except: return jsonify({'result':'ERROR', 'message':'Ha ocurrido un error, verifique su request'})
def post_quote(): try: payload = request.get_json() key = payload['country'].lower() + '_' + payload['city'].lower( ) + '_' + payload['sku'].lower() state = redis_cli.get(key) if state: js = json.loads(state) data = { "sku": js['sku'], "description": js['description'], "country": js['country'], "city": js['city'], "base_price": js['base_price'], "variation": js['variation'], "cache": "hit" } else: wl = Worklog(mysql, app.logger) clima = requests.get( 'http://api.openweathermap.org/data/2.5/weather?q=' + payload['city'] + ',' + payload['country'] + '&appid=3225ae99d4c4cb46be4a2be004226918').json() if clima['cod'] == "404": data = { "mensaje": "No existe informacion metereologica para " + payload['city'] } else: js = wl.find_rules(clima['weather'][0]['id'], **payload) if js is None: data = {"mensaje": "Registro no encontrado"} else: redis_cli.setex( key, 300, '{"sku":"' + js[0] + '","description":"' + js[1] + '","country":"' + js[2] + '","city":"' + js[3] + '","base_price":' + str(js[4]) + ',"variation":' + str(js[5]) + '}') data = { "sku": js[0], "description": js[1], "country": js[2], "city": js[3], "base_price": str(js[4]), "variation": str(js[5]), "cache": "miss" } return jsonify(data) except: return jsonify({"mensaje": "Ha ocurrido un error, Verifique el URL."})
def setUp(self): try: os.mkdir('data') testing = open('data/testing.md', 'w') testing.writelines( ["* 23:41 first entry\n", "* 23:42 last entry\n"]) testing.close() except FileExistsError: print("data directory is dirty.") self.worklog = Worklog('data/testing.md')
def put_active(): # try: payload = request.get_json() auth = request.headers.get("authorization", None) if not auth: return jsonify('Token no enviado') elif auth != "Bearer 2234hj234h2kkjjh42kjj2b20asd6918": return jsonify('El token no autorizado') else: wl = Worklog(mysql, app.logger) wl.state_location(**payload) return jsonify({'payload': payload, 'auth': auth})
def get_active(): vCountry = request.args.get('country') vCity = request.args.get('city') wl = Worklog(mysql, app.logger) js = wl.find_location(vCountry, vCity) if js is None: return jsonify('Registro no encontrado') else: return jsonify({ 'city': js[2], 'country': js[1], 'active': bool(js[3]) })
class WorklogTest(unittest.TestCase): def setUp(self): self.worklog = Worklog(worklog_file_name='test_work_log.csv') def test_creation(self): test_file_name = 'test_creation.csv' os.remove(test_file_name) Worklog(worklog_file_name=test_file_name) with open(test_file_name, 'r') as file: data = file.read() self.assertEqual(data, 'date,title,time spent,notes') def test_get_task_date(self): self.worklog.get_task_date()
def consultar(idSku): try: wl = Worklog(mysql, app.logger) js = wl.find_price(escape(idSku)) response = { "price": float(js[2]), "idSku": escape(idSku), "description": js[1], } return jsonify(response) except: return jsonify({"message": "Datos no asociados"})
def get_product_price(sku): try: wl = Worklog(mysql, app.logger) result = wl.get_price(escape(sku)) price = float(result[0][0]) description = str(result[0][1]) response = { "price": float(price), "sku": escape(sku), "description": description } return jsonify(response) except: return jsonify({"message":"No existen datos Asociados"})
def get_location(): try: country = request.args.get('country') city = request.args.get('city') wl = Worklog(mysql, app.logger) result = wl.obtain_location(escape(country), escape(city)) if result[0][2].find("True") != -1: active = True else: active = False return jsonify({"active": active, "country":result[0][0], "city":result[0][1]}) except: return jsonify({"message":"No existen datos Asociados"})
def main(): formatter = argparse.RawDescriptionHelpFormatter parser = argparse.ArgumentParser(formatter_class=formatter, description=BANNER) parser.add_argument('--file', dest='worklog', default=os.environ['WORKLOG'], help='Path to your Worklog.md file') parser.add_argument('--interval', dest='interval', default=3600, type=int, help='Interval (in Seconds) between logentries') parser.add_argument('start', default=False, type=bool, nargs="?") args = parser.parse_args() worklog = Worklog(args.worklog) frontend = ZenityFrontend logger = Logger(backend=worklog, frontend=frontend) if args.start: logger.today() while (True): logger.log() time.sleep(args.interval) else: if (sys.stdin.isatty()): logger.log() else: lines = (line.strip() for line in sys.stdin.readlines()) logger.log(suggestion=" ".join(lines))
def test_creation(self): test_file_name = 'test_creation.csv' os.remove(test_file_name) Worklog(worklog_file_name=test_file_name) with open(test_file_name, 'r') as file: data = file.read() self.assertEqual(data, 'date,title,time spent,notes')
def post_location(): try: payload = request.get_json() country = payload['country'] city = payload['city'] sku = payload['sku'] key = str(country) + '-' + str(city) + '-' + str(sku) info_cache = redis_cli.get(escape(key)) if info_cache: cache = "hit" js = json.loads(info_cache) price = float(js['base_price']) description = str(js['description']) variation= float(js['variation']) else: cache = "miss" r = requests.get('https://api.openweathermap.org/data/2.5/weather?q='+str(city)+','+str(country)+'&appid=3225ae99d4c4cb46be4a2be004226918') weather = r.json() wl = Worklog(mysql, app.logger) result = wl.obtain_condition(country, city, sku, weather['weather'][0]['id']) if(result): variation = float(result[0][0]) description = result[0][1] price = float(result[0][2]) else: result2 = wl.obtain_product(**payload) description = result2[0][0] price = float(result2[0][1]) variation = float(1.0) redis_cli.set(str(key), str('{"base_price": '+str(price)+', "description":"'+str(description)+'", "variation": '+str(variation)+'}')) #5 MINUTOS DE CACHE POR VARIABLE redis_cli.expire(str(key),300) return jsonify({ "sku": payload['sku'], "description": description, "country": payload['country'], "city": payload['city'], "base_price": price, "variation": variation, "redis_cache": cache}) except: return jsonify({'message':'No existen datos Asociados'})
def post_active(): try: payload = request.get_json() wl = Worklog(mysql, app.logger) js = wl.find_location(payload['country'], payload['city']) if js is None: wl.save_location(**payload) response = { "mensaje": "Registro guardado", "country": payload['country'], "city": payload['city'] } else: response = {"mensaje": "Registro existente"} return jsonify(response) except: return jsonify({"mensaje": "error"})
def get_price(sku): try: wl = Worklog(mysql, app.logger) js = wl.find_product(sku) if js is None: data = {"mensaje": "Registro no encontrado"} else: data = { "sku": js[0], "description": js[1], "base_price": str(js[2]) } return jsonify(data) except: return jsonify({"mensaje": "Ha ocurrido un error, Verifique el URL."})
class WorklogTest(unittest.TestCase): def setUp(self): try: os.mkdir("data") testing = open("data/testing.md", "w") testing.writelines(["* 23:41 first entry\n", "* 23:42 last entry\n"]) testing.close() except FileExistsError: print("data directory is dirty.") self.worklog = Worklog("data/testing.md") def tearDown(self): os.remove("data/testing.md") os.rmdir("data") def test_last(self): last = self.worklog.get_last() self.assertEqual("* 23:41 first entry\n", last[0]) self.assertEqual("* 23:42 last entry\n", last[1]) def test_header(self): self.worklog.today(location="MyLocation") my_header = self.worklog.get_last(4) self.assertEqual("# 01.02.2014 Saturday\n", my_header[0]) self.assertEqual("\n", my_header[1]) self.assertEqual("## (23:52 - 16:00)\n", my_header[2]) def test_append(self): self.worklog.append("this is my next") my_next = self.worklog.get_last() self.assertEqual("* 23:42 last entry\n", my_next[0]) self.assertEqual("* 23:52 this is my next\n", my_next[1])
class WorklogTest(unittest.TestCase): def setUp(self): try: os.mkdir('data') testing = open('data/testing.md', 'w') testing.writelines( ["* 23:41 first entry\n", "* 23:42 last entry\n"]) testing.close() except FileExistsError: print("data directory is dirty.") self.worklog = Worklog('data/testing.md') def tearDown(self): os.remove('data/testing.md') os.rmdir('data') def test_last(self): last = self.worklog.get_last() self.assertEqual('* 23:41 first entry\n', last[0]) self.assertEqual('* 23:42 last entry\n', last[1]) def test_header(self): self.worklog.today(location='MyLocation') my_header = self.worklog.get_last(4) self.assertEqual('# 01.02.2014 Saturday\n', my_header[0]) self.assertEqual('\n', my_header[1]) self.assertEqual('## (23:52 - 16:00)\n', my_header[2]) def test_append(self): self.worklog.append('this is my next') my_next = self.worklog.get_last() self.assertEqual('* 23:42 last entry\n', my_next[0]) self.assertEqual('* 23:52 this is my next\n', my_next[1])
def post_quote(): #try: payload = request.get_json() key = payload['country'].lower() + '-' + payload['city'].lower( ) + '-' + payload['sku'].lower() cache = redis_cli.get(key) if cache: js = json.loads(cache) response = { "sku": js['sku'], "country": js['country'], "city": js['city'], #"price": js['price'], #"var": js['var'], "cache": "hit" } return jsonify(response) else: weather = requests.get( 'http://api.openweathermap.org/data/2.5/weather?q=' + payload['city'] + ',' + payload['country'] + '&appid=3225ae99d4c4cb46be4a2be004226918').json() wl = Worklog(mysql, app.logger) js = wl.find_rules(weather['weather'][0]['id'], **payload) redis_cli.setex( key, 300, '{"country":"' + js[0] + '","city":"' + js[1] + '","sku":"' + js[2] + '","min":"' + str(js[3]) + '","max":"' + str(js[4]) + '","var":"' + str(js[5]) + '","description":"' + js[6] + '","price":' + str(js[7]) + '}') return jsonify({ 'cache': 'miss', 'country': js[0], 'city': js[1], 'sku': js[2], 'min': str(js[3]), 'max': str(js[4]), 'var': str(js[5]), 'price': str(js[7]), 'description': js[6] })
def setUp(self): try: os.mkdir("data") testing = open("data/testing.md", "w") testing.writelines(["* 23:41 first entry\n", "* 23:42 last entry\n"]) testing.close() except FileExistsError: print("data directory is dirty.") self.worklog = Worklog("data/testing.md")
def post_active(): try: payload = request.get_json() wl = Worklog(mysql, app.logger) js = wl.find_location(payload['country'], payload['city']) if js is None: wl.save_location(**payload) data = { "mensaje": "Registro guardado satisfactoriamente", "country": payload['country'], "city": payload['city'] } else: data = {"mensaje": "El registro ya existe en la base de datos"} return jsonify(data) except: return jsonify({"mensaje": "Ha ocurrido un error, Verifique el URL."})
def get_active(): try: country = request.args.get('country') city = request.args.get('city') wl = Worklog(mysql, app.logger) js = wl.find_location(country, city) if js is None: data = {"mensaje": "Registro no encontrado"} else: data = { "country": js[0], "city": js[1], "active": bool(js[2]) } return jsonify(data) except: return jsonify({"mensaje": "Ha ocurrido un error, Verifique el URL."})
def put_active(): try: payload = request.get_json() auth = request.headers.get("authorization", None) if not auth: return jsonify('Token no enviado') elif auth != "Bearer 2234hj234h2kkjjh42kjj2b20asd6918": return jsonify('Token no autorizado') else: wl = Worklog(mysql, app.logger) wl.state_location(**payload) response = { "mensaje": "Registro actualizado", "token": auth, "country": payload['country'], "city": payload['city'], "active": payload['active'] } return jsonify(response) except: return jsonify({"mensaje": "error"})
""" run.py ---------- Module runs worklog for the PWD-Techdegree-Project-3 cli tool. """ from worklog import Worklog if __name__ == '__main__': """Runs WorkLog process starting with main menu""" Worklog().main_menu()
def setUp(self): self.worklog = Worklog(worklog_file_name='test_work_log.csv')
from worklog import Worklog time_manager = Worklog() time_manager.menu()
# Aaron Pope # 09/01/2018 # Treehouse TechDegree - Python, Unit 3: Work Log from menus import lookup_menu from menus import main_menu from utils import clear_screen from utils import continue_prompt from utils import exit_check from worklog import Worklog if __name__ == '__main__': clear_screen() worklog = Worklog() while True: selection = main_menu.get_menu_selection( "What would you like to do?\n") exit_check(selection) if selection == "A": worklog.add_new_entry() elif selection == "C": worklog.clear_entries() elif len(worklog.entries) == 0: clear_screen() print("This worklog does not yet contain any entries.") print("Please go add some before searching!") continue_prompt() else: