def update_product(id): product = Product.query.get_or_404(id) if request.method == "GET": return render_template("update_product.html", product=product) if request.method == "POST": product_name = request.form['product-name'] product = Product.query.get_or_404(id) if not product_name.strip(): error = 'Please Enter Valid Product!' return render_template('update_product.html', error=error, product=product) if db.session.query(Product).filter( func.lower(Product.name) == func.lower(product_name)).all(): error = 'Product already exist!' return render_template('update_product.html', error=error, product=product) else: product.name = request.form['product-name'] try: db.session.commit() return redirect('/products') except: return "Database error"
def update_locations(id): location = Location.query.get_or_404(id) if request.method == "GET": return render_template("update_location.html", location=location) if request.method == "POST": location_name = request.form['location-name'] location = Location.query.get_or_404(id) if not location_name.strip(): error = 'Please Enter Valid Location!' return render_template('update_location.html', error=error, location=location) if db.session.query(Location).filter( func.lower(Location.name) == func.lower(location_name)).all(): error = 'Location already exist!' return render_template('update_location.html', error=error, location=location) else: location.name = request.form['location-name'] try: db.session.commit() return redirect('/locations') except: return "Database error"
def products(): error = None if request.method == "GET": products = Product.query.all() return render_template('products.html', products=products) if request.method == "POST": products = Product.query.all() product_name = request.form["product-name"] if not product_name.strip(): error = 'Please Enter Valid Product!' return render_template('products.html', error=error, products=products) if db.session.query(Product).filter( func.lower(Product.name) == func.lower(product_name)).all(): error = 'Product already exist!' return render_template('products.html', error=error, products=products) else: new_product = Product(name=product_name) try: db.session.add(new_product) db.session.commit() return redirect('/products') except: return "Database error"
class DocumentVersion(db.Model): doc_type = db.Column(db.String, nullable=False) id = db.Column(db.String, nullable=False) version = db.Column(db.Integer, nullable=False, autoincrement=False) document = db.Column(JSON) def __init__(self, doc_type, pk, version, document): self.doc_type = doc_type self.id = pk self.version = version self.document = document __tablename__ = 'document_versions' __table_args__ = ( PrimaryKeyConstraint('doc_type', 'id', 'version'), CheckConstraint(r"doc_type <> ''"), CheckConstraint(r"id <> ''"), CheckConstraint(r'version > 0'), # case insensitive unique constraint for our primary key Index('uniq_primary_ci', func.lower(doc_type), func.lower(id), version, unique=True), )
def locations(): error = None if request.method == "GET": locations = Location.query.all() return render_template('locations.html', locations=locations) if request.method == "POST": locations = Location.query.all() location_name = request.form["location-name"] if not location_name.strip(): error = 'Please Enter Valid Location!' return render_template('locations.html', error=error, locations=locations) if db.session.query(Location).filter( func.lower(Location.name) == func.lower(location_name)).all(): error = 'Location already exist!' return render_template('locations.html', error=error, locations=locations) else: new_location = Location(name=location_name) try: db.session.add(new_location) db.session.commit() return redirect('/locations') except: return "Database error"
def user_where_from_query(rp): where = [] query = rp.get('query', '').strip().lower() if not query: return where strict_queries = get_strict_query(query) if len(query.split(' ')) > 1 and not strict_queries: query = ','.join(['query:%s' % q for q in query.split(' ') if q.strip()]) if not query.split(','): return where for type_name, type_queries in strict_queries.iteritems(): same_type = [] for query in type_queries: if type_name == 'tags': same_type.append(User.tags.any(func.lower(Tag.text) == query)) elif type_name == 'type': same_type.append(User.primary_type == query) elif type_name == 'location': same_type.append(User.state == query) elif type_name == 'technical' and len(type_queries) == 1: if query == 'true': same_type.append(User.is_technical == True) else: same_type.append(User.is_technical.op('IS NOT')(True)) elif type_name == 'companies': same_type.append(func.lower(BaseCompany.name) == query) elif type_name == 'query': different_type = [] for search_field in User.search_fields: if 'class' in search_field: if 'class' in query: query = query.replace('alchemistclass', '').replace('class', '').strip().split(' ')[0] try: different_type.append(BaseCompany.alchemistclass == int(query)) except: pass else: different_type.append(getattr(User, search_field).ilike('%' + query + '%')) for search_field in ['firstname', 'lastname', 'name', 'username', 'email', 'linkedin_email']: different_type.append(getattr(User, search_field).ilike(query + '%')) different_type.append((User.firstname + ' ' + User.lastname).ilike('%' + query + '%')) different_type.append(User.tags.any(Tag.text.ilike('%' + query + '%'))) different_type.append(User.previous_companies.any(BaseCompany.name.ilike('%' + query + '%'))) different_type.append(BaseCompany.name.ilike('%' + query + '%')) for bool_field in User.boolean_fields: if rp.get(bool_field) or bool_field.split('_')[-1] in (query or ''): different_type.append(getattr(User, bool_field) == True) same_type.append(or_(*different_type)) where.append(and_(*same_type)) return where
def admin_agencies(): if 'reactivate' in request.args: try: aid = int(request.args['reactivate']) a = model.Agency.query.get(aid) a.active = True model.db.session.commit() except: model.db.session.rollback() flash('Database Error! Can not reactivate agency.', 'error') log_except() elif 'deactivate' in request.args: try: aid = int(request.args['deactivate']) a = model.Agency.query.get(aid) assert a a.active = False model.DriverScheduleItem.query.filter_by(agency_id=aid).delete() model.db.session.commit() except: model.db.session.rollback() flash('Database Error! Can not deactivate agency.', 'error') log_except() agencies = model.Agency.query.order_by(func.lower(model.Agency.name)).all() return render_template('admin/agencies.html', agencies=agencies, page_title='Agencies')
def count_known_users(usernames): if len(usernames) < 1: return 0 with DBManager.create_session_scope() as db_session: # quick EXPLAIN ANALYZE for this query: # # pajbot=# EXPLAIN ANALYZE SELECT count(*) AS count_1 # FROM "user" # WHERE ("user".login IN ('randers', 'lul', 'xd', 'penis', 'asd', 'hello', 'world') OR lower("user".name) IN ('randers', 'lul', 'xd', 'penis', 'asd', 'hello', 'world')) AND "user".last_seen IS NOT NULL AND now() - "user".last_seen <= make_interval(weeks := 2); # QUERY PLAN # -------------------------------------------------------------------------------------------------------------------------------------------------------------------- # Aggregate (cost=37.45..37.46 rows=1 width=8) (actual time=0.113..0.113 rows=1 loops=1) # -> Bitmap Heap Scan on "user" (cost=21.53..37.43 rows=5 width=0) (actual time=0.110..0.110 rows=1 loops=1) # Recheck Cond: ((login = ANY ('{randers,lul,xd,penis,asd,hello,world}'::text[])) OR (lower(name) = ANY ('{randers,lul,xd,penis,asd,hello,world}'::text[]))) # Filter: ((last_seen IS NOT NULL) AND ((now() - last_seen) <= '14 days'::interval)) # Heap Blocks: exact=6 # -> BitmapOr (cost=21.53..21.53 rows=14 width=0) (actual time=0.101..0.101 rows=0 loops=1) # -> Bitmap Index Scan on user_login_idx (cost=0.00..10.76 rows=7 width=0) (actual time=0.054..0.054 rows=1 loops=1) # Index Cond: (login = ANY ('{randers,lul,xd,penis,asd,hello,world}'::text[])) # -> Bitmap Index Scan on user_lower_idx (cost=0.00..10.76 rows=7 width=0) (actual time=0.046..0.047 rows=6 loops=1) # Index Cond: (lower(name) = ANY ('{randers,lul,xd,penis,asd,hello,world}'::text[])) # Planning Time: 0.092 ms # Execution Time: 0.140 ms # (12 rows) return ( db_session.query(User) .with_entities(count()) .filter(or_(User.login.in_(usernames), func.lower(User.name).in_(usernames))) .filter(and_(User.last_seen.isnot(None), (func.now() - User.last_seen) <= timedelta(weeks=2))) .scalar() )
def find_by_user_input(db_session, input): input = User._normalize_user_username_input(input) # look for a match in both the login and name return (db_session.query(User).filter( or_(User.login == input, func.lower(User.name) == input)).order_by( User.login_last_updated.desc()).limit(1).one_or_none())
def api_property_search(context, request): street_number = request.GET.get("street_number") street_name = request.GET.get("street_name") city = request.GET.get("city") state = request.GET.get("state") zip = request.GET.get("zip") q = DBSession.query(Property, func.avg(Review.rating_average)) if street_number is not None: q = q.filter(Property.street_number == int(street_number)) if street_name is not None: q = q.filter(func.lower(Property.street_name).like("%%%s%%" % street_name.lower())) if city is not None: q = q.filter(func.lower(Property.city).like("%%%s%%" % city.lower())) if state is not None: q = q.filter(func.lower(Property.state).like("%%%s%%" % state.lower())) if zip is not None: q = q.filter(Property.zip == zip) q = q.outerjoin(Property.reviews) q = q.group_by(Property.id) q = q.limit(7) results = [] for property, avg in q.all(): if avg is not None: property.overall = int(avg) else: property.overall = None results.append(property) return results
def _match_existing_student(username, email, current_line) -> (bool, StudentData): # test whether we can find an existing student record with this email address. # if we can, check whether it is a student account. # If not, there's not much we can do dont_convert = False existing_record = db.session.query(User) \ .filter(or_(func.lower(User.email) == func.lower(email), func.lower(User.username) == func.lower(username))).first() if existing_record is not None: if not existing_record.has_role('student'): print( '## skipping row {row} because matched to existing user that is ' 'not a student'.format(row=current_line)) raise SkipRow if existing_record.email.lower() != email.lower(): dont_convert = True return dont_convert, existing_record.student_data if existing_record is not None else None
def get_cost_leaderboard(self): with self._session() as session: sum_size = func.sum(Job.size).label('sum_size') nick = func.lower( func.substr(JSONMetadata.started_by, 1, 4) ).label('nick') rows = session.query(nick, sum_size)\ .filter(Job.id == JSONMetadata.job_id)\ .group_by(nick)\ .order_by(sum_size.desc()) for row in rows: yield row.nick, row.sum_size
def post(self): """User's login view""" args = user_login_parser.parse_args() user: User = User.query.filter( or_( func.lower(User.email) == args.get("username", "").lower(), func.lower(User.username) == args.get("username", "").lower(), )).first() if not user or user.password != args.get("password", None): raise UserExceptions.wrong_login_creds() token = create_access_token(user) user.token = get_csrf_token(token) user_session = Session(user=user, token=get_jti(token), **extract_request_info(request=request)) user_session.save(True) response = make_response(marshal( user, user_model, )) set_access_cookies(response=response, encoded_access_token=token) return response
class User: __tablename__ = "user" id = Column(Integer(), primary_key=True) name = Column(String) # this gets inferred big_col = deferred(Column(Text)) # this gets inferred explicit_col = column_property(Column(Integer)) # EXPECTED: Can't infer type from ORM mapped expression assigned to attribute 'lower_name'; # noqa lower_name = column_property(func.lower(name)) # EXPECTED: Can't infer type from ORM mapped expression assigned to attribute 'syn_name'; # noqa syn_name = synonym("name") # this uses our type lower_name_exp: str = column_property(func.lower(name)) # this uses our type syn_name_exp: Optional[str] = synonym("name")
def retrieve_all_transcript_ids(gene_name): """Retrieves all transcript ids for a gene name""" # Open as session _session = db.create_scoped_session() try: return [transcript for transcript in _session.query(Gene).filter(func.lower(Gene.gene_name) == gene_name.lower()).all()] except (AlchemyResourceClosedError, AlchemyOperationalError, PsycopOperationalError) as e: raise RecoverableError(str(e)) except: _log.error(traceback.format_exc()) raise finally: # Close this session, thus all items are cleared and memory usage is kept at a minimum _session.remove()
class FirefoxAccount(Base): __tablename__ = "fxa" id = Column(Integer, primary_key=True) fxa_id = Column(String(255), unique=True) email_id = Column(UUID(as_uuid=True), ForeignKey(Email.email_id), unique=True, nullable=False) primary_email = Column(String(255), index=True) created_date = Column(String(50)) lang = Column(String(255)) first_service = Column(String(50)) account_deleted = Column(Boolean) create_timestamp = Column(DateTime(timezone=True), nullable=False, server_default=func.now()) update_timestamp = Column(DateTime(timezone=True), nullable=False, onupdate=func.now(), default=func.now()) email = relationship("Email", back_populates="fxa", uselist=False) stripe_customer = relationship( "StripeCustomer", uselist=False, viewonly=True, primaryjoin=( "foreign(FirefoxAccount.fxa_id)==remote(StripeCustomer.fxa_id)"), ) # Class Comparators @hybrid_property def fxa_primary_email_insensitive(self): return self.primary_email.lower() @fxa_primary_email_insensitive.comparator def fxa_primary_email_insensitive_comparator(cls, ): # pylint: disable=no-self-argument return CaseInsensitiveComparator(cls.primary_email) # Indexes __table_args__ = (Index("idx_fxa_primary_email_lower", func.lower(primary_email)), )
def where_from_query(request): where = [] if hasattr(request, 'params'): rp = request.params query = rp.get('query', '').strip().lower() elif request.get('sessquery'): rp = request query = request.get('sessquery').strip().lower() else: query = '' if not query: return where strict_queries = get_strict_query(query) for type_name, type_queries in strict_queries.iteritems(): same_type = [] for query in type_queries: if type_name == 'tags': same_type.append(BaseCompany.tags.any(func.lower(Tag.text) == query)) elif type_name == 'type': same_type.append(BaseCompany.companytype == get_company_typestr(query)) elif type_name == 'class': same_type.append(BaseCompany.alchemistclass == int(query.strip())) elif type_name == 'round': same_type.append(BaseCompany.startup_lastraise == query) elif type_name == 'query': different_type = [] for search_field in BaseCompany.search_fields: if 'class' in search_field: if 'class' in query: query = query.replace('alchemistclass', '').replace('class', '').strip().split(' ')[0] try: different_type.append(BaseCompany.alchemistclass == int(query)) except: pass else: different_type.append(getattr(BaseCompany, search_field).ilike('%' + query + '%')) different_type.append(BaseCompany.tags.any(Tag.text.ilike('%' + query + '%'))) for bool_field in BaseCompany.boolean_fields: if rp.get(bool_field) or bool_field.split('_')[-1] in (query or ''): different_type.append(getattr(BaseCompany, bool_field) == True) same_type.append(or_(*different_type)) where.append(and_(*same_type)) return where
def _filter_query_for_text_contents( self, q: Query, taskclass: Type[Task]) -> Optional[Query]: """ Returns the query, filtered for the "text contents" filter. Args: q: the starting SQLAlchemy ORM Query taskclass: the task class Returns: a Query, potentially modified. """ tf = self._filter # task filter if not tf.text_contents: return q # unmodified # task must contain ALL the strings in AT LEAST ONE text column textcols = taskclass.get_text_filter_columns() if not textcols: # Text filtering requested, but there are no text columns, so # by definition the filter must fail. return None clauses_over_text_phrases = [] # type: List[ColumnElement] # ... each e.g. "col1 LIKE '%paracetamol%' OR col2 LIKE '%paracetamol%'" # noqa for textfilter in tf.text_contents: tf_lower = textfilter.lower() clauses_over_columns = [] # type: List[ColumnElement] # ... each e.g. "col1 LIKE '%paracetamol%'" for textcol in textcols: # Case-insensitive comparison: # https://groups.google.com/forum/#!topic/sqlalchemy/331XoToT4lk # https://bitbucket.org/zzzeek/sqlalchemy/wiki/UsageRecipes/StringComparisonFilter # noqa clauses_over_columns.append( func.lower(textcol).contains(tf_lower, autoescape=True)) clauses_over_text_phrases.append(or_(*clauses_over_columns)) return q.filter(and_(*clauses_over_text_phrases))
def api_create_review(context, request): property_id = context.__parent__.property_id user_id = request.cookies.get("user_id", 1) manager_name = request.json_body.get("manager") rating_kitchen = int(request.json_body.get("rating_kitchen")) rating_bedroom = int(request.json_body.get("rating_bedroom")) rating_bathroom = int(request.json_body.get("rating_bathroom")) rating_area = int(request.json_body.get("rating_area")) rent = request.json_body.get("rent") tag_ids = request.json_body.get("tag_ids") avg_sum = 0 avg_total = 0 if rating_kitchen is not None: avg_sum += rating_kitchen avg_total += 1 if rating_bedroom is not None: avg_sum += rating_bedroom avg_total += 1 if rating_bathroom is not None: avg_sum += rating_bathroom avg_total += 1 if rating_area is not None: avg_sum += rating_area avg_total += 1 if avg_total > 0: rating_avg = avg_sum / avg_total else: rating_avg = None text = request.json_body.get("text") q = DBSession.query(Manager) q = q.filter(func.lower(Manager.name).like("%%%s%%" % manager_name.lower())) manager = q.scalar() if manager is None: manager = Manager() manager.name = manager_name DBSession.add(manager) DBSession.flush() review = Review() review.user_id = user_id review.property_id = property_id review.manager = manager review.rating_kitchen = rating_kitchen review.rating_bathroom = rating_bathroom review.rating_bedroom = rating_bedroom review.rating_area = rating_area review.rating_average = rating_avg review.rent = rent review.text = text review.date = datetime.datetime.now() for tag_id in tag_ids: q = DBSession.query(Tag) q = q.filter(Tag.id == tag_id) tag = q.scalar() if tag is not None: review.tags.append(tag) DBSession.add(review) DBSession.flush() return {}
class Email(Base): __tablename__ = "emails" __mapper_args__ = {"eager_defaults": True} email_id = Column(UUID(as_uuid=True), primary_key=True) primary_email = Column(String(255), unique=True, nullable=False) basket_token = Column(String(255), unique=True) sfdc_id = Column(String(255), index=True) first_name = Column(String(255)) last_name = Column(String(255)) mailing_country = Column(String(255)) email_format = Column(String(1)) email_lang = Column(String(5)) double_opt_in = Column(Boolean) has_opted_out_of_email = Column(Boolean) unsubscribe_reason = Column(Text) create_timestamp = Column(DateTime(timezone=True), nullable=False, server_default=func.now()) update_timestamp = Column( DateTime(timezone=True), nullable=False, onupdate=func.now(), default=func.now(), ) newsletters = relationship("Newsletter", back_populates="email", order_by="Newsletter.name") fxa = relationship("FirefoxAccount", back_populates="email", uselist=False) amo = relationship("AmoAccount", back_populates="email", uselist=False) vpn_waitlist = relationship("VpnWaitlist", back_populates="email", uselist=False) mofo = relationship("MozillaFoundationContact", back_populates="email", uselist=False) stripe_customer = relationship( "StripeCustomer", uselist=False, back_populates="email", primaryjoin="Email.email_id==FirefoxAccount.email_id", secondaryjoin= "remote(FirefoxAccount.fxa_id)==foreign(StripeCustomer.fxa_id)", secondary= "join(FirefoxAccount, StripeCustomer, FirefoxAccount.fxa_id == StripeCustomer.fxa_id)", ) # Class Comparators @hybrid_property def primary_email_insensitive(self): return self.primary_email.lower() @primary_email_insensitive.comparator def primary_email_insensitive_comparator(cls): # pylint: disable=no-self-argument return CaseInsensitiveComparator(cls.primary_email) # Indexes __table_args__ = ( Index("bulk_read_index", "update_timestamp", "email_id"), Index("idx_email_primary_email_lower", func.lower(primary_email)), )
def __eq__(self, other): return func.lower(self.__clause_element__()) == func.lower(other)
def _get_password(self): return self._password def _set_password(self, password): self._password = PasswordUtil.encrypt_password(password) def validate_password(self, plain_password): """Check the password against existing credentials. """ return PasswordUtil.is_password_valid(plain_password, self._password) password = property(_get_password, _set_password) Index('ix_users_user_lower_forum_username', func.lower(User.forum_username), unique=True) schema_user = SQLAlchemySchemaNode( User, # whitelisted attributes includes=[ 'id', 'username', 'forum_username', 'name', 'email', 'email_validated', 'moderator'], overrides={ 'id': { 'missing': None } })
def build_expression(self): return self.operator( func.lower(sqlalchemy.column(self.column_name)), func.lower(sqlalchemy.bindparam(self.parameter)) )
def driver_route_today(): today = datetime.date.today() route = model.DriverDailyRoute.query.filter(model.DriverDailyRoute.driver_id == session['user_id'], model.DriverDailyRoute.date == today).first() if not route: return render_template('driver/driver_load_route.html', page_title='Load Route') total = route.totals() totals = total[1] total = total[0] ages = [('---', '---')] + [(a.id, a.name) for a in model.Agency.query.options(load_only('id', 'name')).order_by(func.lower(model.Agency.name)).all()] special_form = forms.AddSpecialPickup() special_form.set_choices(ages) return render_template('driver/driver_today.html', page_title='Today\'s Route', route=route, totals=totals, total=total, special_form=special_form)
def admin_schedule_edit(sid): s = model.DriverSchedule.query.get(sid) assert s f = forms.CreateSchedule(request.form) if not f.name.data: f.name.data = s.name if request.method == 'POST': try: if f.name.data != s.name and f.validate(): s.name = f.name.data.strip() model.DriverScheduleItem.query.filter_by(schedule_id=sid).delete() for field in request.form: if not field.startswith('item_'): continue v = request.form[field] if not v or not v.isdigit(): continue field = field.split('_') day = int(field[1]) pos = int(field[2]) assert day >= 0 and day < 7 and pos >= 0 and pos <= 50 a_id = int(v) itm = model.DriverScheduleItem() itm.day_of_week = day itm.position_in_day = pos itm.agency_id = a_id itm.skip_next = 'skip_' + str(day) + '_' + str(pos) in request.form s.items.append(itm) model.db.session.commit() flash('Schedule Saved!') except: model.db.session.rollback() flash('Error updating schedule!', 'error') log_except() ages = model.Agency.query.options(load_only('id', 'name')).filter_by(active=True).order_by(func.lower(model.Agency.name)).all() ages = [(a.id, a.name) for a in ages] schedule = s.items rows = 50 for itm in schedule: if itm.position_in_day + 1 > rows: rows = itm.position_in_day schedule_list = [([None] * rows) for day in range(7)] for itm in schedule: schedule_list[itm.day_of_week][itm.position_in_day] = (itm.agency_id, itm.skip_next) return render_template('admin/edit_schedule.html', select_values=schedule_list, agencies=ages, rows=rows, page_title='Edit Schedule - ' + s.name, form=f)
def admin_drivers(): if request.method == 'POST' and 'did' in request.form and 'sid' in request.form: try: did = int(request.form['did']) d = model.User.query.get(did) assert d and d.acct_type == model.User.DRIVER for s in model.DriverSchedule.query.filter_by(driver_id = did).all(): s.driver_id = None sid = request.form['sid'] if sid and sid != 'None': model.DriverSchedule.query.get(int(sid)).driver_id = did model.db.session.commit() flash('Schedule Updated') return redirect(request.url) except: model.db.session.rollback() flash('Database Error! Can not update schedule.', 'error') log_except() elif request.method == 'POST' and 'reactivate' in request.form: try: did = int(request.form['reactivate']) d = model.User.query.get(did) assert d.acct_type == model.User.DRIVER d.active = True model.db.session.commit() return redirect(request.url) except: model.db.session.rollback() flash('Database Error! Can not reactivate driver.', 'error') log_except() elif request.method == 'POST' and 'deactivate' in request.form: try: did = int(request.form['deactivate']) d = model.User.query.get(did) assert d.acct_type == model.User.DRIVER d.active = False d.schedule.clear() model.db.session.commit() return redirect(request.url) except: model.db.session.rollback() flash('Database Error! Can not deactivate driver.', 'error') log_except() elif request.method == 'POST' and 'resetpw' in request.form: try: did = int(request.form['resetpw']) d = model.User.query.get(did) assert d.acct_type == model.User.DRIVER newpw = ''.join([str(random.randrange(10)) for _ in range(10)]) d.password = newpw model.db.session.commit() flash('Password for ' + d.username + ' reset to ' + newpw + '\nPlease notify the driver of their new password so they can change it.') return redirect(request.url) except: model.db.session.rollback() flash('Database Error! Can not reset password!', 'error') log_except() drivers = model.User.query.filter_by(acct_type = model.User.DRIVER).order_by(func.lower(model.User.last_name), func.lower(model.User.first_name), func.lower(model.User.username)).all() return render_template('admin/drivers.html', drivers=drivers, page_title='Driver Accounts', schedules=model.DriverSchedule.query.all())
def _save_results(self, action_instance, session, post_data): if 'results' in post_data: try: failures_count = False try: failures_count = self._get_summary_results( post_data['results'])[Constants.FAILURES_COUNT] except: pass results = self._save_summary(action_instance, post_data['results'], session) should_create = dict(results) test_cache = {} for qa_test in session.query(QaTest).filter( QaTest.name.in_(list(results.keys()))): if qa_test.name in should_create: del should_create[qa_test.name] test_cache[qa_test.name] = qa_test for name in should_create.keys(): qa_test = QaTest(name=name) session.add(qa_test) test_cache[qa_test.name] = qa_test session.flush() status_cache = {} for test, value in results.items(): status_id = None if 'status' not in value: status_id = StatusConstants.UNKNOWN if 'status' in value: if value['status'] not in status_cache: status = session.query(Status).filter( func.lower(Status.name) == func.lower( value['status'])).first() if status: status_id = status.id status_cache[status.name] = status else: status_id = StatusConstants.UNKNOWN else: status_id = status_cache[value['status']].id if not failures_count or status_id == StatusConstants.FAILED: qa_test_history = QaTestHistory( test_id=test_cache[test].id, pipeline_instance_id=action_instance. pipeline_instance_id, action_instance_id=action_instance.id, status_id=status_id, duration=value['time'] if 'time' in value and value['time'] else 0) session.add(qa_test_history) session.flush() if 'stacktrace' in value: session.add( Stacktrace( qa_test_history_id=qa_test_history.id, stacktrace=value['stacktrace'])) session.commit() except: import traceback traceback.print_exc()
def post(self): """Creates new user - requires admin permission-.""" organization_args: dict = dict( (k.replace("organization_", ""), v) for (k, v) in organization_parser.parse_args().items()) user_args: dict = self.user_signup_parser.parse_args() user_position = user_args.pop("position") department_args: dict = dict( (k.replace("dep_", ""), v) for (k, v) in department_parser.parse_args().items()) use_user_info = organization_args.pop("my_info", False) if use_user_info: organization_args.update({ "email": user_args.get("email"), "phone": user_args.get("phone") }) if (Organization.query.filter( func.lower(Organization.name) == organization_args.get( "name", "").lower()).count() > 0): raise InvalidUsage.custom_error( "Organization already registered, kindly " + "contact responsible person to send you an invitation", 401, ) photo: werkzeug.datastructures.FileStorage = user_args.pop("photo") if photo: photostorage = FileHandler(data=photo.stream, title=photo.filename) user_args["photo"] = photostorage user = User(**user_args) user.save() user.add_roles(Role.get(name="user")) db.session.flush() organization = Organization(**organization_args, contact_user_id=user.id) organization.save() db.session.flush() if len([val for val in department_args.values() if val is not None]) > 0: if user_position.lower() == "ceo": raise InvalidUsage.custom_error( "CEO can only be specified with no department", 401) department = OrganizationDepartment(**department_args, org=organization) department.save() db.session.flush() else: department = None affiliation = UserAffiliation(user=user, org=organization, position=user_position, org_dep=department) affiliation.save() db.session.commit() photostorage.save() return user
def build_expression(self, table): return self.operator(func.lower(get_column(table, self.column_name)), func.lower(bindparam(self.parameter)))
def build_expression(self, table): return self.operator( func.lower(get_column(table, self.column_name)), func.lower(bindparam(self.parameter)) )