def homepage(): """Show homepage.""" recipes = db.session.query(Recipe).order_by( Recipe.id.desc()).limit(15).all()[::-1] veggies = util.partition_list( db.session.query(Product).filter_by(product_type='veggies').all(), 6) fruits = util.partition_list( db.session.query(Product).filter_by(product_type='fruits').all(), 6) nuts_seeds = util.partition_list( Product.query.filter( db.or_(Product.product_type == 'nuts', Product.product_type == 'seeds')).all(), 6) fats_oils = util.partition_list( Product.query.filter( db.or_(Product.product_type == 'healthy fats', Product.product_type == 'healthy oils')).all(), 6) sweeteners = util.partition_list( db.session.query(Product).filter_by(product_type='sweetener').all(), 6) result_rec = r_util.get_carousel_card_info(recipes) return render_template("index.html", recipes=result_rec, veggies=veggies, fruits=fruits, nuts_seeds=nuts_seeds, fats_oils=fats_oils, sweeteners=sweeteners, flag=True, state='active')
def action_batch_alter(self, ids): try: if request.form['promotion_id'] is '': raise Exception(lazy_gettext('No new promotion ID entered.')) new_promotion_id = int(request.form['promotion_id']) new_promotion = Promotion.query.filter_by(id=new_promotion_id).one_or_none() if new_promotion is None: raise Exception(lazy_gettext('New promotion not found.')) user_promotion_ids = [(id_pair.split(',')[0], id_pair.split(',')[1]) for id_pair in ids] user_promotions = UserPromotion.query.filter( db.or_( db.and_(UserPromotion.user_id == user_id, UserPromotion.promotion_id == promotion_id) for user_id, promotion_id in user_promotion_ids )) count = 0 for user_promotion in user_promotions.all(): user_promotion.promotion_id = new_promotion_id self.session.add(user_promotion) count += 1 self.session.commit() flash(lazy_gettext("Successfully Changed") + f" {count} " + lazy_gettext("Records")) logger.info(f'Batch UserPromotion change by admin {auth_get_current_username()} changed {count} UserPromotions') except Exception as ex: self.session.rollback() flash(lazy_gettext("Error ") + f"{str(ex)}") logger.exception(f'Batch UserPromotion change by admin {auth_get_current_username()} raised exception')
def build_query(self, resource_type, params, id_only=False): ''' Compile a SQL query from a set of FHIR search params If `id_only` is true, a SQL query that selects only `resource_id` will be returned ''' query_args = [Resource.visible == True, Resource.resource_type == resource_type, Resource.owner_id == self.owner_id] valid_search_params = SPECS[resource_type]['searchParams'] make_pred = partial(self.make_pred_from_param, resource_type, possible_param_types=valid_search_params) predicates = [pred for pred in map(make_pred, iterdict(params)) if pred is not None] # customized coordinate search parameter if 'coordinate' in params and resource_type == 'Sequence': coords = params['coordinate'].split(',') coord_preds = map(make_coord_pred, coords) query_args.append(db.or_(*coord_preds)) if len(predicates) > 0: query_args.append( Resource.resource_id.in_(intersect_predicates(predicates).alias())) if '_id' in params: query_args.append(Resource.resource_id.in_(params['_id'].split(','))) if id_only: return db.select([Resource.resource_id]).\ select_from(Resource).\ where(db.and_(*query_args)).alias() else: return Resource.query.filter(*query_args)
def display_all_image(): """ Route for displaying all images """ # search function if request.args.get("search"): pictures = Picture.query.filter( db.or_( Picture.caption.ilike(f'%{request.args.get("search")}%'), Picture.photographer.ilike( f'%{request.args.get("search")}%'))).all() else: pictures = Picture.query.all() # format the url and append to an array picturesUrl = [] for picture in pictures: picturesUrl.append({ "url": f'{IMAGE_URL}{picture.id}', "id": f'{picture.id}', "photog": f'{picture.photographer}', "caption": f'{picture.caption}' }) return render_template("all_pictures.html", pictures=picturesUrl)
def is_applicant_user_id(user_id): user = db.session.query(User).filter(User.id == user_id).join( Application, Application.user_id == User.id, ).filter( db.or_( db.not_(Application.is_concluded), db.and_(Application.is_accepted, db.not_(Application.is_invited)))).one_or_none() return user is not None
def search(): text = request.args['text'] result = Post.query.filter(db.or_( Post.title.like(f'%{text}%'), Post.body.like(f'%{text}%') )).all() if len(result) == 1: return redirect(url_for('/index/<int:article_id>', article_id=result[0].id)) return render_template('index.html', header=f'Поиск по слову "{text}"', articles=result)
def is_applicant_character_id(character_id): base = db.session.query(Character).filter(Character.id == character_id, ) character = base.join(User, User.id == Character.user_id).join( Application, Application.user_id == User.id, ).filter( db.or_( db.not_(Application.is_concluded), db.and_(Application.is_accepted, db.not_(Application.is_invited)))).first() return character is not None
def get_applicant_list(current_user=None): if not (is_recruiter(current_user) or is_admin(current_user)): raise ForbiddenException('User must be recruiter or admin.') result = {} for user in User.query.join( Application, Application.user_id == User.id).filter( db.and_( Application.is_submitted, db.or_( db.not_(Application.is_concluded), db.and_(Application.is_accepted, db.not_(Application.is_invited))))): recruiter_name = None application = Application.query.filter_by( user_id=user.id, is_concluded=False).one_or_none() if application is None: application = Application.query.filter_by( user_id=user.id, is_accepted=True, is_invited=False).one_or_none() application_status = 'new' if application: recruiter_id = application.recruiter_id if recruiter_id: recruiter = User.get(recruiter_id) recruiter_name = recruiter.name application_status = 'claimed' if application.is_accepted: application_status = 'accepted' applicant_visible = False # senior recruiters see all if is_senior_recruiter(current_user) or is_admin(current_user): applicant_visible = True elif is_recruiter(current_user): if application and application.recruiter_id == current_user.id: applicant_visible = True else: applicant_visible = application_status == 'new' if applicant_visible: result[user.id] = { 'user_id': user.id, 'recruiter_id': application.recruiter_id if application else None, 'recruiter_name': recruiter_name, 'status': application_status, 'name': user.name, } return {'info': result}
def make_pred_from_param(self, resource_type, param_and_val, possible_param_types): ''' Compile FHIR search parameter into a SQL predicate This is the "master" function that invokes other `make_*_pred` functions. `param_and_val` is the key-value pair of a parameter and its value `possible_param_types` is a dictionary maintaining the mapping between a name of a search parameter and it's type (string, number, etc). ''' raw_param, param_val = param_and_val matched_param = PARAM_RE.match(raw_param) if matched_param is None: # invalid search param return None param_data = matched_param.groupdict() param = param_data['param'] modifier = param_data['modifier'] if param not in possible_param_types: # an undefined search parameter is supplied return None param_type = possible_param_types[ param] if modifier != 'text' else 'string' if modifier == 'missing': pred = ((SearchParam.missing == True) if param_val == 'true' else (SearchParam.missing == False)) else: if param_type == 'reference': pred_maker = partial(self.make_reference_pred, resource_type=resource_type) elif param_type in PRED_MAKERS: pred_maker = PRED_MAKERS[param_type] if pred_maker is None: raise InvalidQuery else: pred_maker = make_string_pred # deal with FHIR's union search (e.g. `abc=x,y,z`) here alts = param_val.split(',') preds = [pred_maker(param_data, alt) for alt in alts] pred = db.or_(*preds) return db.and_( pred, SearchParam.name == param, SearchParam.param_type == possible_param_types[param], #SearchParam.owner_id==self.owner_id )
def make_pred_from_param(self, resource_type, param_and_val, possible_param_types): ''' Compile FHIR search parameter into a SQL predicate This is the "master" function that invokes other `make_*_pred` functions. `param_and_val` is the key-value pair of a parameter and its value `possible_param_types` is a dictionary maintaining the mapping between a name of a search parameter and it's type (string, number, etc). ''' raw_param, param_val = param_and_val matched_param = PARAM_RE.match(raw_param) if matched_param is None: # invalid search param return None param_data = matched_param.groupdict() param = param_data['param'] modifier = param_data['modifier'] if param not in possible_param_types: # an undefined search parameter is supplied return None param_type = possible_param_types[param] if modifier != 'text' else 'string' if modifier == 'missing': pred = ((SearchParam.missing == True) if param_val == 'true' else (SearchParam.missing == False)) else: if param_type == 'reference': pred_maker = partial(self.make_reference_pred, resource_type=resource_type) elif param_type in PRED_MAKERS: pred_maker = PRED_MAKERS[param_type] if pred_maker is None: raise InvalidQuery else: pred_maker = make_string_pred # deal with FHIR's union search (e.g. `abc=x,y,z`) here alts = param_val.split(',') preds = [pred_maker(param_data, alt) for alt in alts] pred = db.or_(*preds) return db.and_(pred, SearchParam.name==param, SearchParam.param_type==possible_param_types[param], SearchParam.owner_id==self.owner_id)
def build_query(self, resource_type, params, id_only=False): ''' Compile a SQL query from a set of FHIR search params If `id_only` is true, a SQL query that selects only `resource_id` will be returned ''' query_args = [ Resource.visible == True, Resource.resource_type == resource_type, #Resource.owner_id == self.owner_id or Resource.owner_id=='0' ] valid_search_params = SPECS[resource_type]['searchParams'] make_pred = partial(self.make_pred_from_param, resource_type, possible_param_types=valid_search_params) predicates = [ pred for pred in map(make_pred, iterdict(params)) if pred is not None ] #print params # customized coordinate search parameter if 'coordinate' in params and resource_type == 'Sequence': coords = params['coordinate'].split(',') coord_preds = map(make_coord_pred, coords) query_args.append(db.or_(*coord_preds)) if len(predicates) > 0: query_args.append( Resource.resource_id.in_( intersect_predicates(predicates).alias())) if '_id' in params: query_args.append( Resource.resource_id.in_(params['_id'].split(','))) if id_only: return db.select([Resource.resource_id]).\ select_from(Resource).\ where(db.and_(*query_args)).alias() else: return Resource.query.filter(*query_args)
def make_string_pred(param_data, param_val): ''' Comiple a string search parameter into a SQL predicate When we store a resource in database, we store any text associated text search param by enclosing them in a pair of "::". E.g. "hello, world!" would be stored like this "::hello, world::". This is so that an exact search can be done simply by surrounding a the searched text with "::". (So a search like this `greeting:exact=hello world` will be translated like this SELECT ... FROM ... WHERE ... like "%::hello world::%"). ''' if param_data['modifier'] == 'exact': return SearchParam.text.like('%%::%s::%%' % param_val) else: # we split the search param here so that # an (inexact) search like "hello world" will get a hit # for text like "hello tom" even though the whole text might not be hit. preds = [SearchParam.text.ilike('%%%s%%' % text) for text in param_val.split()] return db.or_(*preds)
def homepage(): """Show homepage: - anon users: no messages - logged in: 100 most recent messages of followed_users """ if g.user: # get list of ids of users the logged-in user is following following = g.user.following following_ids = [user.id for user in following] messages = (Message.query.filter( db.or_(Message.user_id.in_(following_ids), Message.user_id == g.user.id)).order_by( Message.timestamp.desc()).limit(100).all()) return render_template('home.html', messages=messages) else: return render_template('home-anon.html')
def homepage(): """Show homepage: - anon users: no messages - logged in: 100 most recent messages of followed_users """ if g.user: following_ids = [user.id for user in g.user.following] messages = (Message.query.filter( db.or_(Message.user_id.in_(following_ids), Message.user_id == g.user.id)).order_by( Message.timestamp.desc()).limit(100).all()) # users = [m.user for m in messages] g_likes = [msg.id for msg in g.user.likes] return render_template('home.html', messages=messages, user_likes=g_likes) else: return render_template('home-anon.html')
def make_quantity_pred(param_data, param_val): ''' Compile a quantity search parameter into a SQL predicate ''' quantity = QUANTITY_RE.match(param_val) if quantity is None: raise InvalidQuery preds = [] if quantity.group('code') is not None: preds.append(SearchParam.code == quantity.group('code')) if quantity.group('system') is not None: preds.append(SearchParam.system == quantity.group('system')) # tough stuff here... because quantity stored in the database can also have comparator # we have to build query based on the comparators from both the search and the db value = quantity.group('number') comparator = quantity.group('comparator') if comparator is None: comparator = '=' val_preds = [] if '<' in comparator: val_preds = [ SearchParam.comparator.in_('<', '<='), SearchParam.comparator.quantity < value ] elif '>' in comparator: val_preds = [ SearchParam.comparator.in_('>', '>='), SearchParam.comparator.quantity > value ] if '=' in comparator: val_preds.append( db.and_(SearchParam.comparator.in_(None, '<=', '>='), SearchParam.quantity == value)) preds.append(db.or_(*val_preds)) return db.and_(*preds)
def make_quantity_pred(param_data, param_val): ''' Compile a quantity search parameter into a SQL predicate ''' quantity = QUANTITY_RE.match(param_val) if quantity is None: raise InvalidQuery preds = [] if quantity.group('code') is not None: preds.append(SearchParam.code == quantity.group('code')) if quantity.group('system') is not None: preds.append(SearchParam.system == quantity.group('system')) # tough stuff here... because quantity stored in the database can also have comparator # we have to build query based on the comparators from both the search and the db value = quantity.group('number') comparator = quantity.group('comparator') if comparator is None: comparator = '=' val_preds = [] if '<' in comparator: val_preds = [ SearchParam.comparator.in_('<', '<='), SearchParam.comparator.quantity < value] elif '>' in comparison: val_preds = [ SearchParam.comparator.in_('>', '>='), SearchParam.comparator.quantity > value] if '=' in comparator: val_preds.append(db.and_( SearchParam.comparator.in_(None, '<=', '>='), SearchParam.quantity == value)) preds.append(db.or_(*val_preds)) return db.and_(*preds)
def signupView(): form = SignUpForm() # 接受返回的数据 if request.method == "POST": if form.validate_on_submit(): userName = request.form.get("user_name") email = request.form.get("user_email") password = request.form.get("password") user = UserInformation(userName=userName, password=password, email=email) # 查看是否已经注册 check_ = ( db.session.query(UserInformation) .filter( db.or_( UserInformation.userName == userName, UserInformation.email == email, ) ) .first() ) if check_ is not None: flash("用户名或邮箱已经注册") return redirect(url_for("webBlueprint.signup")) else: try: # 校验成功,写入 ,并跳转到主页,获取到session db.session.add(user) db.session.commit() login_user(user) session["user"] = user.userName session["userID"] = user.id return redirect(url_for("webBlueprint.index")) except AttributeError as e: flash(e) return redirect(url_for("webBlueprint.signup")) return render_template("sign_up.html", form=form)
def homepage(): """Show homepage: - anon users: no messages - logged in: 100 most recent messages of followed_users """ if g.user: following_ids = [ user.user_being_followed_id for user in Follows.query.filter( g.user.id == Follows.user_following_id) ] messages = (Message.query.filter( db.or_(Message.user_id == g.user.id, Message.user_id.in_(following_ids))).order_by( Message.timestamp.desc()).limit(100).all()) likes = [ l.message_id for l in Likes.query.filter_by(user_id=g.user.id).all() ] return render_template('home.html', messages=messages, likes=likes) else: return render_template('home-anon.html')
def possible_matches(): query_prams = request.args if query_prams: if (('offset' in query_prams) and ('limit' in query_prams) and ('q' in query_prams)): query_name = query_prams.get('q') query_param = str(query_name) limit = query_prams.get('limit') offset = query_prams.get('offset') # columns = [ # "branch", # "address", # "ifsc", # "city", # "district", # "state" # ] # d = {column: query_param for column in columns} # time1 = time.time() # raw = [ # Branch.query.filter(getattr(Branch, col).ilike(query_param)).all() # for col in columns # ] # time2 = time.time() # time3 = time.time() # deletion = [set(x) for x in raw if len(x) != 0] # deletion = deletion[0].intersection(*deletion) # raw = [j for i in raw for j in i] # print(len(raw)) # raw = set(raw) # raw = raw - deletion # time4 = time.time() # print(time2-time1) # print(time4-time3) raw = set( Branch.query.filter( db.or_(Branch.branch.ilike(query_param), Branch.district.ilike(query_param), Branch.city.ilike(query_param), Branch.address.ilike(query_param), Branch.state.ilike(query_param), Branch.ifsc.ilike(query_param))).offset( offset).limit(limit).all()) print(len(raw)) results = { "branches": [{ "ifsc": x.ifsc, "branch": x.branch, "address": x.address, "city": x.city, "district": x.district, "state": x.state } for x in raw] } if results["branches"]: return jsonify(results) return jsonify({"Oops": "No relevant matches found"}) else: return jsonify({"error": "Query parameter not properly defined."}) return jsonify({"error": "No query parameters found"}), 200
def paginated_table(self, survey, page_index=0, items_per_page=10, search=None, sort_fields={}): # return empty response if no user rows found if not survey.survey_responses.first(): return { 'data': [], 'pagination': { 'currentPage': 0, 'totalPages': 0, 'totalItems': 0 }, 'columns': [] } # generate table columns excluded_cols = ['id', 'survey_id', 'modified_at'] columns = [ c.name for c in MobileUser.__table__.columns if c.name not in excluded_cols ] # select column names from survey stack excluding address fields excluded_types = [4, 105, 106, 107] # address prompts json_columns = [ q.question_label for q in survey.survey_questions.order_by( SurveyQuestion.question_num) if q.question_type not in excluded_types ] columns += json_columns # begin building the query query = survey.survey_responses.join(MobileUser) # generate the search string filter on each field and cast # column to text if necessary cast = ['created_at'] ignore = ['_sa_instance_state', 'id', 'survey_id', 'modified_at'] search_filters = [] if search: search_filters += self._normalized_filters(MobileUser, search, ignore, cast) search_filters += self._denormalized_filters(json_columns, search) query = query.filter(db.or_(*search_filters)) if sort_fields: field_is_json = sort_fields['column'] in json_columns if field_is_json: column = SurveyResponse.response[sort_fields['column']] else: column = getattr(MobileUser, sort_fields['column']) if sort_fields['direction'] == -1: column = column.desc() query = query.order_by(column) # create the sliced pagination query paginated_query = query.paginate(page_index, items_per_page) # format output rows for javascript table rows = self._format_users_rows(paginated_query.items, ignore, cast) # create output pagination json object total_answers = survey.survey_responses.count() total_pages = total_answers / items_per_page if total_answers > 0 and items_per_page != 0: total_pages += 1 response = { 'data': rows, 'pagination': { 'currentPage': page_index, 'totalPages': total_pages, 'totalItems': total_answers }, 'columns': columns } return response