def save(self, w2req): w2changes: List = w2req.get('changes', None) pkey = self.primarycol.model_column model = self.primarycol.model_column.class_ updates = [] try: for row in w2changes: recid = row['recid'] if recid < 0: record = model() else: record = session.query(model).filter(pkey == recid).first() for k, v in row.items(): if k != 'recid': w2c = self.w2columns[k] setattr(record, w2c.model_column.key, v) if recid < 0: session.add(record) session.flush() newid = getattr(record, pkey.key) updated_row = self.query.filter(pkey == newid).first() else: updated_row = self.query.filter(pkey == recid).first() updates.append( dict(recid=recid, record=self.row_as_dict(updated_row))) session.commit() return jsonify(dict(status="success", updates=updates)) except SQLAlchemyError as e: session.rollback() return jsonify(dict(status="error", message=str(e)))
def newItem(): """This page will be for adding a new item.""" error=None login_already=current_user.is_authenticated() # This function will return to homepage if it found user is not login. # There are same setting in pages below which are able to edit the database. if login_already: if request.method == "POST": error = vacant_input() if not error: """go on input database if no empty imput. If there any, reload and labels of the empty form will turn red.""" time_now=datetime.now().strftime("%Y-%m-%d %H:%M:%S") """ Get currunt time and insert to create_time. This will use for index items display order""" i = Item(create_time=time_now, name=request.form['name'], discription=request.form['discription'], category=request.form['category']) session.add(i) session.flush() i.photo=upload_image(i.id) session.commit() return redirect("/") c = session.query(Category).all() return render_template("add.html", c=c, login_already=login_already, error=error) c = session.query(Category).all() return render_template("add.html", c=c, login_already=login_already, error=error) else: return redirect("/")
def get_or_create_position(session, admin_position): position = session.query(Position).filter( Position.position_type == admin_position).one_or_none() if position: return position.id position = Position(position_type=admin_position) session.add(position) session.flush() return position.id
def create_trials(participant_id, staff_id, copy_trial_id, recall_trial_id, trial_start_time, trial_end_time): trialsInfo=trials(participantID=participant_id, userName=staff_id, copyTrialID=int(copy_trial_id), recallTrialID=int(recall_trial_id), trialStartTime=trial_start_time, trialEndTime=trial_end_time) session.add(trialsInfo) session.flush() session.commit() print("Trial has been created")
def create_copy_trial(participant_id, copy_trial_pixels, copy_trial_start_time, copy_trial_end_time, staff_id): copy_trialInfo=copy_trial(copyTrialPixels=copy_trial_pixels, copyTrialStartTime=copy_trial_start_time, copyTrialEndTime=copy_trial_end_time) session.add(copy_trialInfo) session.flush() inserted_id = copy_trialInfo.copyTrialID session.commit() print("Copy Trial has been created with ID:"+str(inserted_id)) temp_str = str(inserted_id)+','+str(copy_trial_start_time)+','+str(staff_id) trialsData[participant_id] = temp_str # Cache data. Value = copyTrialID, copyTrialStartTime, staffID
def upload_new(folder): check_write_access(folder) session = db.session() base_folder = folder uncompress_files = "uncompress_files" in request.form fds = request.files.getlist("file") created_count = 0 path_cache = {} # mapping folder path in zip: folder instance for upload_fd in fds: for filepath, fd in explore_archive(upload_fd, uncompress=uncompress_files): folder = base_folder parts = [] # traverse to final directory, create intermediate if necessary. Folders # may be renamed if a file already exists, path_cache is used to keep # track of this for subfolder_name in filepath: parts.append(subfolder_name) path = "/".join(parts) if path in path_cache: folder = path_cache[path] continue subfolders = {f.title: f for f in folder.subfolders} if subfolder_name in subfolders: folder = subfolders[subfolder_name] path_cache[path] = folder continue subfolder_name = get_new_filename(folder, subfolder_name) folder = folder.create_subfolder(subfolder_name) session.flush() path_cache[path] = folder create_document(folder, fd) created_count += 1 flash( _n( "One new document successfully uploaded", "%(num)d new document successfully uploaded", num=created_count, ), "success", ) session.commit() return redirect(url_for(folder))
def upload_new(folder): check_write_access(folder) session = db.session() base_folder = folder uncompress_files = "uncompress_files" in request.form fds = request.files.getlist("file") created_count = 0 path_cache = {} # mapping folder path in zip: folder instance for upload_fd in fds: for filepath, fd in explore_archive(upload_fd, uncompress=uncompress_files): folder = base_folder parts = [] # traverse to final directory, create intermediate if necessary. Folders # may be renamed if a file already exists, path_cache is used to keep # track of this for subfolder_name in filepath: parts.append(subfolder_name) path = "/".join(parts) if path in path_cache: folder = path_cache[path] continue subfolders = {f.title: f for f in folder.subfolders} if subfolder_name in subfolders: folder = subfolders[subfolder_name] path_cache[path] = folder continue subfolder_name = get_new_filename(folder, subfolder_name) folder = folder.create_subfolder(subfolder_name) session.flush() path_cache[path] = folder create_document(folder, fd) created_count += 1 flash( _n( "One new document successfully uploaded", "%(num)d new document successfully uploaded", num=created_count, ), "success", ) session.commit() return redirect(url_for(folder))
def get_or_create_school(session, school_name, address, email=None, phone=None): school = session.query(School).filter( School.address == address).one_or_none() if school: return school school = School(name=school_name, address=address, email=email, phone=phone) session.add(school) session.flush() return school
def objeto_agregar(): codigo = request.form['cod_objeto'] nom_objeto = str(request.form['nom_objeto']) categoria = str(request.form['categoria']) marca = str(request.form['marca']) estado = str(request.form['estado']) fecha_hallado = request.form['fecha_hallado'] fecha_dev = request.form['fecha_dev'] lugar = str(request.form['lugar']) nro_anaquel = request.form['nro_anaquel'] caract_esp = str(request.form['caract_esp']) cod_usu_entrega = request.form['cod_usu_entrega'] print(cod_usu_entrega) #conn = engine.connect() status = 200 session = session_db() stmt = Objeto(cod_objeto=codigo, nom_objeto=nom_objeto, categoria=categoria, marca=marca, estado=estado, fecha_hallado=fecha_hallado, fecha_dev=fecha_dev, lugar=lugar, nro_anaquel=nro_anaquel, caract_esp=caract_esp, cod_usu_entrega=cod_usu_entrega) session.add(stmt) session.flush() print('1 ++++++++++++++++++++++++') session.commit() print('2 ++++++++++++++++++++++++') #users.insert().values({"name": "some name"}) #conn.execute(stmt) rpta = { 'tipo_mensaje': 'success', 'mensaje': ['Se ha registrado los cambios en los items del subtítulo'] } #return json.dumps(rpta),status return redirect('/register') '''
def create_recall_trial(participant_id, recall_trial_pixels, recall_trial_thinking_start_time, recall_trial_thinking_end_time, recall_trial_drawing_start_time, recall_trial_drawing_end_time): recall_trialInfo=recall_trial(recallTrialPixels=recall_trial_pixels, recallTrialThinkingStartTime=recall_trial_thinking_start_time, recallTrialThinkingEndTime=recall_trial_thinking_end_time, recallTrialDrawingStartTime=recall_trial_drawing_start_time, recallTrialDrawingEndTime=recall_trial_drawing_end_time) session.add(recall_trialInfo) session.flush() inserted_id = recall_trialInfo.recallTrialID session.commit() print("Recall Trial has been created with ID:"+str(inserted_id)) tempArr = trialsData[participant_id].split(',') staff_id = tempArr[2] copy_trial_id = tempArr[0] trial_start_time = tempArr[1] create_trials(participant_id, staff_id, copy_trial_id, inserted_id, trial_start_time, recall_trial_drawing_end_time)
def login(self, *args, **kws): from flask.globals import _request_ctx_stack, request, current_app ## current_app.before_login(*args, **kws) assert self.password_check_result user = self from flask import session user.last_login = datetime.datetime.now() user.save() if self.USER_ID_KEY in session: if session[self.USER_ID_KEY] != user.id: # To avoid reusing another user's session, create a new, empty # session if the existing session corresponds to a different # authenticated user. session.flush() else: session.cycle_key() if hasattr(session, "_user"): delattr(session, "_user") session[self.USER_ID_KEY] = user.id
def editstudent(sid): session = DBSession() name = request.form['name'] no = request.form['studentno'] phone = request.form['phonenumber'] email = request.form['studentemail'] address = request.form['address'] try: student = session.query(Student).filter(Student.id == sid).one() student.sname = name student.sno = no student.sphone = phone student.semail = email student.param1 = address session.flush() return ResponseBody(0, None)() except Exception as e: logging.info(e) print e return ResponseBody(1, None)() finally: session.commit() session.close()
def newItem(): """This page will be for adding a new item.""" error = None login_already = current_user.is_authenticated() # This function will return to homepage if it found user is not login. # There are same setting in pages below which are able to edit the database. if login_already: if request.method == "POST": error = vacant_input() if not error: """go on input database if no empty imput. If there any, reload and labels of the empty form will turn red.""" time_now = datetime.now().strftime("%Y-%m-%d %H:%M:%S") """ Get currunt time and insert to create_time. This will use for index items display order""" i = Item(create_time=time_now, name=request.form['name'], discription=request.form['discription'], category=request.form['category']) session.add(i) session.flush() i.photo = upload_image(i.id) session.commit() return redirect("/") c = session.query(Category).all() return render_template("add.html", c=c, login_already=login_already, error=error) c = session.query(Category).all() return render_template("add.html", c=c, login_already=login_already, error=error) else: return redirect("/")
def create_albergue(): create = json.loads(request.form['data']) files = request.files session = db.getSession(engine) usuario = entities.Usuario( nombre = create["admin"]["nombre"], apellidos = create["admin"]["apellidos"], representante = create["admin"]["representante"], celular = create["admin"]["celular"], correo = create["admin"]["correo"] ) session.add(usuario) session.flush() albergue = entities.Albergue( admin_id = usuario.id, nombre = create["albergue"]["nombre"], anios = create["albergue"]["anios"], direccion = create["albergue"]["direccion"], urbanizacion = create["albergue"]["urbanizacion"], distrito = create["albergue"]["distrito"], ciudad = create["albergue"]["ciudad"], departamento = create["albergue"]["departamento"], tamanio = create["albergue"]["tamanio"], material = create["albergue"]["material"], gasto = create["albergue"]["gasto"], pertenencia = create["albergue"]["pertenencia"], voluntarios = create["albergue"]["voluntarios"], albergan = create["albergue"]["albergan"], num_gatos = create["albergue"]["num_gatos"], acep_donaciones = create["albergue"]["acep_donaciones"], acep_apoyo = create["albergue"]["acep_apoyo"], banco_name = create["albergue"]["banco_name"], banco_number = create["albergue"]["banco_number"], banco_cci = create["albergue"]["banco_cci"], facebook = create["albergue"]["facebook"], instagram = create["albergue"]["instagram"], correo = create["albergue"]["correo"], otro_contacto = create["albergue"]["otro_contacto"] ) session.add(albergue) session.flush() for i in range(6): nombre = "gato" + str(i) if(create[nombre]["nombre"] != ""): gato = entities.Gato( albergue_id = albergue.id, nombre = create[nombre]["nombre"], img = "", #nombre de la imagen edad = create[nombre]["edad"], adopcion = create[nombre]["adopcion"] ) session.add(gato) session.flush() temp = gato.id path = os.getcwd() os.mkdir(path + "/gatos_imgs/" + str(gato.id)) foto = files['files[' + str(i) + ']'] print(foto.filename) nombre_foto = secure_filename(foto.filename) foto.save(path+"/gatos_imgs/"+str(gato.id)+"/"+ nombre_foto) session.commit() actualizar = session.query(entities.Gato).filter(entities.Gato.id == temp).first() setattr(actualizar, 'img', path+"/gatos_imgs/"+str(gato.id)+"/"+ nombre_foto) session.commit() session.commit() session.close() return "finalizado la inserción de datos :)"
def signout(): session.flush() return render_template("login.html")
def logout(cls): session.flush() session._user = cls.AnonymousUser() session.modified = True
def post(self): print("In post user method") sign_up_data = request.json user_data = sign_up_data["user_info"] device_data = sign_up_data["device_info"] # print("device_data: " + str(device_data)) if User.query.filter(User.email_address == user_data["email_address"]).first() is not None: raise ValidationError("That email address is already in use.") role_data = user_data.pop("role") user_data["role"] = self._role_type_to_role_class(role_data["type"])(**role_data) print("In post user method") user = User(**user_data) session = current_app.db.session session.add(user) new_user_id = session.query(User.id).filter(User.email_address == user_data["email_address"]).first() # Check for off-network version of new user. If found, create contacts for all on-network contacts that had new user as off-network contact and deletes off-network version list_off_network_ids = session.query(OffNetworkContact).filter(OffNetworkContact.email_address == user_data["email_address"]).all() # query_off_network_ids = off_network_ids.all() if list_off_network_ids: # print("off-network ids: " + str(list_off_network_ids)) for off_network_id in list_off_network_ids: print("off_network_id: " + str(off_network_id)) contact = Contact(off_network_id.owning_user_id, new_user_id) session.add(contact) off_network_id.active = False # Check for bucket for new user, and if found, dump messages from bucket into received_messages table bucket_id = session.query(OffNetworkBucket.id).filter(OffNetworkBucket.bucket_id == user_data["email_address"]).first() if bucket_id: # list_message_id = session.query(OffNetworkMessage.message_id).filter(OffNetworkMessage.off_network_bucket_id == bucket_id).all() off_network_messages = session.query(OffNetworkMessage.message_id).filter(OffNetworkMessage.off_network_bucket_id == bucket_id).all() # list_contacts = [ message._asdict() for message in off_network_messages.all() ] # for message_id in list_message_id: for message in off_network_messages: # received_message = ReceivedMessage(new_user_id, message_id, 'unread') received_message = ReceivedMessage(new_user_id, message[0], 'unread') session.add(received_message) # Add device from which user signed up on device = Device(new_user_id, 'activated') session.add(device) # Add device characteristics including InstanceID device_id = session.query(Device.id).filter(Device.owner_user_id == new_user_id).first() device_data['device_id'] = device_id[0] device_char = DeviceCharacteristic(**device_data) session.add(device_char) session.flush() # return redirect(url_for("Users:get", id=user.id), 303) return "Success"