def customerEdit(customer_id): # pdb.set_trace() # this page will be for creating API Clients try: customer = db_session.query(User_Customer).filter_by(id=customer_id) if customer.first(): if request.method == 'POST': customer.update({ "name": request.form['customerName'], "phone": request.form['customerPhone'], "email": request.form['customerEmail'], 'status': request.form['customerStatus']}) db_session.commit() flash('%s was sucessfully updated!' % request.form['customerName']) # return redirect(url_for('customerEdit', customer_id=customer.one().id)) return redirect(url_for('Customers', customers=db_session.query(User_Customer).filter_by( user_id=current_user.id).all())) else: # pdb.set_trace() return render_template('/customers/customerEdit.html', customer=customer.one()) else: flash('Customer with Id %s not found!' % customer_id) # return render_template('/customers/customers.html') return redirect(url_for('Customers', customers=db_session.query(User_Customer).filter_by( user_id=current_user.id).all())) except: db_session.rollback() db_session.commit() flash('Something went wrong, rolling back transactions!') return redirect(url_for('Customers', customers=db_session.query(User_Customer).filter_by( user_id=current_user.id).all()))
def newInboundMessage(): """ This page will be for all inbound messages, check if customer exists if so, check content of message if == "UNSUBSCRIBE", change user status. If customer does not exist add to database. """ try: print ('requestform', request.form) tel = str(request.form['To']) user = db_session.query(User).filter_by( phone=tel).one() if user: customer = db_session.query( User_Customer).filter_by(phone=request.form['From']).first() if customer: if request.form['Text'] == "UNSUBSCRIBE": customer.status = "UNSUBSCRIBED" else: customer = User_Customer( name='UNKNOWN', phone=request.form['From'], user_id=user.id, status="SUBSCRIBED") db_session.add(customer) db_session.commit() newMessage = Message( user_id=user.id, user_customer_id=customer.id, message_uuid=request.form['MessageUUID'], message=request.form['Text'], direction="inbound", status="RECEIVED", units=request.form["Units"], total_rate=request.form["TotalRate"], total_amount=request.form["TotalAmount"], error_code="200", message_time=datetime.datetime.now()) db_session.add(newMessage) db_session.commit() return jsonify(newMessage.serialize) except: print('Something went wrong, rolling back transaction!') db_session.rollback() db_session.commit()
def dislikes(): if request.method == "PUT": user_id = session['user_id'] post_id = request.form['post_id'] user = db_session.query(User).filter(User.user_id == user_id).first() post = db_session.query(Post).filter(Post.post_id == post_id).first() dislike_found = db_session.query(Dislike).filter( Dislike.post_id == post_id and Dislike.user_id == user_id).first() if dislike_found is None: new_dislike = Dislike() user.user_dislikes.append(new_dislike) post.post_dislikes.append(new_dislike) post.dislike_number += 1 db_session.add(new_dislike) # remove old like old_like = db_session.query(Like).filter( Like.post_id == post_id and Like.user_id == user_id).first() if old_like is not None: db_session.delete(old_like) post.like_number -= 1 db_session.commit() data = {"dislike_post": True} else: dislike = db_session.query(Dislike).filter( Dislike.post_id == post_id and Dislike.user_id == user_id).first() post.dislike_number -= 1 db_session.delete(dislike) db_session.commit() data = {"dislike_post": False} return gen_json_success(data)
def get_topneighbors_rateditem(id_user, id_movie, N): """ :param id_user: user id :param id_movie: movie id :param N: number of users that will return :return: return the N-top users most similar to id_user that rated id_movie """ users_movie = db_session.query(Ratings).filter( Ratings.movie_id == id_movie, Ratings.user_id != id_user).all() if not users_movie: return [] similar = [] for item in users_movie: user_ = item.user_id similarity_register = db_session.query( UserSimilarity.similarity).filter( UserSimilarity.id_user_x == id_user, UserSimilarity.id_user_y == user_).first() if not similarity_register: similarity_value = 0.0 else: similarity_value = float(similarity_register[0]) similar.append((user_, similarity_value)) sorted_ = sorted(similar, key=operator.itemgetter(1), reverse=True) return sorted_[:N]
def restaurantMenuJSON(restaurant_id): pdb.set_trace() restaurant = db_session.query(Restaurant).filter_by(id=restaurant_id) menuItems = db_session.query(MenuItem).filter_by( restaurant_id=restaurant_id).all() return jsonify(Restaurant=[i.serialize for i in restaurant], MenuItems=[i.serialize for i in menuItems])
def apiRoomDeleteScore(roomid, scoreid): if request.method == 'DELETE': if request.headers['Content-Type'] == 'application/json': db_room = db_session.query(Room).filter_by(id=roomid).first() db_session.query(Score).filter_by(id=scoreid, room_id=db_room.id).delete() db_session.commit() return jsonify('ok') abort(400)
def add_asso_group(): if request.method == 'POST': try: request_key = request.form.keys()[0] get_user_id = int(request_key.split('-')[1]) get_group_id = int(request.form.get(request_key, '')) assouser = db_session.query(GitUser).filter_by( id=get_user_id).first() assogroup = db_session.query(GitGroup).filter_by( id=get_group_id).first() if assogroup not in assouser.git_group: assouser.git_group.append(assogroup) assos = db_session.query(asso_group_user).all() if (get_group_id, get_user_id) not in assos: try: db_session.add(assouser) db_session.commit() print '====> Store (%s) to DB successfully.' % assouser.name assogroup_file = BASE_DIR + '/conf/groups/' \ + assogroup.name + '.conf' gconf_dict = {} with open(assogroup_file, 'rb') as f: lines = f.readlines() for line in lines: gconf_group = line.split('=')[0].lstrip( '@').strip() gconf_user = line.split('=')[1].split() gconf_dict[gconf_group] = gconf_user allowed_ext_user = [] for _ in allowed_ext: allowed_ext_user.append('.'.join( assouser.name.split('.')[:-1])) for _ in set(allowed_ext_user): if gconf_dict.has_key( assogroup.name) and _ not in gconf_dict[ assogroup.name]: gconf_dict[assogroup.name].append(str(_)) f = open(assogroup_file, 'wb') f.truncate() for _ in gconf_dict: f.write('@' + _ + ' = ' + ' '.join(gconf_dict[_])) f.close() except TypeError: db_session.rollback() print '====> TypeError Need string or buffer, list found.' finally: db_session.close() else: print '====> The record(%s) already exists.' % assouser.name except IndexError: print '====> IndexError because of out of range.' return redirect(url_for('user'))
def user_remove(): if request.method == 'POST': try: remove_user_name = request.form.keys()[0] except IndexError: remove_user_name = '' assouser = db_session.query(GitUser).filter_by( name=remove_user_name).first() assogroup_relation = db_session.query(asso_group_user).filter_by( git_user_id=assouser.id).all() assogroup_list = [] for _ in assogroup_relation: assogroup = db_session.query(GitGroup).filter_by( id=_.git_group_id).first() assogroup_list.append(assogroup) if not assogroup_list: for assogroup in assogroup_list: assouser.git_group.remove(assogroup) db_session.delete(assouser) db_session.delete(assouser) db_session.commit() deleteuser_assogroup = [] for _ in assogroup_list: deleteuser_assogroup_file = BASE_DIR \ + '/conf/groups/' + _.name + '.conf' deleteuser_assogroup.append(deleteuser_assogroup_file) gconf_dict = {} for i in deleteuser_assogroup: with open(i, 'rb') as f: lines = f.readlines() for line in lines: gconf_group = line.split('=')[0].lstrip('@').strip() gconf_user = line.split('=')[1].split() gconf_dict[gconf_group] = gconf_user assouser.name = '.'.join(assouser.name.split('.')[:-1]) assouser_name = str(assouser.name) for each_group in gconf_dict: if assouser_name in gconf_dict[each_group]: gconf_dict[each_group].remove(assouser_name) assogroup_file = BASE_DIR + '/conf/groups/' + each_group \ + '.conf' f = open(assogroup_file, 'wb') f.truncate() f.write('@' + each_group + ' = ' + ' '.join(gconf_dict[each_group])) f.close() db_session.close() user_name_file = os.path.join(KEY_DIR, remove_user_name) os.remove(user_name_file) return redirect(url_for('user'))
def update_courier_rating(courier_id, new_rating): if CourierRating.courier_rating_exist(courier_id): db_session.query(CourierRating) \ .filter(CourierRating.courier_id == courier_id) \ .update({CourierRating.rating: new_rating}) else: db_session.add( CourierRating( courier_id=courier_id, rating=new_rating, updated=arrow.utcnow().datetime ) ) db_session.commit()
def apiClientDelete(api_client_id): try: client = db_session.query(User_Api_Client).get(api_client_id) db_session.delete(client) db_session.commit() flash("%s was sucessfully Deleted!" % client.name) clients = db_session.query(User_Api_Client).filter_by( user_id=current_user.id).all() return render_template('/apiClients/apiClients.html', clients=clients) except: flash("Something went wrong rolling back transaction!" % client.name) print('some error could not save transaction, rolling back') db_session.rollback() db_session.commit()
def repo_rename(): if request.method == 'POST': try: old_reponame = request.form.keys()[0] except IndexError: old_reponame = '' new_reponame = request.form.get(old_reponame, '') old_name_file = BASE_DIR + '/conf/repos/' \ + old_reponame + '.conf' new_name_file = BASE_DIR + '/conf/repos/' \ + new_reponame + '.conf' if new_reponame.strip() != '' and new_reponame != old_reponame: renamerepo = db_session.query(GitRepo).filter_by( name=old_reponame).first() renamerepo.name = new_reponame db_session.commit() db_session.close() #~ repodict.pop(old_reponame) new_lines = [] with open(old_name_file, 'rb') as f: while True: lines = f.readlines(8192) if not lines: break for line in lines: line = line.rstrip('\n') line = re.sub('@' + old_reponame, '@' + new_reponame, line) new_lines.append(line) with open(old_name_file, 'wb') as f: f.truncate() for _ in new_lines: print >> f, _ os.rename(old_name_file, new_name_file) return redirect(url_for('repo'))
def deleteRestaurant(restaurant_id): # this page will be for deleting restaurant if request.method == 'POST': restaurant = db_session.query(Restaurant).filter_by( id=restaurant_id).one() menuItems = db_session.query(MenuItem).filter_by( restaurant_id=restaurant_id).all() db_session.delete(restaurant) db_session.commit() flash('The %s Restaurant was successfully deleted!' % restaurant.name) return redirect(url_for('showRestaurants')) restaurant = db_session.query(Restaurant).filter_by(id=restaurant_id).one() return render_template('deleteRestaurant.html', restaurant=restaurant, current_user=current_user)
def editRestaurant(restaurant_id): if request.method == 'POST': restaurant = db_session.query(Restaurant).filter_by( id=restaurant_id).one() restaurant.name = request.form['name'] db_session.add(restaurant) db_session.commit() flash('The %s Restaurant was sucessfully updated!' % restaurant.name) return redirect(url_for('editRestaurant', restaurant_id=restaurant.id)) else: restaurant = db_session.query(Restaurant).filter_by( id=restaurant_id).one() # this page will be for editing restaurant return render_template('editRestaurant.html', restaurant=restaurant, current_user=current_user)
def user_similarity_db(): """ :return: calculate all users similarity and insert this information in dabase """ deleted_rows = db_session.query(UserSimilarity).delete() db_session.commit() print("Deleted %i rows" % deleted_rows) local_ = utils.pre_get_movies_by_user() all_users = utils.get_all_users() for i in all_users: print("Calculating similarity of user %i" % i) for j in all_users: if i < j: value = similarity_value(i, j, local_) similarity_instance = UserSimilarity(i, j, value) db_session.add(similarity_instance) db_session.commit()
def get_movies_by_user(user_id): result_ = (db_session.query( Movies, MoviesIMDb, Ratings).filter(Users.id == Ratings.user_id).filter( MoviesIMDb.id == Ratings.movie_id).filter( Movies.id == Ratings.movie_id)).filter( Users.id == user_id).all() watched_movies = [] for object_ in result_: movie = object_[0] movie_imdb = object_[1] movie_ratings = object_[2] object_movie = { 'id': movie.id, 'title': movie_imdb.title, 'year': movie_imdb.year, 'image_url': movie_imdb.image_url, 'rating': movie_ratings.rating, 'rating_star': convert_rating_stars(movie_ratings.rating) } watched_movies.append(object_movie) return watched_movies
def apiClientEdit(api_client_id): # pdb.set_trace() # this page will be for creating API Clients try: client = db_session.query(User_Api_Client).filter_by(id=api_client_id) if client.one(): if request.method == 'POST': client.update({ "name": request.form['name'], "api_id": aes_encrypt(request.form['api_id']), "auth_id": aes_encrypt(request.form['auth_id'])}) db_session.commit() flash('%s was sucessfully updated!' % request.form['name']) return redirect(url_for('apiClientEdit', api_client_id=api_client_id)) else: # pdb.set_trace() apiClient = client.one() id = apiClient.id api_id = aes_decrypt(apiClient.api_id) auth_id = aes_decrypt(apiClient.auth_id) name = apiClient.name return render_template('/apiClients/apiClientEdit.html', id=id, api_id=api_id, auth_id=auth_id, clientName=name) else: flash('API Client Id %s not found!' % api_client_id) return render_template('/apiClients/apiClients.html') except: print('some error could not save transaction, rolling back') db_session.rollback() db_session.commit() flash('API Client Id %s not found!' % api_client_id) return render_template('/apiClients/apiClients.html')
def create_post(): user_id = session['user_id'] user = db_session.query(User).filter(User.user_id == user_id).first() title = request.form['post_title'] content = request.form['post_content'] location_description = request.form['location_description'] longitude = request.form['longitude'] latitude = request.form['latitude'] style = request.form['post_style'] has_cipher = request.form['has_cipher'] cipher = request.form['post_cipher'] has_picture = request.form['has_picture'] new_post = Post(title=title, content=content, location_description=location_description, longitude=longitude, latitude=latitude, style=style, has_cipher=has_cipher, has_picture=has_picture, cipher=cipher, create_time=datetime.now().strftime("%Y-%m-%d %H:%M:%S")) db_session.add(new_post) user.posts.append(new_post) db_session.commit() if has_picture == '1': post_picture = request.files['post_picture'] post_picture.save(sys.path[0] + "/post_picture/" + str(new_post.post_id) + ".png") app.logger.info("User %s created post successfully.", user_id) return gen_json_success(None)
def get_post(post_id): if request.method == "GET": user_id = session['user_id'] post = db_session.query(Post).filter(Post.post_id == post_id).first() if request.args.get( 'has_cipher' ) == "1" and post.cipher != request.args.get('cipher'): app.logger.info("User %s failed to get post detail. (%d)", user_id, POST_CIPHER_WRONG) return gen_json_failure(POST_CIPHER_WRONG) data = {"post": post.as_dict()} # 是否已点赞 likes = post.post_likes for like in likes: if like.user_id == user_id: data['has_liked'] = 1 break else: data['has_liked'] = 0 # 是否已点踩 dislikes = post.post_dislikes for dislike in dislikes: if dislike.user_id == user_id: data['has_disliked'] = 1 break else: data['has_disliked'] = 0 app.logger.info("User %s got post detail.", user_id) return gen_json_success(data)
def add_comment(): user_id = session['user_id'] post_id = request.form['post_id'] user = db_session.query(User).filter(User.user_id == user_id).first() post = db_session.query(Post).filter(Post.post_id == post_id).first() content = request.form['comment_content'] new_comment = Comment( content=content, create_time=datetime.now().strftime("%Y-%m-%d %H:%M:%S")) post.post_comments.append(new_comment) post.comment_number += 1 user.user_comments.append(new_comment) db_session.add(new_comment) db_session.commit() data = {'comment': new_comment.as_dict()} return gen_json_success(data)
def get_uptime_for_team(ateam): event = Event.query.order_by(Event.id.desc()).first() # get all tss from a team grouped by services tsss1 = db_session.query( label('count', func.count(TeamServiceState.id)), TeamServiceState.challenge_id, ).group_by(TeamServiceState.challenge_id, ).filter_by(attending_team=ateam) total_counts = {} for tss in tsss1: total_counts[tss[1]] = tss[0] # get all tss from a team with state 2 where service is up grouped by service tsss2 = db_session.query( label('count', func.count(TeamServiceState.id)), TeamServiceState.challenge_id, ).group_by(TeamServiceState.challenge_id, ).filter_by(attending_team=ateam, state=2) up_counts = {} for tss in tsss2: up_counts[tss[1]] = tss[0] uptimes = {} for service_id in total_counts.keys(): total = total_counts[service_id] up = 0 try: up = up_counts[service_id] except: pass uptime = ((up * 1.0) / (total * 1.0)) * 100 uptimes[service_id] = uptime # now average all the uptimes total = 0 for service_id in uptimes.keys(): total += uptimes[service_id] if len(uptimes) == 0: return 0 return total / len(uptimes)
def apiDevicesScreenOn(): devices = db_session.query(Device).all() for device in devices: device.screen_enable = True db_session.commit() return jsonify("ok")
def showMenu(restaurant_id): # this page will be for showing restaurant %s menu restaurant = db_session.query(Restaurant).filter_by(id=restaurant_id).one() menuItems = db_session.query(MenuItem).filter_by( restaurant_id=restaurant_id).group_by('course', 'id').all() courses = [] for el in menuItems: if el.course not in courses: courses.append(el.course) for el in courses: print(el) print(len(courses)) return render_template('menuItems.html', restaurant=restaurant, menuItems=menuItems, courses=courses, current_user=current_user)
def apiRoomUpdate(roomid): if request.method == 'POST': if request.headers['Content-Type'] == 'application/json': db_room = db_session.query(Room).filter_by(id=roomid).first() db_room.name = request.json['name'] db_room.description = request.json['description'] db_room.profile_image = request.json['profile_image'] db_room.bg_image = request.json['bg_image'] db_session.commit() return jsonify(db_room.serialize()) abort(400) elif request.method == 'DELETE': if request.headers['Content-Type'] == 'application/json': db_session.query(Room).filter_by(id=roomid).delete() db_session.commit() return jsonify('ok') abort(400)
def remove_asso_group(): if request.method == 'POST': try: request_key = request.form.keys()[0] get_user_id = int(request_key.split('-')[1]) get_group_id = request.form.get(request_key, '') assouser = db_session.query(GitUser).filter_by( id=get_user_id).first() assogroup = db_session.query(GitGroup).filter_by( id=get_group_id).first() assouser.git_group.remove(assogroup) db_session.add(assouser) db_session.commit() print '====> Sponge (%s) from DB successfully.' % assouser.name assogroup_file = BASE_DIR + '/conf/groups/' \ + assogroup.name + '.conf' gconf_dict = {} with open(assogroup_file, 'rb') as f: lines = f.readlines() for line in lines: gconf_group = line.split('=')[0].lstrip('@').strip() gconf_user = line.split('=')[1].split() gconf_dict[gconf_group] = gconf_user allowed_ext_user = [] for _ in allowed_ext: allowed_ext_user.append('.'.join( assouser.name.split('.')[:-1])) for _ in set(allowed_ext_user): if gconf_dict.has_key( assogroup.name) and _ in gconf_dict[assogroup.name]: gconf_dict[assogroup.name].remove(str(_)) f = open(assogroup_file, 'wb') f.truncate() for _ in gconf_dict: f.write('@' + _ + ' = ' + ' '.join(gconf_dict[_])) f.close() except IndexError: db_session.rollback() print '====> IndexError Out of range.' except ValueError: db_session.rollback() print '====> ValueError Not in list.' finally: db_session.close() return redirect(url_for('user'))
def get_all_users(): """ :return: a list of ids with all users of dataset """ result_ = db_session.query(Users.id).all() return [id for (id, ) in result_]
def get_all_movies(): """ :return: return all movies of database """ result_ = db_session.query(Movies.id).all() return result_
def customerDelete(customer_id): try: customer = db_session.query(User_Customer).get(customer_id) db_session.delete(customer) db_session.commit() flash("%s was sucessfully Deleted!" % customer.name) customers = db_session.query(User_Customer).filter_by( user_id=current_user.id).all() return render_template('/customers/customers.html', customers=customers) except: print('some error could not save transaction, rolling back') db_session.rollback() db_session.commit() flash("Encountered some errors, rolling back transactions") customers = db_session.query(User_Customer).filter_by( user_id=current_user.id).all() return render_template('/customers/customers.html', customers=customers)
def get_comments(): post_id = request.args.get('post_id') post = db_session.query(Post).filter(Post.post_id == post_id).first() comments = post.post_comments comment_list = [] for comment in comments: comment_list.append(comment.as_dict()) data = {"comments": comment_list} return gen_json_success(data)
def apiStreamUpdate(streamid): if request.method == 'POST': if request.headers['Content-Type'] == 'application/json': db_stream = db_session.query(Stream).filter_by(id=streamid).first() db_stream.name = request.json['name'] db_stream.url = request.json['url'] db_stream.width = request.json['width'] db_stream.height = request.json['height'] db_stream.orientation = request.json['orientation'] db_session.commit() return jsonify(db_stream.serialize()) abort(400) elif request.method == 'DELETE': if request.headers['Content-Type'] == 'application/json': db_session.query(Stream).filter_by(id=streamid).delete() db_session.commit() return jsonify('ok') abort(400)
def newMessage(): try: # This page will be for creating a new Customer customers = db_session.query( User_Customer).filter_by(user_id=current_user.id).all() if request.method == 'POST': apiClient = db_session.query(User_Api_Client).filter_by( user_id=current_user.id).all()[0] destinationNumbers = list(map(lambda x: db_session.query(User_Customer).filter_by( id=int(x)).one().phone, request.form.getlist('customerSelect'))) # Commented out to not make unnecessary api calls client = plivo.RestClient( auth_id=aes_decrypt(apiClient.api_id), auth_token=aes_decrypt(apiClient.auth_id)) response = client.messages.create( src=current_user.phone, dst="<".join(destinationNumbers), text=request.form['message'], url="https://sms-messages.herokuapp.com/message/status") # message_uuid = [] # for i in destinationNumbers: # message_uuid.append(datetime.datetime.now()) # response = {'message_uuid': message_uuid} # uncomment below when using api for i, uuid in enumerate(response.message_uuid, 0): # uncomment below when not using api # for i, uuid in enumerate(response['message_uuid'], 0): newMessage = Message( user_id=current_user.id, user_customer_id=int(request.form.getlist('customerSelect')[i]), message_uuid=uuid, message=request.form['message'], direction="outbound") db_session.add(newMessage) db_session.commit() flash('The message was sucessfully created!') return redirect(url_for('newMessage', customers=customers)) else: return render_template('/messages/newMessage.html', customers=customers) except: print('some error could not save transaction, rolling back') db_session.rollback() db_session.commit() flash('There was some errors and some of your messages my have Failed!') return render_template('/messages/newMessage.html', customers=customers)
def create_user(data): user = None data = data.get('data') if data: user_id = data.get('id') if user_id: user = db_session.query(User).get(user_id) else: user = User(data.get('login'),data.get('name'),data.get('password'),data.get('email')) db_session.add(user) db_session.commit() return jsonify({u'user': orm_to_dict(user) if user else None})
def find_user_work_experiences(user, limit=10, page=1): """ 获取用户的工作经历 """ condition = [UserEmployer.user_id == user.id] employers_query = UserEmployer.query count_query = db_session.query(func.count(UserEmployer.id)) employers_query = employers_query.filter(*condition) count_query = count_query.filter(*condition) employers, pages = inquiry_process(count_query, employers_query, limit=limit, page=page) return employers, pages
def update_user(data): user = None data = data.get('data') if data: user_id = data.get('user_id') if user_id: user = db_session.query(User).get(user_id) if user: user.login = data.get('login') user.name = data.get('name') user.password = data.get('password') user.email = data.get('email') db_session.commit() return jsonify({u'user': orm_to_dict(user) if user else None})
def del_user_work_experiences(id): db_session.query(UserEmployer).filter(UserEmployer.id == id).delete() db_session.commit()
def refresh_user(data): user = None if data['id']: user = db_session.query(User).get(data['id']) return jsonify({u'user': orm_to_dict(user) if user else None})
def get_all_users(): q = db_session.query(User) users = q.all() return jsonify({u'users': orm_to_dict(users) if users else None})