def new_item(): data = ast.literal_eval(json.dumps(request.json)) s = Service(name=str(data['name']), description=str(data['description']), primary_support=str(data['primary_support'])) db_session.add(s) db_session.commit() return 'Success'
def create_task(project_id): if request.method == "POST": _description = request.form["description"] _tl = request.form["tags"] _start_time = request.form["start_time"] _end_time = request.form["end_time"] print(project_id) task = Task(project_id=project_id, description=_description, start_time=_start_time, end_time=_end_time) db_session.add(task) db_session.commit() _tags_list = [x.strip() for x in _tl.split(",")] for t in _tags_list: tag = Tag(task_id=task.task_id, tag_name=t) db_session.add(tag) db_session.commit() return redirect(url_for("core.tasks", project_id=project_id)) return render_template("create_task.html", project_id=project_id)
def setPushToken(): userId = request.form['userId'] pushTokenStr = request.form['pushToken'] os = request.form['os'] update_result = db_session.query(PushToken).filter_by(userId=userId).update({'pushToken': pushTokenStr, 'os' : os}) try: db_session.commit() except exc.IntegrityError as e: db_session.rollback() if(update_result==None): result = { "code": 400, "result": "DB Error" } elif(update_result==0): pushToken = PushToken(userId, pushTokenStr, os) db_session.add(pushToken) try: db_session.commit() except exc.IntegrityError as e: db_session.rollback() result = { "code": 201, "result": "Success to insert" } else: result = { "code": 200, "result": "Success to update" } return jsonify(result)
def putTodayHappiness(): params = dict() params["userId"] = request.form['userId'] params["companyId"] = request.form['companyId'] params["groupId"] = request.form['groupId'] params["happyVal"] = request.form['happyVal'] today = datetime.today() todayDate = today.strftime("%Y-%m-%d") todayHappiness = Happiness.query.filter_by(userId=params["userId"]).filter(Happiness.rdate > todayDate ).first() if todayHappiness!=None and todayHappiness.id!=None: result = { "code": 305, "result": "Duplicate today's entry", "happyVal": todayHappiness.happyVal } else: happiness = Happiness(**params) db_session.add(happiness) try: db_session.commit() except exc.IntegrityError as e: db_session.rollback() if(happiness.id==None): result = { "code": 400, "result": "DB Error" } else: result = { "code": 200, "result": "Success" } return jsonify(result)
def likeGoodPost(): # 일일한도 체크 todayCount = myTodayCounts(request.form['userId'], "GoodLike"); if todayCount["Like"] >= 10 : return jsonify({ "code": 313, "result": "Limit today's like good thing" }) try: like = GoodLike(request.form['postId'], request.form['userId']) db_session.add(like) db_session.commit() result = { "code": 200, "result": "Success" } # 포인트 적립 point_result = putPointFunc(request.form['userId'], 10, "GoodLike", request.form['postId']) if point_result!=False : result["pointId"] = point_result["pointId"] result["point"] = point_result["point"] # 글쓴이 적립 putPointFunc(request.form['pUserId'], 10, "GoodLikeRcv", request.form['postId']) # 푸쉬알림. push_result = sendPush(request.form['pUserId'], 3, "작성한 게시물이 \'좋아요\'를 받았습니다.") result["push"] = push_result except exc.IntegrityError as e: db_session.rollback() result = { "code": 402, "result": "Duplicate entry or No such entry" } return jsonify(result)
def putPointFunc(userId, point, where, why): #이벤트 체크 - 이벤트 당첨자(=해당 날)이면 point 2배 if amIinEvent(userId) == True : point = point * 2 insert_row = PointHistory(userId, point, where, why) db_session.add(insert_row) if where.startswith("Praise"): myPoint_update_result = db_session.query(PointTotal).filter_by(userId=userId)\ .update({PointTotal.pointTotal: PointTotal.pointTotal + point, PointTotal.pointPraise: PointTotal.pointPraise + point}) elif where.startswith("Thanks"): myPoint_update_result = db_session.query(PointTotal).filter_by(userId=userId)\ .update({PointTotal.pointTotal: PointTotal.pointTotal + point, PointTotal.pointThanks: PointTotal.pointThanks + point}) elif where.startswith("Good") : myPoint_update_result = db_session.query(PointTotal).filter_by(userId=userId)\ .update({PointTotal.pointTotal: PointTotal.pointTotal + point, PointTotal.pointGood: PointTotal.pointGood + point}) else : myPoint_update_result = False if not (myPoint_update_result > 0) : #insert when no row insert_row2 = PointTotal(userId, request.form['companyId'], request.form['groupId'], point, where) db_session.add(insert_row2) try: db_session.commit() except exc.IntegrityError as e: db_session.rollback() if(insert_row.id==None or (not (myPoint_update_result > 0) )): # and insert_row2.inserted_primary_key==None)): return False else: return { "pointId" : insert_row.id, "point" : point }
def todos(id): """ Need a todo id pased by url, Provide: - /api/todo/x PATCH and DELETE routes PATCH require title, content, done as arg DELETE is without arg """ todo = Todo.query.get(id) if not todo: abort(400) elif request.method == 'PATCH': print todo print request.json # uggly, how to factorise ? if not request.json or not 'content' in request.json or not 'done' in request.json or not 'title' in request.json: abort(400) todo.title = request.json['title'] todo.content = request.json['content'] todo.done = request.json['done'] db_session.add(todo) db_session.commit() return jsonify(ok=todo.serealize) elif request.method == 'DELETE': db_session.delete(todo) db_session.commit() return jsonify(deleted=todo.serealize) else: abort(400)
def cpanel(): form = NewTireForm() img_form = UpdateImageForm() if form.validate_on_submit(): tire = Tire(name = form.name.data, price = form.price.data, size = form.size.data, status = Tire.Status.active.name, description = form.description.data, quantity = form.quantity.data) if form.image.data is not None: tire.image = save_image(form) sess.add(tire) sess.commit() flash('Added {0}'.format(form.name.data)) return redirect(url_for('.cpanel')) elif img_form.validate_on_submit(): t = Tire.query.filter_by(id=img_form.pk.data).first() t.image = save_image(form) sess.commit() flash('Updated image') return redirect(url_for('.cpanel')) elif request.method == 'POST': flash(form.errors) return render_template('admin.html', form=form, img_form=img_form)
def add(): if request.method == 'GET': output = render_template("user/add.html") else: output = { 'error': None, 'error_message': None, 'redirect_url': None, } try: if request.json: form_data = request.json else: form_data = request.form name = form_data["user_name"] phone = form_data["user_phone"] mac_address = form_data["user_mac_address"] user = RegisteredUser(name, mac_address, phone) db_session.add(user) db_session.commit() output['redirect_url'] = url_for('mod_user.show') except Exception as e: output['error'] = True output['error_message'] = str(e) db_session.rollback() finally: output = Response(json.dumps(output), mimetype='application/json') return output
def confirmMsg(): msgId = request.form['msgId'] msgType = request.form['msgType'] userId = request.form['userId'] update_result = db_session.query(Message).filter_by(id=msgId).filter_by(rUserId=userId).filter_by(msgType=msgType).filter_by(isRead=0)\ .update({'isRead': 1, 'readTime': datetime.now()}) try: db_session.commit() except exc.IntegrityError as e: db_session.rollback() if(update_result==None): result = { "code": 400, "result": "DB Error" } elif(update_result==0): result = { "code": 401, "result": "No affected rows" } else: result = { "code": 200, "result": "Success" } # 포인트 적립 msgTypeStr = params["msgType"]=='1' and 'PraiseRcv' or 'ThanksRcv' point_result = putPointFunc(request.form['userId'], 200, msgTypeStr, msgId) if point_result!=False : result["pointId"] = point_result["pointId"] result["point"] = point_result["point"] return jsonify(result)
def delete_message(message_id): message = Message.query.get_or_404(message_id) if current_user != message.author and not current_user.is_admin: abort(403) db_session.delete(message) db_session.commit() return '', 204
def add(): """ { "name":"Egg Burger", "price":10.00, "category":"hamburguer" } :return: {"result": "product has been created","status_code": 201} """ try: data = request.get_json(force=True) if not data or not data.get("name") or not data.get("price"): return json_response( status_=StatusCodeEnum.HTTP_400_BAD_REQUEST, result=get_messages("PRODUCT_REQUIRED_FIELDS"), ) product = Product(data) db_session.add(product) db_session.commit() return json_response( status_=StatusCodeEnum.HTTP_201_CREATED, result=get_messages("PRODUCT_CREATED"), ) except ValueError as ex: db_session.rollback() raise ex finally: db_session.close()
def post(self): parser = reqparse.RequestParser() parser.add_argument('title', type=str, required=True) parser.add_argument('content', type=str, required=True) parser.add_argument('labels', type=int, required=False, action="append") args = parser.parse_args() labels = [] try: #Checks for duplicate if db_session.query(Blog).filter(Blog.title.ilike("%"+args.title+"%"))\ .first() is not None: return self.response.warning(\ self.response.WARNINGS['duplicate'](args.title), None) #Check of the labels exist for label in args.labels: label_instance = db_session.query(BlogLabel).get(label) if label_instance is None: return self.response.warning("Label with id %d does not exist." % label, None) labels.append(label_instance) blog = Blog(title=args.title, author_id=1, #TODO: Change this to user's current session content=args.content) #Now append the labels to the blog for label_instance in labels: blog.labels.append(label_instance) db_session.add(blog) db_session.commit() return self.response.success(None) except exc.SQLAlchemyError: return self.response.error('Error creating new blog', self.response.ERROR_SQLALCHEMY)
def populate_songs(): df = pd.read_csv('app/data/labeled_chords.csv', header = 0) song_ids = {} for index, row in df.iterrows(): song = Song() if row['Echo_song_id'] in song_ids: continue else: song_ids[row['Echo_song_id']] = 0 song.song_id = row['Echo_song_id'] song.artist = row['Local Artist'] song.title = row['Local title'] song.energy = row['energy'] song.liveness = row['liveness'] song.tempo = row['tempo'] song.speechiness = row['speechiness'] song.acousticness = row['acousticness'] song.danceability = row['danceability'] song.instrumentalness = row['instrumentalness'] song.loudness = row['loudness'] song.key = root_key[row['key']] song.mode = row['mode'] song.valence_label = row['labeled_valence'] song.arousal_label = row['labeled_arousal'] session.add(song) session.commit()
def add_example(new): print('New is: %s' % new) if db_session.query(ExampleModel.id).filter_by(id=new).scalar() is None: ex = ExampleModel() ex.id = new ex.field1 = 'ExampleString' db_session.add(ex) db_session.commit() #return url_for('app.get_example', variable=new) body = 'Success!' response = jsonify(body) response.status_code = 201 return response else: body = 'That example record already exists' response = jsonify(body) response.status_code = 404 return response
def kill(): if request.method == "POST": book_id = request.json book = db_session.query(Book).filter_by(id=book_id).first() db_session.delete(book) db_session.commit() return redirect(url_for('odminko'))
def set_roles(): all_users = User.query.all() roles = Role.query.all() ## FILTER SUPERADMIN USER for i in all_users: if i.username == ADMIN: all_users.remove(User.query.filter_by(username=ADMIN).first()) if request.method == 'POST': ## This loop checks all the users and assign all the roles assigned by the administrator ## Like the previous checking loop, this loop does the same, checking each checkboxes, ## and assign the checked values to the User roles. for user in all_users: u = User.query.filter_by(username=user.username).first() u.role = [] for r in roles: type = u.username + ' ' + r.name print type get_val = request.form.get(str(type)) if get_val is not None: erole = Role.query.filter_by(name=str(get_val)).first() ##Entered role print 'ENTERED! ' + str(erole) u.role.append(erole) print str(u.username) + ' ' + str(u.role) db_session.add(u) u.init_active_roles(u.username) db_session.commit() flash('Role changed.') return redirect(url_for('Users.set_roles')) return render_template('admin/set_roles.html', all_users=all_users, roles=roles, ADMIN=ADMIN)
def change_permissions(): ## This block filters the admin role and permissions all_users = User.query.all() list_of_roles = Role.query.all() list_of_perms = Permission.query.all() admin_role = Role.query.filter_by(name='Administrator').first() admin_perms = Permission.query.filter_by(permission_name='Administrator').first() list_of_roles.remove(admin_role) list_of_perms.remove(admin_perms) ## Endblock print list_of_perms if request.method == 'POST': for roles in list_of_roles: role = Role.query.filter_by(name=roles.name).first() role.permissions = [] for perms in list_of_perms: ## number of permissions type = roles.name + ' ' + perms.permission_name print type get_val = request.form.get(str(type)) if get_val is not None: p = Permission.query.filter_by(permission_name=str(get_val)).first() print 'ENTERED! ' + str(p) role.permissions.append(p) print role.permissions db_session.add(role) db_session.commit() flash('Permissions changed.') return redirect(url_for('Users.change_permissions')) return render_template('admin/edit_permissions.html',list_of_roles=list_of_roles, list_of_perms=list_of_perms, all_users=all_users)
def delete_users(user): print user ## Checks if the user is an admin if current_user.is_admin(current_user.username): u = User.query.filter_by(username=user).first() us = UserStatistics.query.filter_by(userId=u.id).first() ## Checks if the user tries to delete itself if current_user.username == u.username: flash('Sorry, but you cannot delete yourself. Think about those people who love you more than their world mi amigo.') return redirect(url_for('Users.set_roles')) # loads the supervisor and deletes the user load_supervisor = u.supervisor supervisor = User.query.filter_by(username=load_supervisor).first() load_supervisees = supervisor.supervisee print "Load supervisee before split: " + str(load_supervisees) load_supervisees = load_supervisees.split(' ') print "Load supervisee after split: " + str(load_supervisees) load_supervisees.remove(u.username) supervisor.supervisee = ' '.join(load_supervisees) print supervisor.supervisee db_session.delete(u) db_session.add(supervisor) db_session.commit() flash('User Deleted') return redirect(url_for('Users.set_roles')) flash('USER UNAUTHORIZED') return redirect(url_for('Home.show_home'))
def add_blog(): db_session.execute( 'insert into blog(title, content, pub_date) values("%s", "%s", "%s")' % (request.form['title'], request.form['content'], datetime.now())) db_session.commit() flash('a new blog') return redirect(url_for('show_blogs'))
def handle_form_data(register_dict): reg_num = rand_gen() register_dict['reg_num'] = reg_num p = Presenters(arg_dict=register_dict) handle_email(register_dict['email'],register_dict) db_session.add(p) db_session.commit()
def oauth_callback(provider_name): if provider_name not in providers.keys(): abort(404) provider = providers[provider_name] response = provider.authorized_response() if response is not None: if provider_name == 'twitter': access_token = response.get('oauth_token'), response.get('oauth_token_secret') else: access_token = response.get('access_token') else: access_token = None if access_token is None: flash('Access denied, please try again.') return redirect(url_for('auth.login')) username, website, github, email, bio = get_social_profile(provider, access_token) user = User.query.filter_by(email=email).first() if user is None: user = User(email=email, nickname=username, website=website, github=github, bio=bio) db_session.add(user) db_session.commit() login_user(user, remember=True) return redirect(url_for('chat.profile')) login_user(user, remember=True) return redirect(url_for('chat.home'))
def register(): if request.method == 'POST': if "" in request.form.values(): return render_template("register.html") if request.form['username'] in list(User.query.values(User.name)): flash('Please enter a password.', 'error') return render_template("register.html") if request.form['email'] in list(User.query.values(User.email)): flash('Please enter a valid email.', 'error') return render_template("register.html") if request.form['password'] != request.form['passwordconfirm']: flash('Passwords do not match.', 'error') return render_template("register.html") # TODO: error for when they try to register when logged in already u = User(request.form['username'], request.form['email'], generate_password_hash(request.form['password'].strip())) db_session.add(u) db_session.commit() """for currency in config.get_currencies(): addr = generate_deposit_address(currency) a = Address(currency, addr, u.id) db_session.add(a) db_session.commit() if not send_confirm_email(u.id): flash('An error occured during registration. Please contact the administrator.', 'danger') return home_page("ltc_btc")""" flash( 'Successfully registered. Please check your email and confirm your account before logging in.', 'dismissable') return home_page("ltc_btc") if request.method == 'GET': return render_template("register.html")
def create_model(): form = Form(request.form) del form.delete if request.method == 'POST' and form.validate(): new_el = Model() for field in form: if field.type == "SubmitField": continue if field.data == "": continue setattr(new_el, field.name.lower(), field.data) db_session.add(new_el) try: db_session.commit() except (sqlalchemy.exc.IntegrityError, sqlalchemy.orm.exc.FlushError) as e: flash(str(e), "danger") return redirect(url_for(".view_all")) return render_template("form_view.html", title=title, form=form)
def updateGroup(): groupId = request.form.get('groupId') if groupId : group = Group.query.filter_by(groupId=groupId).first() if group : group.name = request.form['name'] try: db_session.commit() result = { "code" : 200, "msg" : "Success" } except exc.IntegrityError as err: result = { "code" : 301, "msg" : "IntegrityError" } else : result = { "code" : 300, "msg" : "No such group" } else : # new group companyId = session['companyId'] if not companyId: return jsonify({"code": 405, "result": "no company id"}) elif request.form.get("name"): newGroup = Group(companyId, request.form.get("name")) db_session.add(newGroup) try: db_session.commit() except exc.IntegrityError as e: db_session.rollback() if(newGroup.groupId==None): result = { "code": 400, "result": "DB Error" } else: result = { "code": 200, "result": "Success", "groupId": newGroup.groupId } else : result = { "code": 302, "result": "No group name" } return jsonify(result)
def delete_movie(id): movie = Movies.query.get(id) db_session.delete(movie) db_session.commit() return (jsonify(movie.to_json()), 200, { 'Location': url_for('api.get_movie', id=movie.id, _external=True) })
def edit_preset(id): error = None data = Preset.query.get(id) if data is None: abort(404) form = dict(name=data.name, r_code = data.r_code, g_code = data.g_code, b_code = data.b_code, id = data.id) if request.method == 'POST': if 'delete' in request.form: db_session.delete(data) db_session.commit() flash(u'Deleting preset: %s' % data.name) return redirect(url_for('presets.index')) elif 'submit' in request.form: data.name = request.form.get('name', type=str) data.r_code = request.form.get('r_code', type=int) data.g_code = request.form.get('g_code', type=int) data.b_code = request.form.get('b_code', type=int) db_session.commit() flash(u'Saving modifications for %s' % data.name) return redirect(url_for('presets.index')) else: flash(u'Nothing changed') return render_template(url_for('presets.index')) if request.method == 'GET': flash(u'Editing preset: %s' % data.name) return render_template('presets/edit.html', form=form)
def insert(self, current_user, address, notes, duration): if address is None: db_session.flush() return False submitterID = current_user.id #fix me: should handle additional address types (cidr, range, name) ipString = address.strip() ipAddress = unpack('!L', inet_aton(ipString))[0] self.ip = ipAddress self.notes = notes self.duration = int(duration) self.submitter_id = submitterID #self.tdSubmitted = datetime.utcnow() #self.approver_id = submitterID try: print "Blocking %s for %s days" % (ipString, self.duration) print int2ip(ipAddress) #db_session.flush() db_session.merge(self) #db_session.add(self) db_session.commit() except AttributeError: traceback.print_exc(file=sys.stderr)
def changeAccountPW(): accountId = request.form['accountId'] befPW = request.form['befPW'] newPW = request.form['newPW'] account_row = db_session.query(Account).filter_by(accountId=accountId).filter_by(isValid=1)\ .with_entities(Account, func.password(befPW), func.password(newPW)).first() account = None if account_row: account, pw, nPW = account_row result = dict() if(account): print pw, account.password, nPW if len(befPW)>0 and pw != account.password : return jsonify({ "code": 302, "result": "Wrong password" }) update_result = db_session.query(Account).filter_by(accountId=accountId)\ .filter(Account.isValid>0).update({'password': nPW}) try: db_session.commit() except exc.IntegrityError as e: db_session.rollback() return jsonify({ "code": 400, "result": "DB Error" }) if(update_result==0): result = { "code": 401, "result": "No affected rows" } else: result = { "code": 200, "result": "Success" } else : result["code"] = 301 result["result"] = "No Such User" return jsonify(result)
def add_location(): error = None location_id = None tempList = [] if request.method == 'POST': name = request.form['name'] code = request.form['code'] body = request.form['body'] if 'cancel' in request.form: return redirect(url_for('locations.index')) if len(name) < 1: flash(u'Error: you have to enter a name') return render_template('locations/new.html') elif not int(code): flash(u'Error: location number required') return render_template('locations/new.html') else: newloc = Locations(name, code, body) db_session.add(newloc) db_session.commit() flash(u'Your location was added') overzicht = Locations.query.all() number = Locations.query.count() return render_template('locations/location.html', location_list=overzicht, location_count=number) if request.method == 'GET': flash(u'Please fill in all fields.') return render_template('locations/new.html')
def mutate(self, info, title): book = Book.query.filter_by(title=title).first() if book is None: raise Exception('book does not exist in the catalogue!') db_session.delete(book) db_session.commit() return DeleteBook(book=book)
def verticalization_remove(server_id): output = { 'error': None, 'error_message': None, 'redirect_url': None, } try: form_json = request.json location_system = db_session.query(LocationSystem).filter( LocationSystem.id == server_id).first() campi = location_system.campuses for campus in campi: campus.vertical_name = None for building in campus.buildings: building.vertical_name = None for floor in building.floors: floor.vertical_name = None for zone in floor.zones: zone.vertical_name = None zone.max_occupation = -1 db_session.commit() output['redirect_url'] = url_for('mod_cmx_server.details', server_id=server_id) except Exception as e: output['error'] = True output['error_message'] = str(e) traceback.print_exc() db_session.rollback() output = Response(json.dumps(output), mimetype='application/json') return output
def delete_payslip(file_name): user = Payslip.query.filter_by(filename=file_name).first() # Checks the filename to be deleted db_session.delete(user) db_session.commit()# and poof os.remove(current_app.config['UPLOADS_FILES_DEST'] +'//'+ file_name) # Remove it also from its storage flash('Payslip deleted.') return redirect(url_for('.payslip_base'))
def register(): if request.method == 'POST': if "" in request.form.values(): return render_template("register.html") if request.form['username'] in list(User.query.values(User.name)): flash('Please enter a password.', 'error') return render_template("register.html") if request.form['email'] in list(User.query.values(User.email)): flash('Please enter a valid email.', 'error') return render_template("register.html") if request.form['password'] != request.form['passwordconfirm']: flash('Passwords do not match.', 'error') return render_template("register.html") # TODO: error for when they try to register when logged in already u = User( request.form['username'], request.form['email'], generate_password_hash( request.form['password'].strip())) db_session.add(u) db_session.commit() """for currency in config.get_currencies(): addr = generate_deposit_address(currency) a = Address(currency, addr, u.id) db_session.add(a) db_session.commit() if not send_confirm_email(u.id): flash('An error occured during registration. Please contact the administrator.', 'danger') return home_page("ltc_btc")""" flash('Successfully registered. Please check your email and confirm your account before logging in.', 'dismissable') return home_page("ltc_btc") if request.method == 'GET': return render_template("register.html")
def command_add(message_text, room_id, person_id): post_text = 'Command not valid... Usage = add user/asset name MAC_address phone[optional]' try: message_pieces = message_text.split(' ') second_word = message_pieces[1].lower() if second_word in ['user', 'asset', 'user/asset']: name = message_pieces[2] mac_address = message_pieces[3] phone = None if len(message_pieces) > 4: phone = message_pieces[3] try: user = RegisteredUser(name, mac_address, phone) db_session.add(user) db_session.commit() post_text = 'Item created successfully' except Exception as e: if 'duplicate key value violates unique constraint "registered_user_mac_address_key"' in str( e): post_text = 'MAC Address already registered. Try a different value' else: post_text = str(e) db_session.rollback() except: pass finally: print('Posting on Spark... {}'.format(post_text)) write_to_spark(room_id, None, None, post_text, None, None) return post_text
def add_recipe(): data = request.data recipe_data = json.loads(data.decode("utf-8")) recipe = Recipe(title=recipe_data['title'], instructions=recipe_data['instructions'], img=recipe_data['img'], type=recipe_data['type'], time=recipe_data['time'], people=recipe_data['people'], owner=recipe_data['owner']) db_session.add(recipe) for ingredient in recipe_data['ingredients']: ingredient = Ingredient(item=ingredient['item'], quantity=ingredient['quantity']) db_session.add(ingredient) recipe.ingredients.append(ingredient) try: db_session.commit() except Exception: db_session.rollback() clear_sessions() return return_result(data=recipe_data)
def user_init_func(row): if len(row['name'])==0: return None group_row = db_session.query(Group.groupId).filter(Group.companyId==companyId).filter(Group.name==row['groupName']).first() if group_row: groupId = group_row[0] elif len(row['groupName']) > 0 : newGroup = Group(companyId, row['groupName']) db_session.add(newGroup) try: db_session.commit() except exc.IntegrityError as e: db_session.rollback() if(newGroup.groupId==None): return None else: groupId = newGroup.groupId else : groupId = None # companyId, jobClass, groupId, email, accessKey, name, gender, birth, jobType, workYear, workMonth, jobTitle, jobTitleNo u = User(companyId, jobClass, groupId, row['email'], row['accessKey'], row['name'], row['gender'], row['birth'], row['jobType'], row['workYear'], row['workMonth'], row['jobTitle'], row['jobTitleNo']) return u
def edit_wifidomo(id): error = None data = WiFiDomo.query.get(id) if data is None: abort(404) form = dict(name=data.name, ip4 = data.ip4, ip6 = data.ip6, port = data.port, mac = data.MAC, fqdn = data.fqdn, location = data.locationid, status = data.status) if app.debug: print(data.name) print(data.ip4) print(data.ip6) print(data.fqdn) print(data.port) print(data.locationid) tempList = get_location_list() if request.method == 'POST': if 'delete' in request.form: db_session.delete(data) db_session.commit() flash(u'Deleting wifidomo: %s' % data.name) return redirect(url_for('wifidomos.index')) elif 'submit' in request.form: data.name = request.form.get('name', type=str) data.fqdn = request.form.get('fqdn', type=str) data.status = request.form.get('status', type=bool) data.MAC = request.form.get('mac', type=str) data.ip4 = request.form.get('ip4', type=str) data.ip6 = request.form.get('ip6', type=str) data.port = request.form.get('port', type=int) data.locationid = int(request.form.get('location', type=int)) if app.debug: print(data.name) print(data.ip4) print(data.ip6) print(data.fqdn) print(data.locationid) db_session.commit() flash(u'Saving modifications for %s' % data.name) return redirect(url_for('wifidomos.index')) else: flash(u'Nothing changed') return redirect(url_for('wifidomos.index')) if request.method == 'GET': flash(u'Editing wifidomo: %s' % data.name) return render_template('wifidomos/edit.html', form=form, wifidomo_locations=tempList)
def voteincrement(): idea = request.get_json(force=True)['idea'] db_object = Idea.query.filter_by(name=idea).first() db_object.votes += 1 db_session.commit() data = jsonify(message='Transaction successful') return data
def delete_task(task_id): task = Task.query.filter(Task.id == task_id).first() if task: db_session.delete(task) db_session.commit() return redirect(url_for('planner.show_index')) else: abort(404)
def mutate(self, info, title, description, year, username): user = User.query.filter_by(username=username).first() book = Book(title=title, description=description, year=year) if user is not None: book.author_id = user.id db_session.add(book) db_session.commit() return AddBook(book=book)
def seer(): u('Seer','super','SuperAdmin','*****@*****.**','seer','seer') user = User.query.filter_by(username='******').first() r = Role.query.filter_by(name='Administrator').first() user.roles.append(r) user.is_supervisor = True db_session.add(user) db_session.commit()
def post(): if request.method == 'POST': a = Activity(request.form['title'], request.form['description']) db_session.add(a) db_session.commit() return redirect(url_for('.detail', id=a.id)) else: return render_template('activity/post.html')
def upload(): form = UploadForm() if request.method == 'POST' and form.validate(): g.user.avatar = form.uri.data db_session.add(g.user.avatar) db_session.commit() return redirect(url_for("home", username=g.user.username)) return render_template("upload.html", form=form, user=g.user)
def mutate(self, info, username, email): ifUser = User.query.filter_by(username=username).first() if ifUser is not None: raise Exception('user exists!') user = User(username=username, email=email) db_session.add(user) db_session.commit() return AddUser(user=user)
def change_active_role(self, user, role): r = Role.query.filter_by(name=role).first() u = User.query.filter_by(username=user).first() u.active_role = r.name if not u.active_role: u.active_role = '' db_session.add(u) db_session.commit()
def addSpelling(item, spelling): itemSpelling = ItemSpelling.query.filter(and_(ItemSpelling.item == item, ItemSpelling.spelling == spelling)).first() if itemSpelling == None: db_session.add(ItemSpelling(item, spelling)) db_session.commit() itemSpelling = ItemSpelling.query.filter(and_(ItemSpelling.item == item, ItemSpelling.spelling == spelling)).first() itemSpelling.occurrences += 1 db_session.commit()
def shutdown_session(response_or_exc): try: sb.commit() except Exception as e: # logging.exception(e) pass finally: sb.remove() return response_or_exc
def sign_up(): content = request.get_json() print(content) db_session.add(Company(content['email'], content['companyName'], pbkdf2_sha256.hash(content['password']), content['countryId'], content['country'])) db_session.commit() company = Company.query.filter_by(email=content['email']).first() add_user(content['email'], content['password'], company.id, user_type="Owner") return "SUCCESS", status.HTTP_202_ACCEPTED
def login(): form = LoginForm() if form.validate_on_submit(): user = User('Joff', 'joff69', '*****@*****.**', 'f**k you') db.add(user) db.commit() user = User.query.filter_by(username=form.username.data).first() print(user) return render_template('login.html', title='Sign In', form=form)
def makeApprover(self, user): if self.role >= ROLE_ADMIN: user.role = ROLE_APPROVER db_session.merge(user) db_session.commit() return True return False
def makeAdmin(self, user): if self.role >= ROLE_ADMIN: user.role = ROLE_ADMIN db_session.merge(user) db_session.commit() return True return False
def disable(self, user): if self.role >= ROLE_ADMIN: user.disabled = 1 db_session.merge(user) db_session.commit() return True return False
def confirm_offsetDays(user): u = User.query.filter_by(username=user).first() us = UserStatistics.query.filter_by(userId=u.id).first() us.offset = int(us.proposed_offset) + int(us.offset) us.proposed_offset = 0 db_session.add(us) db_session.commit() flash('Number of offset days confirmed.') return redirect(url_for('.approval_of_leaves'))
def before_request(): if 'user' in session: g.user = pickle.loads(session['user']) g.user.last_seen = datetime.now() from app.database import db_session db_session.add(g.user) db_session.commit() else: g.user = None
def add_all_episodes(): for ep in all_episodes(episodes): t = titles.loc[titles['tconst'] == ep].to_dict('records')[0] e = episodes.loc[episodes['tconst'] == ep].to_dict('records')[0] r = ratings.loc[ratings['tconst'] == ep].to_dict('records') db_session.add(episode_obj(ep, t, e, r)) db_session.commit() db_session.close()
def delete(self, user_id): if not current_user.is_admin: abort(403) user = User.query.get(user_id) if user.is_admin: abort(400) db_session.delete(user) db_session.commit() return '', 204
def wrapper(*args, **kwargs): if kwargs.get("id_from_token" ) is not None and kwargs["id_from_token"] is not None: if kwargs["id_from_token"] != 0: user = db.query(User).filter_by( id=kwargs["id_from_token"]).first() user.last_seen = datetime.utcnow() db.commit() return func(*args, **kwargs)
def register(): form = RegistrationForm() if form.validate_on_submit(): user = User(username=form.username.data, password=form.password.data) db_session.add(user) db_session.commit() flash('you can now login') return redirect(url_for('auth.login')) return render_template('auth/register.html', form=form)