def POST(self): _input = web.input() if 'csrf_token' not in _input or _input.csrf_token != web.config._session.get('csrf_token'): raise web.HTTPError( "400 Bad request", {'Content-Type': 'text/html'}, 'Cross-site request forgery (CSRF) attempt (or stale browser form).') if 'order' in _input: try: username = web.config._session.username except: return render.index(None) try: db.insert_one({ '_lame': username, '_order': _input._order or '牛肉粉', '_wday': int(_input._wday), '_lunch': int(_input._lunch) }) except: pass return render.index(db.select_all(username)) else: username = _input.username.strip() if not username: return render.index(None) web.config._session.username = username return render.index(db.select_all(username))
def select_top_db(): db.open() dict = {} try: result = db.select_all() for row in result: if(not dict.has_key(row[1])): summary = MsgSummary() summary.msg = row[3] summary.prefix_msg = row[1] summary.time = row[2] summary.id_list = [row[0]] dict[row[1]] = [1, summary] else: dict[row[1]][0] += 1 dict[row[1]][1].id_list.append(row[0]) happenList = [] for k,v in dict.items(): happenList.append((v[0], v[1].time, v[1])) finally: db.db.close() print happenList happenList = sorted(happenList, key=itemgetter(0,1) , reverse=True) print happenList return happenList
def delete(): id_num = request.args.get('id_num') deleted_name = db.select_name_by_id(id_num) # 1: ok ; 0: error status_code = 1 error_info = "%s has been deleted!" % deleted_name result_code = db.user_delete_by_id(id_num) if result_code == 0: error_info = "id not exist" status_code = 0 res_status_tuple = ("res_status", error_info, status_code) # return redirect("/?error_info=%s" % (error_info)) # red_url = url_for('index', error_info=error_info) # return redirect(red_url) res_tuple = db.select_all() res_list = list(res_tuple) res_list.insert(0, res_status_tuple) res_json = json.dumps(res_list) # print "*" * 20 # print res_json # print "*" * 20 return res_json
def test_database_operations(self): #initialization of engine db.create_engine('test.db') #create Table db.update('drop table if exists User') db.update('create table User(id int primary key, name varchar(20),password varchar(20),gender varchar(8))') #insert r1 = db.insert('User',id=db.get_id(),name='user1',password='******',gender='male') r2 = db.insert('User',id=db.get_id(),name='user2',password='******',gender='female') r3 = db.insert('User',id=db.get_id(),name='user3',password='******',gender='male') self.assertEquals(r1,1) self.assertEquals(r2,1) self.assertEquals(r3,1) #test select r4 = db.select_one('select name from User where gender=?','male') r5 = db.select_all('select name from User where gender=?','male') self.assertIsInstance(r4,dict) self.assertIsInstance(r5,list) r6 = db.select_one('select name from User where gender=?','asldfkj') r7 = db.select_all('select name from User where gender=?','asldfkj') self.assertIsNone(r6) self.assertEquals(r7,[]) #test update r8 = db.update('update User SET gender=? where name=?','male','user1') r9 = db.update('update User SET gender=? where name=?','male','asdfas') r10 = db.update('update User SET name =? where gender=?','haha','male') self.assertEquals(r8,1) self.assertEquals(r9,0) self.assertEquals(r10,2) #test transactions with db.transaction(): db.insert('User',id=db.get_id(),name='user5',password='******',gender='female') db.insert('User',id=db.get_id(),name='user5',password='******',gender='male') r12 = db.select_all('select * from User where name=?','user5') self.assertEquals(len(r12),2) db.engine = None
def list(): """Gets commit history Returns: (list): List containing commit history, including commit_id, build_date, build_logs and url """ conn = db.create_connection(r"commit_history") return db.select_all(conn)
def send_json_form(request): """ Отправка JSON с комментариями """ json_obj = [] query_list = select_all(db_name="comment") for i in query_list: json_obj.append([i[0], i[7]]) return Response(json.dumps(json_obj), content_type='application/json')
def send_json_stat(request): """ Отправка JSON со статистикой комментариев по регионам """ json_obj = [] query_list = select_all('region') for i in query_list: if i[2] > 5: json_obj.append(i) return Response(json.dumps(json_obj), content_type='application/json')
def send_json(request): """ Отправка JSON со всеми заполнеными формами """ json_obj = select_all(db_name='comment') json_dict = {} j = 0 for fields in json_obj: j += 1 json_dict[str(j)] = fields return Response(json.dumps(json_dict), content_type='application/json')
def calculate(): sql = 'select * from animal_weights' results = db.select_all(sql) dates = [get_days(x['weigh_date'][:date_str_size]) for x in results] weights = [float(x['weight']) for x in results] x = np.array(dates) y = np.array(weights) print(x, y) A = np.vstack([x, np.ones(len(x))]).T a, b = np.linalg.lstsq(A, y, rcond=None)[0] return a, b
def send_json_form(request): """ Отправка JSON с комментариями """ json_obj = [] query_list = select_all(db_name="comment") for i in query_list: json_obj.append([i[0], i[7]]) return Response( json.dumps(json_obj), content_type='application/json' )
def menu(conn, key): cipher = crypt.read_key(key) while (1): print('\n') print("*******************************") print("[1] Search Passwords by website") print("[2] Add A Password") print("[3] Show All") print("[4] Exit") print("*******************************") option = input("Enter number of the option: ") if option == "1": web = input("Which website?") web = web.lower() rows = db.select_by_website(conn, web) if not rows: print("No password of ", web, " stored") else: display_pwds(cipher, rows) submenu(conn, cipher) elif option == "2": web = input("Which website? ") web = web.lower() user = input("What is your username? ") pwd = input( "What is your password? (enter 'a' for auto generated password) " ) if pwd == 'a': pwd = autopwd.autopwd() pwd = crypt.encrypt_pwd(cipher, pwd) db.create_entry(conn, (web, user, pwd)) print("password stored") elif option == "3": rows = db.select_all(conn) if not rows: print("no passwords stored yet") else: display_pwds(cipher, rows) submenu(conn, cipher) elif option == "4": print("Bye!") break else: #error handle print("no such option")
def animal_health(): sql = 'select * from animal_weights' results = db.select_all(sql) total_score = 0 for result in results: expected_weight = estimate_weight(result['weigh_date'][:date_str_size]) weight = float(result['weight']) daily_score = (1 - abs(expected_weight - weight) / expected_weight) * 100 print(expected_weight, weight, daily_score) total_score += daily_score health_score = total_score / len(results) return health_score
def send_json_stat(request): """ Отправка JSON со статистикой комментариев по регионам """ json_obj = [] query_list = select_all('region') for i in query_list: if i[2] > 5: json_obj.append(i) return Response( json.dumps(json_obj), content_type='application/json' )
def send_json(request): """ Отправка JSON со всеми заполнеными формами """ json_obj = select_all(db_name='comment') json_dict = {} j = 0 for fields in json_obj: j += 1 json_dict[str(j)] = fields return Response( json.dumps(json_dict), content_type='application/json' )
def add(): name = request.args.get('name') passwd = request.args.get('passwd') error_info = "%s has added succussfully." % name # 1: ok ; 0: error status_code = 1 # if name == "" or passwd == "": 前端可以做,后端也要做 # 前后端都要做数据校验 if name == "" or passwd == "": error_info = "name or password is empty." status_code = 0 else: result_code = db.user_add(name, passwd) if result_code == -1: error_info = "db error!" status_code = 0 elif result_code == 0: error_info = "changed %s's password." % name status_code = 1 else: # 1 error_info = "%s has been added." % name status_code = 1 res_status_tuple = ("res_status", error_info, status_code) # url_for ?error_info=str # red_url = url_for('index', error_info=error_info) # return redirect(red_url) res_tuple = db.select_all() res_list = list(res_tuple) res_list.insert(0, res_status_tuple) res_json = json.dumps(res_list) # print "*" * 20 # print res_json # print "*" * 20 return res_json
def add(): name = request.args.get('name') passwd = request.args.get('passwd') error_info = "%s has added succussfully." % name # 1: ok ; 0: error status_code = 1 # if name == "" or passwd == "": 前端可以做,后端也要做 # 前后端都要做数据校验 if name == "" or passwd == "": error_info = "name or password is empty." status_code = 0 else: result_code = db.user_add(name, passwd) if result_code == -1: error_info = "db error!" status_code = 0 elif result_code == 0: error_info = "changed %s's password." % name status_code = 1 else: # 1 error_info= "%s has been added." % name status_code = 1 res_status_tuple = ("res_status", error_info, status_code) # url_for ?error_info=str # red_url = url_for('index', error_info=error_info) # return redirect(red_url) res_tuple = db.select_all() res_list = list(res_tuple) res_list.insert(0, res_status_tuple) res_json = json.dumps(res_list) # print "*" * 20 # print res_json # print "*" * 20 return res_json
def GET(self): if 'username' in web.config._session: return render.index(db.select_all(web.config._session.username)) return render.index(None)
def test_select_all(self): result = db.select_all(self.conn) if isinstance(result, list): self.assertEqual(True, True)
def menu(): try: choice = input( "1) List users\n2) Add user\n3) Edit user\n4) Delete user\n5) Quit\nEnter Command> " ) choice = int(choice) if choice == 1: print("\nList Users\n") res = db.select_all("users") print( "username password full name\n---------------------------------------------------------------------" ) for row in res: print("{: <25} {: <25} {: <25}".format(*row)) print("\n") menu() elif choice == 2: print("\nAdd User\n") username = input("Username>") password = input("Password>") full_name = input("Full name>") print("\n") if not username: print("Failed to add user: username must be specified\n") menu() else: db.add_user(username, password, full_name) menu() elif choice == 3: print("\nEdit User\n") user_to_edit = input("\nUsername to edit>") cursor = db.connection.cursor() cursor.execute("select * from users where username='******';") res = cursor.fetchall() if not res: print("\nNo such user exists\n") print("\n") menu() else: password = input("New password (press enter to keep current)>") full_name = input( "New full name (press enter to keep current)>") print("\n") db.edit_user(user_to_edit, password, full_name) menu() elif choice == 4: print("\nDelete User\n") user_to_delete = input("\nEnter username to delete>") cursor = db.connection.cursor() cursor.execute("select * from users where username='******';") res = cursor.fetchall() if not res: print("\nNo such user exists\n") menu() else: answer = input("\nAre you sure that you want to delete " + user_to_delete + "? ") if answer is "Yes" or "Y": db.delete_user(user_to_delete) menu() elif choice == 5: print("\nGoodbye!\n") else: print("\n") menu() except Exception as error: print("\n") menu()
def find_by(cls,where,*args): """ Find by where clause and return list """ L = db.select_all('select * from `%s` %s' % (cls.__table__,where), *args) return [cls(**t) for t in L]
def find_all(cls): """ Find all and return list """ d = db.select_all('select * from `%s`' % cls.__table__) return [cls(**l) for l in d]
def list(): return render_template('list.html', site_title=site_title, l=db.select_all())
def index(): res_tuple = db.select_all() error_info = request.args.get('error_info') # print error_info return render_template('index.html', data=res_tuple, error=error_info)
def select_db(): db.open() try: db.select_all() finally: db.db.close()
def show_data(): if request.method == 'GET': return jsonify(db.select_all()) # select all persons in the table elif request.method == 'DELETE': # delete whole table return jsonify(db.del_all_pers())
def get_weights(): sql = 'select * from animal_weights' result = db.select_all(sql) print('result', result) return jsonify(result)
def get_all_movies(): return db.select_all()
def pred_emotion(): # 画像サイズ IMAGE_SIZE = (48, 48) # 画像を読み込む save_path = os.path.join(SAVE_DIR, "image.png") # pathを連結する img = load_img(save_path, target_size=IMAGE_SIZE) # 画像を読み込むと同時にリサイズ app.logger.debug(img) # ログ出力 # モデルを読み込む model = load_model('../model_epoch100.h5') # 画像をnumpy配列に変換 img = np.asarray(img) # グレースケール img_gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) img_gray = img_gray.reshape(-1, 48, 48, 1) / 255.0 # numpy配列の変形 -1:1列データ 48,48:縦横 1:要素1つ # 255で割って正規化。0-255 → 0-1の範囲になることで扱いやすくなる app.logger.debug(img) # ログ出力 app.logger.debug(img_gray) # ログ出力 # 予測させる pred = model.predict(img_gray) # [[0.7929875 0.20701244]] # 結果を表示(それぞれの表情の予測) print("Bad: ", pred[0][0]) print("Happy: ", pred[0][1]) bad = pred[0][0].astype(np.float64) happy = pred[0][1].astype(np.float64) app.logger.debug(pred) # ログ出力 response = { "bad": bad, "happy": happy, } # 今回判別させた画像を保存 img = Image.open(save_path) # PILで画像読み込み filepath = "image" + datetime.now().strftime("_%Y%m%d%H%M%S") + ".png" # ファイル名を指定 save_path = os.path.join(SAVE_DIR, filepath) # パスとファイル名を連結 img.save(save_path) # 画像を保存 con = get_db() pk = db.insert(con, filepath, bad, happy) # DBの中身を全件取得 results = db.select_all(con) # フロントエンドに判別の結果を返す return render_template( "index.html", predict = response, filepath = filepath, results = results )
def do_GET(self): if self.path=="/": self.path = "index.html" elif self.path == "/order/create": self.path = "order_create.html" elif self.path == "/order/viewall": self.path = "order_viewall" elif self.path == "/maintenance/viewall": self.path = "maintenance_viewall" elif self.path == "/qa/viewall": self.path = "qa_viewall" elif self.path == "/order/view": self.path = "order_view.html" elif self.path == "/maintenance/view": self.path = "maintenance_view.html" elif self.path == "/order/update": self.path = "order_update.html" elif self.path == "/maintenance/create": self.path = "maintenance_create.html" elif self.path == "/schedule": self.path = "schedule_create.html" elif self.path == "/qa/create": self.path = "qa_create.html" elif self.path == "/demand": self.path = "demand_viewall" elif self.path == "/product": self.path = "product_viewall" elif self.path == "/rawmaterials": self.path = "rawmaterials_viewall" elif self.path == "/schedule/view": self.path = "schedule_view.html" try: sendReply = False if self.path.endswith(".html"): mimetype = 'text/html' sendReply = True elif self.path == "order_viewall": orders = db.select_all("orders") for order in orders: product_name = db.get_product_name(order[1]) self.wfile.write(product_name) self.wfile.write(order) self.wfile.write("\n") elif self.path == "maintenance_viewall": self.print_query(db.select_all("maintenance")) elif self.path == "qa_viewall": self.print_query(db.select_all("qa")) elif self.path == "demand_viewall": self.print_query(db.select_all("demand")) elif self.path == "product_viewall": self.print_query(db.select_all("product")) elif self.path == "rawmaterials_viewall": self.print_query(db.select_all("rawmaterials")) if sendReply == True: f = open(curdir + sep + self.path) self.send_response(200) self.send_header('Content-type', mimetype) self.end_headers() self.wfile.write(f.read()) f.close() return except IOError: self.send_error(404, "File Not Found: %s" % self.path)