def admin_project_update_content_img(): id = request.form['id'] project = request.form['project'] try: if 'file' not in request.files: flash('No file part','danger') return redirect(request.url) file = request.files['file'] # if user does not select file, browser also # submit a empty part without filename if file.filename == '': flash('No selected file','danger') return redirect(request.url) if file and allowed_file(file.filename): filename = secure_filename(file.filename) file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename)) with connection.cursor() as cursor: update_img_name_query = "UPDATE {0}_back set img_name = %s WHERE id = %s".format(project) cursor.execute(update_img_name_query,(filename,id),) connection.commit() flash('You have updated successfully','success') return redirect(url_for('admin_project_gallery')) except Exception as e: print(str(e)) flash('You have not updated successfully','danger') return redirect(url_for('admin_project_gallery'))
def create_relation(user_1_id, user_2_id, relation_type): remove_relation(user_1_id, user_2_id) remove_relation(user_2_id, user_1_id) timestamp = int(time.time() * 1000) cursor.execute("insert into social values (?, ?, ?, ?)", [user_1_id, user_2_id, relation_type, timestamp]) connection.commit()
def start_game(game_id, user_2_id): timestamp = int(time.time() * 1000) db_game = cursor.execute( "select player_2_id, status, private from games where game_id = ?", [game_id] ).fetchone() if db_game[1] != "wait_for_opponent": return False if db_game[0] == None: cursor.execute( "update games set player_2_id = ? where game_id = ?", (user_2_id, game_id) ) cursor.execute( "update games set status = \"in_progress\", started = ?, last_activity = ? where game_id = ?", (timestamp, timestamp, game_id) ) connection.commit() players = cursor.execute( "select player_1_id, player_2_id from games where game_id = ?", [game_id] ).fetchone() games[game_id] = game(game_id, io, players[0], players[1]) io.emit("gameStart", room=games[game_id].room)
def post(self): data = UserRegistration.parser.parse_args() data['pwd'] = User.generate_hash(data['pwd']) create_users_table() insert_query = """INSERT INTO users (username, pwd, firstname, lastname, othernames, email, registered, isAdmin) VALUES (%s, %s, %s, %s, %s, %s, %s, %s);""" record_to_insert = list(data.values()) try: cursor.execute(insert_query, record_to_insert) connection.commit() access_token = create_access_token(identity=data['username']) return { 'status': 201, 'data': [{ 'token': access_token, 'user': data['username'] }] }, 201 # TODO: HANDLE ERROR BETTER -- 409 IF CONFLICT, 500 IF OTHER except (Exception, psycopg2.Error) as error: connection.rollback() return { 'status': 500, 'message': json.dumps(error, default=str) }, 500
def modify_tokens(user_id, formatted_token, remove): temp_tokens = valid_tokens(user_id) temp_tokens.remove(formatted_token) if remove else temp_tokens.append( formatted_token) cursor.execute("update users set valid_tokens = ? where user_id = ?", [json.dumps(temp_tokens), user_id]) connection.commit()
def move(self, user_id, column): if len(self.board.win_positions) > 0: return if self.board.board_full: return move = self.player_1_id if self.board.player_1 else self.player_2_id if user_id != move: return self.board.drop_fisje(column) io.emit("fieldUpdate", {"field": self.board.board}, room=self.room) now = int(time.time() * 1000) cursor.execute( "update games set last_activity = ?, moves = moves || ? || ',' where game_id = ?", [now, column, self.game_id]) connection.commit() if len(self.board.win_positions) > 0 or self.board.board_full: outcome = "d" if not self.board.board_full: winner = self.board.board[int(self.board.win_positions[0][0])] outcome = "w" if winner == "2" else "l" io.emit("finish", { "winPositions": self.board.win_positions, "boardFull": self.board.board_full }, room=self.room) self.close("finished", outcome) return io.emit("turnUpdate", {"player1": self.board.player_1}, room=self.room)
def admin_home_img(): if request.method == 'POST': caption = request.form['caption'] # check if the post request has the file part if 'file' not in request.files: flash('No file part','danger') return redirect(request.url) file = request.files['file'] # if user does not select file, browser also # submit a empty part without filename if file.filename == '': flash('No selected file','danger') return redirect(request.url) if file and allowed_file(file.filename): filename = secure_filename(file.filename) file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename)) with connection.cursor() as cursor: upload_img_name_query = "INSERT INTO home_page_img (img_name,img_caption) VALUES (%s,%s)" cursor.execute(upload_img_name_query,(filename,caption),) connection.commit() flash('New image/text uploaded','success') return redirect(request.url) return render_template('admin-home.html')
def cleanup(): now = int(time.time() * 1000) old_games = cursor.execute( "select game_id from games where (status = \"wait_for_opponent\" or status = \"in_progress\") and last_activity < ?", [now - 5 * 60 * 1e3]).fetchall() for game_id in old_games: cursor.execute("delete from games where game_id = ?", [game_id[0]]) connection.commit()
def update_asset(asset_id, asset): del asset["asset_id"] c = connection.cursor() query = "UPDATE assets SET %s=? WHERE asset_id=?" % "=?, ".join(asset.keys()) c.execute(query, asset.values() + [asset_id]) connection.commit() asset.update({"asset_id": asset_id}) asset.update({"is_active": is_active(asset)}) return asset
def createDocument(): try: with connection.cursor() as cursor: sql = "INSERT INTO document (text , employeeID) VALUES (%s, %s)" cursor.execute(sql , (request.form["text"] , request.form["employeeId"])) connection.commit() return jsonify({'isOK':True}) except: return jsonify({'isOK':False,'error':"someting went wrong"})
def insert_asset(asset): c = connection.cursor() c.execute( "INSERT INTO assets (%s) VALUES (%s)" % (", ".join(asset.keys()), ",".join(["?"] * len(asset.keys()))), asset.values(), ) connection.commit() asset.update({"is_active": is_active(asset)}) return asset
def added_user(): us = request.form.get("us") pa = request.form.get("pa") pq = request.form.get("pq") sql = f"insert into tbl_user(user_name, pass_word, phan_quyen) values(N'{us}', N'{pa}', {pq})" cursor.execute(sql) connection.commit() return redirect("/user")
def rename_shop_final(message): new_name = message.text old_name = cursor.execute( f"select name from shops where user_id = '{message.from_user.id}'" ).fetchall()[0][0] cursor.execute( f"update shops set name = '{new_name}' where name = '{old_name}'") update_state(RENAME_STATE, message, RENAME_CLOSE) connection.commit() bot.send_message(message.chat.id, 'Имя успешно изменено')
def start_command(message): clear_all_state(message) bot.send_message( message.chat.id, 'Привет, ты на универсальной платформе по доставке еды.\n' 'Достпуный список команд - /help') user_id = str(message.from_user.id) if [user_id] not in cursor.execute('select user_id from users').fetchall(): cursor.execute(f"insert into users (user_id) values ('{user_id}')") connection.commit()
def route(user_1_id, user_2_id): cursor.execute( "update social set type = \"friendship\" where user_1_id = ? and user_2_id = ?", [user_2_id, user_1_id]) connection.commit() io.emit("changedRelation", {"id": user_2_id}, room="user-" + user_1_id) io.emit("changedRelation", {"id": user_1_id}, room="user-" + user_2_id) return "", 200
def index(): # parse request data if the content-type header is set to application/json data = request.get_json() # force string if {}.get(...) returns None username = data.get("username") or "" email = data.get("email") or "" password = data.get("password") or "" # return 400 (malformed request) if any of the required data is missing if not username or \ not email or \ not password: return "", 400 # return 403 (forbidden) if any of the required data is invalid if not validate_username(username) or \ not validate_email(email) or \ not validate_password(password): return {"error": "form_data_invalid"}, 403 # check if username is taken if cursor.execute( "select username from users where lower(username) = lower(?)", [username]).fetchone(): return {"error": "username_taken"}, 403 # check if email is taken if cursor.execute("select email from users where email = ?", [email]).fetchone(): return {"error": "email_taken"}, 403 # create new user_id, hash password and note timestamp user_id = new_uuid("users") password_hash = passwords.password_hash(password) registered = int(time.time() * 1000) # write new user to database and commit cursor.execute( "insert into users values (?, ?, ?, NULL, NULL, ?, ?, \"[]\", FALSE, \"user\", \"{}\", ?) ", (user_id, username, email, password_hash, registered, bcrypt.gensalt())) connection.commit() # create a new token for the user to use for authentication new_token = token.generate_token() token.add_token(user_id, token.hash_token(new_token)) # create a flask response object to add the set-cookie header to res = make_response("", 200) res.set_cookie("token", new_token["token"], expires=int(new_token["expirationDate"] / 1000)) return res
def add_user(): if not request.json or 'username' not in request.json: abort(400) cursor.execute( f"insert into user (username, created_at) values('{request.json['username']}', '{datetime.now()}')" ) connection.commit() user_id = cursor.execute( f"select id from user where username='******'username']}'" ).fetchall()[0][0] return jsonify({'user_id': user_id})
def index(login): data = request.get_json() new_preferences = data.get("newPreferences") or "" formatted_json = format_preferences(new_preferences) cursor.execute("update users set preferences = ? where user_id = ?", [json.dumps(formatted_json), login]) connection.commit() return "", 200
def update_user(): user_id = request.args.get("user_id", type = int) us = request.form.get("user_name") pa = request.form.get("pass_word") pq = request.form.get("phan_quyen") print(us) sql = f"update tbl_user set user_name = N'{us}', pass_word = {pa}, phan_quyen = {pq} where user_id = {user_id}" cursor.execute(sql) connection.commit() return redirect("/user")
def dangky_dn(): us = request.form.get("us") pa = request.form.get("pa") sql = "INSERT INTO tbl_user (user_name, pass_word,phan_quyen) VALUES ('"+str(us)+"','"+str(pa)+"',"'0'")" # Executing a SQL query cursor.execute(sql) connection.commit() return redirect("/")
def create_game(user_1_id, private=False, user_2_id=None): timestamp = int(time.time() * 1000) game_id = new_uuid("games") cursor.execute( "insert into games values (?, NULL, \"\", ?, ?, NULL, ?, NULL, ?, NULL, NULL, NULL, \"wait_for_opponent\", \"default\", ?, FALSE) ", (game_id, user_1_id, user_2_id, timestamp, timestamp, private) ) connection.commit() return game_id
def dangki(): user_name = request.form.get("user_name") pass_word = request.form.get("pass_word") sql = "insert into tbl_user(user_name,pass_word) values( N'" + user_name + "', N'" + pass_word + "')" # Executing a SQL query cursor.execute(sql) connection.commit() return redirect("/login")
def index(user_id): data = request.get_json() status = data.get("status") or "" if not status: return "", 400 cursor.execute( "update users set status = ? where user_id = ?", [status[0:200], user_id] ) connection.commit() return "", 200
def create_shop_final(message): SHOP_DATA[message.from_user.id]['description'] = message.text cursor.execute( f"insert into shops (name, description, user_id) values ('{SHOP_DATA[message.from_user.id]['name']}'," f" '{SHOP_DATA[message.from_user.id]['description']}'," f" '{SHOP_DATA[message.from_user.id]['user_id']}')") connection.commit() bot.send_message( message.chat.id, f'Ресторан {SHOP_DATA[message.from_user.id]["name"]} успешно создан\n' f'Введите /panel для настройки меню ') update_state(CREATE_SHOP_STATE, message, CREATE_SHOP_CLOSE)
def post(): if request.method == 'POST': command = "INSERT INTO activity (staje, patientid, created) VALUES ('{}', {}, '{}')".format( str(request.json['staje']).upper(), request.json['patientid'], date_time_milliseconds()) cur.execute(command) connection.commit() return jsonify({ 'message': 'Succesfully posted activity', 'success': True, })
def withdrawFromAccount(transaction: dict) -> None: cursor = connection.cursor() try: createTransaction(transaction, cursor) statement = f"""update account set balance = balance - {transaction["txn_amount"]} where account_number = {transaction["account_number"]}""" cursor.execute(statement) connection.commit() cursor.close() except mysql.Error as err: print(err) raise finally: cursor.close()
def added_room(): name = request.form.get("name") price = request.form.get("price") decr = request.form.get("decr") for uploaded_file in request.files.getlist("file"): if uploaded_file.filename != "": print(uploaded_file.filename) uploaded_file.save(os.path.join("static/images", uploaded_file.filename)) sql = f"insert into tbl_room(room_name, room_price, room_decr) values(N'{name}', {price}, N'{decr}')" cursor.execute(sql) connection.commit() return redirect("/room")
def checkout_handler_final(message): order_data = message.text cursor.execute( f"update users set delivery_data='{order_data}' where user_id='{message.from_user.id}'" ) connection.commit() if USER_BASKET_DATA[message.from_user.id]: bot.send_message( message.chat.id, 'Данные успешно сохранены\nСейчас произойдет оформление заказа') checkout_handler(message) else: bot.send_message(message.chat.id, 'Данные успешно сохранены') update_state(COMPLETE_ORDER_DATA_STATE, message, ORDER_DATA_CLOSE)
def delete(): if "username" in session: id_sp = request.args.get("id_sp", type=int) sql = f"delete from tbl_sp where id_sp ={id_sp}" # Executing a SQL query cursor.execute(sql) connection.commit() return redirect("/product") else: return redirect("/login")
def close(self, new_status, outcome): cursor.execute( " ".join([ "update games set", "moves = moves || '0',", "duration = ?,", "status = ?,", "outcome = ?", "where game_id = ?" ]), [ int(time.time() * 1000) - cursor.execute("select started from games where game_id = ?", [self.game_id]).fetchone()[0], new_status, outcome, self.game_id ]) connection.commit() games.pop(self.game_id)
def delete_asset(asset_id): c = connection.cursor() c.execute("DELETE FROM assets WHERE asset_id=?", (asset_id,)) try: connection.commit() header = "Success!" message = "Deleted asset." return template('message', header=header, message=message) except: header = "Ops!" message = "Failed to delete asset." return template('message', header=header, message=message)
def shop_activate_s2(message): code = message.text if [code] in cursor.execute('select code from invite_codes').fetchall(): cursor.execute(f"delete from invite_codes where code = '{code}'") bot.send_message( message.chat.id, 'Вы успешно активировали свой ресторан, теперь вам доступна панель управления - /panel' ) cursor.execute( f"update users set is_shop = 'true' where user_id = '{message.from_user.id}'" ) connection.commit() update_state(ACTIVATE_STATE, message, ACTIVATE_CLOSE) else: bot.send_message(message.chat.id, 'Неверный код, попробуйте еще раз')
def update_room(): room_id = request.args.get("room_id", type = int) name = request.form.get("name") price = request.form.get("price") decr = request.form.get("decr") for uploaded_file in request.files.getlist("file"): if uploaded_file.filename != "": print(uploaded_file.filename) uploaded_file.save(os.path.join("static/images", uploaded_file.filename)) sql = f"update tbl_room set room_name = N'{name}', room_price= {price}, room_decr = N'{decr}' where room_id = {room_id}" cursor.execute(sql) connection.commit() return redirect("/room")
def update_asset(): c = connection.cursor() if (request.POST.get('asset_id', '').strip() and request.POST.get('name', '').strip() and request.POST.get('uri', '').strip() and request.POST.get('mimetype', '').strip() ): asset_id = request.POST.get('asset_id', '').strip() name = request.POST.get('name', '').decode('UTF-8') uri = request.POST.get('uri', '').strip() mimetype = request.POST.get('mimetype', '').strip() if not validate_uri(uri) and asset_folder not in uri: header = "Ops!" message = "Invalid URL. Failed to update asset." return template('message', header=header, message=message) try: duration = request.POST.get('duration', '').strip() except: duration = None try: input_start = request.POST.get('start', '') start_date = datetime.strptime(input_start, '%Y-%m-%d @ %H:%M') except: start_date = None try: input_end = request.POST.get('end', '').strip() end_date = datetime.strptime(input_end, '%Y-%m-%d @ %H:%M') except: end_date = None c.execute("UPDATE assets SET start_date=?, end_date=?, duration=?, name=?, uri=?, duration=?, mimetype=? WHERE asset_id=?", (start_date, end_date, duration, name, uri, duration, mimetype, asset_id)) connection.commit() header = "Yes!" message = "Successfully updated asset." return template('message', header=header, message=message) else: header = "Ops!" message = "Failed to update asset." return template('message', header=header, message=message)
def delete_asset(asset_id): c = connection.cursor() c.execute("DELETE FROM assets WHERE asset_id=?", (asset_id,)) try: connection.commit() # If file exist on disk, delete it. local_uri = path.join(asset_folder, asset_id) if path.isfile(local_uri): remove_file(local_uri) header = "Success!" message = "Deleted asset." return template('message', header=header, message=message) except: header = "Ops!" message = "Failed to delete asset." return template('message', header=header, message=message)
def process_schedule(): c = connection.cursor() if (request.POST.get('asset', '').strip() and request.POST.get('start', '').strip() and request.POST.get('end', '').strip() ): asset_id = request.POST.get('asset', '').strip() input_start = request.POST.get('start', '').strip() input_end = request.POST.get('end', '').strip() start_date = datetime.strptime(input_start, '%Y-%m-%d @ %H:%M') end_date = datetime.strptime(input_end, '%Y-%m-%d @ %H:%M') query = c.execute("SELECT mimetype FROM assets WHERE asset_id=?", (asset_id,)) asset_mimetype = c.fetchone() if "image" or "web" in asset_mimetype: try: duration = request.POST.get('duration', '').strip() except: header = "Ops!" message = "Duration missing. This is required for images and web-pages." return template('message', header=header, message=message) else: duration = "N/A" c.execute("UPDATE assets SET start_date=?, end_date=?, duration=? WHERE asset_id=?", (start_date, end_date, duration, asset_id)) connection.commit() header = "Yes!" message = "Successfully scheduled asset." return template('message', header=header, message=message) else: header = "Ops!" message = "Failed to process schedule." return template('message', header=header, message=message)
def delete_asset(asset_id): c = connection.cursor() c.execute("DELETE FROM assets WHERE asset_id=?", (asset_id,)) connection.commit()
def process_asset(): c = connection.cursor() if (request.POST.get('name', '').strip() and (request.POST.get('uri', '').strip() or request.files.file_upload.file) and request.POST.get('mimetype', '').strip() ): name = request.POST.get('name', '').decode('UTF-8') mimetype = request.POST.get('mimetype', '').strip() try: uri = request.POST.get('uri', '').strip() except: uri = False try: file_upload = request.files.file_upload.file except: file_upload = False # Make sure it is a valid combination if (file_upload and 'web' in mimetype): header = "Ops!" message = "Invalid combination. Can't upload web resource." return template('message', header=header, message=message) if (uri and file_upload): header = "Ops!" message = "Invalid combination. Can't select both URI and a file." return template('message', header=header, message=message) if uri: if not validate_uri(uri): header = "Ops!" message = "Invalid URL. Failed to add asset." return template('message', header=header, message=message) if "image" in mimetype: file = req_get(uri, allow_redirects=True) else: file = req_head(uri, allow_redirects=True) # Only proceed if fetch was successful. if file.status_code == 200: asset_id = md5(name + uri).hexdigest() strict_uri = file.url if "image" in mimetype: resolution = Image.open(StringIO(file.content)).size else: resolution = "N/A" if "video" in mimetype: duration = "N/A" else: header = "Ops!" message = "Unable to fetch file." return template('message', header=header, message=message) if file_upload: asset_id = md5(file_upload.read()).hexdigest() local_uri = path.join(asset_folder, asset_id) f = open(local_uri, 'w') asset_file_input = file_upload.read() f.write(asset_file_input) f.close() uri = local_uri start_date = "" end_date = "" duration = "" c.execute("INSERT INTO assets (asset_id, name, uri, start_date, end_date, duration, mimetype) VALUES (?,?,?,?,?,?,?)", (asset_id, name, uri, start_date, end_date, duration, mimetype)) connection.commit() header = "Yay!" message = "Added asset (" + asset_id + ") to the database." return template('message', header=header, message=message) else: header = "Ops!" message = "Invalid input." return template('message', header=header, message=message)