def planning_reader(self, file_name): DB.clear_table() with open(file_name, 'r') as file: self.CSV_read = csv.reader(file, delimiter=';') for line in self.CSV_read: new_record = tuple(line) DB.insert_transport_data(new_record)
def p4f_reader(self, file_name): with open(file_name, 'r') as file: self.CSV_read = csv.reader(file, delimiter=';') for line in self.CSV_read: try: DB.update_transport_data(int(line[1]),line[20], line[25]) except: pass
def get_rating(): if not request.json: return jsonify({'error': 'Empty request'}) db = DB() table = Rating(db.get_connection()) table.init_table() if request.json['operation'] == 'get5': return jsonify({'res': table.return_first_5()}) elif request.json['operation'] == 'get_user': return jsonify({'res': table.find_user(request.json['user'])}) elif request.json['operation'] == 'post': table.add_user(request.json['user'], request.json['result'])
def NombreVisibleUsuario(self): NombrePene = DB().run( "SELECT Nombrevisible_Usuario FROM Usuario WHERE idUsuario = ('%s')" % (self.Usuario_idUsuario)) for item in NombrePene: NombrePenesito = item["Nombrevisible_Usuario"] return NombrePenesito
def Insert(self): cursor = DB().run( "INSERT INTO Post (Fecha_Creacion_Post, Descripcion_Post, Ubicacion_Post, " "Usuario_idUsuario,URL_Post) VALUES ('%s', '%s', '%s', '%s', '%s')" % (self.Fecha_Creacion_Post, self.Descripcion_Post, self.Ubicacion_Post, self.Usuario_idUsuario, self.URL_post)) self.idPost = cursor.lastrowid
def getOriginalData(city_number): operation = DB.operateDB() originalDic = {} originalData = [] tempList = [] results = operation.getAllLink() sceneryRS = operation.sreachSceneryName() sceneryList = [] for scenery in sceneryRS: sceneryList.append(scenery[0]) i = 0 for result in results: if result[1] not in sceneryList: continue if i != result[0]: i = result[0] if len(tempList) > 1: originalData.append(tempList) tempList = [] tempList.append(result[1]) if result[1] not in originalDic: originalDic[result[1]] = 1 else: originalDic[result[1]] += 1 originalData.append(tempList) ListDic = sorted(originalDic.items(), key=lambda x: x[1], reverse=True) return ListDic, originalData
def main(event, context): db = DB('innodb') db.dropTables() print('[INFO]: Tables have been dropped!') db.createTables() print('[INFO]: Tables have been created!') print('[INFO]: DONE!')
def TraerObjeto(self, idComment): Cursor = DB().run("SELECT * FROM Comment WHERE idComment = ('%s')" % (idComment)) for item in Cursor: self.idComment = item["idComment"] self.Post_idPost = item["Post_idPost"] self.Usuario = item["Usuario_idUsuario"] self.Descripcion = item["Descripcion_Comment"] self.ObjetizarIdUsuario()
def TraerObjeto(self, idPost): Cursor = DB().run("SELECT * FROM Post WHERE idPost = ('%s')" % (idPost)) for item in Cursor: self.idPost = item["idPost"] self.Fecha_Creacion_Post = item["Fecha_Creacion_Post"] self.Descripcion_Post = item["Descripcion_Post"] self.Ubicacion_Post = item["Ubicacion_Post"] self.Usuario_idUsuario = item["Usuario_idUsuario"] self.URL_post = item["URL_Post"]
def run(self): print("recv handler start...") while self.is_connect_to_server: # CLIENT___________________________________________________ # инициализируем и чистим значения при последующих циклах pack = [] # сборка цепочки сообщений size_next_mess = 0 current_message = cnf.init_ntuple_data_message() msg = None try: msg = self.sock.recv(cnf.SIZE_HEADER) except: er_message_box("reset connect") DB().mess_to_log("reset connect...") self.close_session() return print("new message... ", msg) if not msg: self.close_session() return current_message = cnf.from_bytes_get_data_message(bytes(msg)) if not current_message: self.close_session() return self._add_to_packet_from_main_header_(current_message) while current_message.size_next > 0: current_message = cnf.from_bytes_get_data_message( bytes(self.sock.recv(size_next_mess))) if not current_message or self.check_mess(current_message): DB().mess_to_log( "dont have data or is not good...\n -->> ", current_message) self.close_session() return else: pack.append(current_message.data) print("принято!!!") self._add_datas_in_packet_(pack) self._analise_packet_(self.packet) pass pass #ошибка: разрыв соединения
def Likecito(): if 'User' in session: LikeLike = Like() UsuarioLike = Usuario() UsuarioLike.TraerObjeto(session['User']) idPosta = request.args.get("IdPost") idUserinho = UsuarioLike.idUsuario LikeLike.AllSets(idPosta, idUserinho) cursor = DB().run( "SELECT * FROM `Like` WHERE Post_idPost = ('%s') AND Usuario_idUsuario = ('%s') " % (idPosta, idUserinho)) if len(cursor.fetchall()) == 0: LikeLike.Insert() else: DB().run( "DELETE FROM `Like` WHERE Post_idPost = ('%s') AND Usuario_idUsuario = ('%s')" % (idPosta, idUserinho)) return redirect("/Inicio#p" + idPosta) else: return redirect("/")
def getScenery(labelList): dictScenery = {} sceneryData = [] operation = DB.operateDB() for label in labelList: result = operation.sreachSceneryByLabel(label) for r in result: if r[0] not in sceneryData: sceneryData.append(r[0]) dictScenery[r[0]] = dictScenery.get(r[0], 0) + 1 return sceneryData, dictScenery
def TraerObjeto(self, Usuario): Cursor = DB().run( "SELECT * FROM Usuario WHERE Nombre_Usuario = ('%s')" % (Usuario)) for item in Cursor: self.idUsuario = item["idUsuario"] self.Nombre = item["Nombre_Usuario"] self.Email = item["Email_Usuario"] self.Contrasena = item["Contraseña_Usuario"] self.FechaIngreso = item["Fecha_ingreso_Usuario"] self.NombreVisible = item["Nombrevisible_Usuario"] self.Biografia = item["Biografia_Usuario"]
def check_mess(self, mess): """ проверяет, что поля cmd и sender соответствуют данным из текущего пакета :param mess: :return: """ if mess[0] != self.packet.id: DB().mess_to_log("dont match id") return False if mess[1] != self.packet.cmd: DB().mess_to_log("dont match cmd") return False if mess[2] != self.packet.sender: DB().mess_to_log("dont match sender") return False if mess[3] != self.packet.recv: DB().mess_to_log("dont match receiver") return False return True
def BorrarComentarios(): if 'User' in session: UsuarioBorrarComentario = Usuario() UsuarioBorrarComentario.TraerObjeto(session['User']) idPosta = request.args.get("IdPost") idUserinho = UsuarioBorrarComentario.idUsuario idComment = request.args.get("IdComment") DB().run( "DELETE FROM Comment WHERE idComment = ('%s') AND Usuario_idUsuario = ('%s') AND Post_idPost = ('%s')" % (idComment, idUserinho, idPosta)) return redirect("/Inicio#p" + idPosta) else: return redirect("/")
def Inicio(): if 'User' in session: UsuarioInicio = Usuario() UsuarioInicio.TraerObjeto(session['User']) cursorsito = DB().run("SELECT * FROM Usuario") for itemsito in cursorsito: if itemsito["Nombre_Usuario"] == None: UsuarioInicio.TraerObjeto(itemsito["idUsuario"]) UsuarioInicio.DeleteManual() Usuariohtml = UsuarioInicio.TraerObjeto(session['User']) PostSeleccionado = [] CommentSeleccionado = [] cursor = DB().run("SELECT * FROM Post ORDER BY(idPost)DESC") for item in cursor: PostInicio = Post() PostInicio.TraerObjeto(item["idPost"]) PostInicio.Contador() PostSeleccionado.append(PostInicio) cursor2 = DB().run("SELECT * FROM `Like`") LikesExistentes = [] for item2 in cursor2: LikeInicio = Like() LikeInicio.TraerObjeto(item2["Post_idPost"], item2["Usuario_idUsuario"]) LikesExistentes.append(LikeInicio) cursor3 = DB().run("SELECT * FROM Comment ORDER BY(idComment)ASC") for item3 in cursor3: CommentInicio = Comment() CommentInicio.TraerObjeto(item3["idComment"]) CommentSeleccionado.append(CommentInicio) return render_template("VerPost.html", PostSeleccionado=PostSeleccionado, LikesExistentes=LikesExistentes, Usuariohtml=Usuariohtml, UserIniciado=UsuarioInicio, CommentSeleccionado=CommentSeleccionado) elif 'User' not in session: return redirect("/")
def show_rating(): db = DB() table = Rating(db.get_connection()) table.init_table() rows = table.return_all_lines() res = '''<!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous"> <title>Привет, Яндекс!</title> </head> <body> <table class="table"> <tbody>''' for i in range(len(rows)): if i == 0: elem = '<tr class="table-warning">' elif i == 1: elem = '<tr class="table-secondary">' elif i == 2: elem = '<tr class="table-danger">' else: elem = '<tr>' elem += '<td>{}</td><td>{}</td><td>{}</td>'.format( str(i + 1), rows[i][1], str(rows[i][2])) elem += '</tr>' res += elem res += '''</tbody> </table> </body> </html>''' return res
def data_split(self): data = DB.get_data() self.headers = data[0] del data[0] for line in data: if line[10] == None: self.geen_mail.append(line) elif '@' and '.' not in line[10]: self.geen_mail.append(line) elif line[6] == 'Niet gepland': self.niet_gepland.append(line) elif line[5] == 'privé': self.wel_gepland_prv.append(line) else : self.wel_gepland.append(line)
def getLabel(): labels = request.form.getlist("labels[]") # 由于返回什么就写什么 # 调用标签找景点的模块 results = mf.main(labels) json_list = [] if len(results) != 0: operation = DB.operateDB() for result in results: json_dict = {} json_dict['scenery_name'] = result[0] r = operation.sreachPostion(json_dict['scenery_name']) if len(r) > 1: logger.warning('该景点有两个以上的经纬度,先返回一个') json_dict['longitude'] = r[0][0] json_dict['latitude'] = r[0][1] json_list.append(json_dict) return json.dumps(getShortScenery(json_list)) # 要有返回值
def index(): operation = DB.operateDB() results = operation.sreachSceneryAndPostion() num = len(results) json_list = [] for i in range(num): json_dict = {} json_dict['scenery_name'] = results[i][0] json_dict['longitude'] = results[i][1] json_dict['latitude'] = results[i][2] if i < int(num / 3) + 1: json_dict['flag'] = '2' elif i < int(num / 3 * 2) + 1: json_dict['flag'] = '1' else: json_dict['flag'] = '0' json_list.append(json_dict) return render_template('index.html', result=json.dumps(json_list))
def xml_parser(xml_file): ''' 解析xml文件内容,并将获取到的用户信息存入数据库(dict->database). 1.通过xml解析xml文件内用户信息部分。(<Buddy>) 2.将信息转换并存入数据库。(item.attrib ->dict) ''' print('开始文件解析') content = ET.parse(xml_file) root = content.getroot() for item in root: buddy_content = item.attrib key_list = [] value_list = [] for key, value in buddy_content.items(): key_list.append(key) value_list.append(value) DB('feiq.db', key_list, value_list) print(f'解析完毕,共解析{len(root)}条信息')
def init_table(self): self.setGeometry(530, 350, 1300, 800) self.data_list = DB.get_data() self.table = QtWidgets.QTableWidget(self) self.table.setRowCount(len(self.data_list)) self.table.setColumnCount(len(self.data_list[0])) hor_headers = window.Trans_Reader.headers self.table.setHorizontalHeaderLabels(hor_headers) self.data_to_table() self.table.resizeColumnsToContents() self.table.resizeRowsToContents() grid_box = QtWidgets.QVBoxLayout() grid_box.addWidget(self.table, 100) self.setLayout(grid_box)
def close_session(self): Recv_Handler_cl.is_connect_to_server = False er_message_box("reset connect... (((") DB().mess_to_log("reset connect...") self.sock.close()
def UpdateContrasena(self, contrasena): self.SetContrasena(contrasena) DB().run( "UPDATE Usuario SET Contraseña_Usuario = ('%s') WHERE idUsuario = ('%s')" % (self.Contrasena, self.idUsuario))
from flask import * from DataBase import DB from Usuario import Usuario from Post import Post from Like import Like from Comment import Comment import os from werkzeug.utils import secure_filename DB().SetConnection('127.0.0.1', 'root', 'alumno', 'mydb') UPLOAD_FOLDER = 'static/img/' app = Flask(__name__, static_url_path='/static') app.secret_key = b'Tubidaor' APP_ROOT = os.path.dirname(os.path.abspath(__file__)) ALLOWED_EXTENSIONS = {('png', 'jpg', 'jpeg')} app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER @app.route("/", methods=['GET', 'POST']) def Logeoin(): return render_template("helloworld.html") @app.route("/LogOut", methods=['GET', 'POST']) def Logueoout(): if 'User' in session: UsuarioLogOut = Usuario() UsuarioLogOut.RegistroSinInsert(None, None, None, None, None) session.pop('User', None) return redirect("/")
def UpdateBiografia(self, Bio): self.SetBiografia(Bio) DB().run( "UPDATE Usuario SET Biografia_Usuario = ('%s') WHERE idUsuario = ('%s')" % (self.Biografia, self.idUsuario))
def UpdateNombreVisible(self, Nombre): self.SetNombreVisible(Nombre) DB().run( "UPDATE Usuario SET Nombrevisible_Usuario = ('%s') WHERE idUsuario = ('%s')" % (self.NombreVisible, self.idUsuario))
def DeleteManual(self): DB().run("DELETE FROM Usuario WHERE idUsuario = ('%d')" % (self.idUsuario))
def Insert(self): cursor = DB().run( "INSERT INTO Usuario (Nombre_Usuario, Contraseña_Usuario, Email_Usuario, Fecha_ingreso_Usuario, Nombrevisible_Usuario, Biografia_Usuario) VALUES ('%s', '%s', '%s', '%s', '%s', '%s')" % (self.Nombre, self.Contrasena, self.Email, self.FechaIngreso, self.NombreVisible, self.Biografia)) self.idUsuario = cursor.lastrowid
from flask import Flask, redirect, render_template, session, request, url_for from flask_bootstrap import Bootstrap from forms import LoginForm, RegistrationForm, SelfForm, AddNewsForm from DataBase import DB, NewsModel, UserModel app = Flask(__name__) app.config['SECRET_KEY'] = 'no_secret_key' bootstrap = Bootstrap(app) db = DB() @app.route('/') def nothing(): return redirect("/logout") @app.route('/login', methods=['GET', 'POST']) def login(): form = LoginForm() user_name = form.user_name password = form.password self = render_template('login.html', title='Авторизация', form=form) if request.method == 'GET': return self elif request.method == 'POST': if not (request.form.get('user_name') and request.form.get('password')): return self # make error введите данные