Пример #1
0
 def decorated_function(*args, **kwargs):
     callback = request.args.get('callback', False)
     if callback:
         data = str(func(*args, **kwargs).data)
         content = str(callback) + '(' + data + ')'
         mimetype = 'application/javascript'
         return current_app.response_class(content, mimetype=mimetype)
     else:
         return func(*args, **kwargs)
Пример #2
0
def _run_forever(func):
    while True:
        try:
            logger.critical("Background worker starting")
            func()
        except Exception as e:
            logger.critical("Unhandled exception in background worker",
                            exc_info=e)
            # cool off in case we have some programming error to not hammer the database
            sleep(60)
Пример #3
0
    def wrapper(*args, **kwargs):
        # Make sure the authorization header exists
        if 'Authorization' not in request.headers:
            abort(400)

        # Verify the sent token
        user = verify_password_or_token(
            request.headers['Authorization'].split(' ')[-1])
        if not user:
            abort(400)

        func()
Пример #4
0
 def wrapper_login_check(*args, **kwargs):
     # check for session's details
     if session.get('user_id') is None:
         return redirect('/login')
     # Then run de called funcction after the check
     called_function = func(*args, **kwargs)
     return called_function
Пример #5
0
	def post(self):
		if not self.get_current_user():
			self.set_status(403)
			return self.json_response({
				'status': 'unauthorized'
				})
		
		action = self.get_argument('action')
		kwrgs = {}
		try:
			kwrgs = json.loads(self.get_argument('args'))
		except:
			kwrgs = {}
		
		actions = {
			'get_pages_list': self.get_pages_list,
			'get_catalog_sections': self.get_catalog_sections,
			'get_catalog_elements': self.get_catalog_elements,
			'get_redirect_list': self.get_redirect_list,
			'get_accounts_list': self.get_accounts_list,
			'get_data_list': self.get_data_list,
			'get_fields': self.get_fields,
			'add': self.create,
			'update': self.update_page,
			'delete': self.delete_smth
		}
		
		if action not in actions.keys():
			return self.json_response({
				'status': 'error',
				'error_code': 'non_existent_action'})
		func = actions[action]
		
		return func(**kwrgs)
Пример #6
0
    def post(self):
        if not self.get_current_user():
            self.set_status(403)
            return self.json_response({'status': 'unauthorized'})

        action = self.get_argument('action')
        kwrgs = {}
        try:
            kwrgs = json.loads(self.get_argument('args'))
        except:
            kwrgs = {}

        actions = {
            'get_pages_list': self.get_pages_list,
            'get_catalog_sections': self.get_catalog_sections,
            'get_catalog_elements': self.get_catalog_elements,
            'get_redirect_list': self.get_redirect_list,
            'get_accounts_list': self.get_accounts_list,
            'get_data_list': self.get_data_list,
            'get_fields': self.get_fields,
            'add': self.create,
            'update': self.update_page,
            'delete': self.delete_smth
        }

        if action not in actions.keys():
            return self.json_response({
                'status': 'error',
                'error_code': 'non_existent_action'
            })
        func = actions[action]

        return func(**kwrgs)
Пример #7
0
 def show_daily_chart():
     today = self.de_chart.dateTime().toPyDateTime().date()
     tomorow = today + dateutil.relativedelta.relativedelta(
         hour=23, minute=59, second=0)
     title, chart_title, data, func, *rest = self.idx_kcal[
         self.cb_kcal_chart_type.currentIndex()]
     print("Daily chart:", today, tomorow, title)
     item_datas = []
     items = self.session.query(Item) \
             .options(joinedload(Item.nutri_info)) \
             .filter(Item.calc_nutrition != None) \
             .filter(Item.time.between(today, tomorow)) \
             .order_by(Item.time)
     keys = list(data.keys())
     for item in items:
         item_data = [item.time, item.description[:20]]
         for key in keys:
             #print ("KEY:", key)
             item_data.append(func(key, getattr(item.nutri_info, key)))
         item_datas.append(item_data)
     header = ["time", "desc"] + keys
     #for time, desc, *rest in item_datas:
     #print (time, desc,)
     #for t in rest:
     #print("{:.2f}".format(t))
     cd = ChartDialog(self)
     cd.set_day_chart(header, today, chart_title, item_datas)
     cd.show()
Пример #8
0
 def wrapper(*args):
     key_ = key(*args)
     cached_result = r.get(key_)
     if cached_result is not None:
         return json.loads(cached_result)
     result = func(*args)
     r.set(key_, json.dumps(result))
     return result
Пример #9
0
 def cached_func(self):
     cacheattr = '_{}'.format(func.func_name)
     try:
         return getattr(self, cacheattr)
     except AttributeError:
         value = func(self)
         setattr(self, cacheattr, value)
         return value
Пример #10
0
def _read_and_process_resources_from_dir(config_dir: str,
                                         func) -> List[Tuple[str, int]]:
    files = [f for f in os.listdir(config_dir) if re.match(r".*\.json$", f)]
    result = []
    for filename in files:
        print("Processing '{filename}' ...".format(filename=filename))
        with open(os.path.join(config_dir, filename)) as fp:
            result.append(func(fp, config_dir=config_dir))
    return result
Пример #11
0
 def fbattr (func, self, *args, **kwargs):
     self._setup_fbinfo_cache()
     self.fbinfo = self.fbcache.get_value(
         key = self.fbid,
         expiretime = self._fbexpiration,
         createfunc = self._get_fbinfo
     )
     try:
         return func(self, *args, **kwargs)
     except:
         self.fbcache.remove_value(self.fbid)
         self.fbcache[self.fbid] = self._get_fbinfo()
         self.fbinfo = self.fbcache.get_value(
             key = self.fbid,
             expiretime = self._fbexpiration,
             createfunc = self._get_fbinfo
         )
         return func(self, *args, **kwargs)
Пример #12
0
 def fballfriends(func, self, *args, **kwargs):
     self._setup_fballfriends_cache()
     self._fballfriends = self.fballfriendscache.get_value(self.fbid,
         expiretime = self._fbexpiration,
         createfunc = self._get_fballfriends
     )
     try:
         return func(self, *args, **kwargs)
     except:
         # Try invalidating the cache
         self.fballfriendscache.remove_value(self.fbid)
         self._setup_fballfriends_cache()
         self._fballfriends = self.fballfriendscache.get_value(
             key = self.fbid,
             expiretime = self._fbexpiration,
             createfunc = self._get_fballfriends
         )
         return func(self, *args, **kwargs)
Пример #13
0
        def fun(*args, **kwargs):
            count = 0
            while count < times:
                try:
                    return func(*args, **kwargs)
                except Exception as e:
                    count = count + 1

            logger.error("connection failed after retried 3 times. {} {}".format(args,kwargs))
            raise Exception("connection failed after retried 3 times. {} {}".format(args,kwargs))
Пример #14
0
        def fun(*args, **kwargs):
            count = 0
            while count < times:
                try:
                    return func(*args, **kwargs)
                except Exception as e:
                    count = count + 1

            logger.error("connection failed after retried 3 times. {} {}".format(args, kwargs))
            raise Exception("connection failed after retried 3 times. {} {}".format(args, kwargs))
Пример #15
0
    def decorated_function(*args, **kwargs):
        priveleges = g.user.app_privileges
        if priveleges == None:
            flash('Access denied.', 'danger')
            return redirect('/home')

        if json.loads(priveleges)['EUROVISION_MGMT'] != 'admin':
            flash('Access denied.', 'danger')
            return redirect('/home')

        return func(*args, **kwargs)
Пример #16
0
 def wrapper(*args, **kwargs):
     if (request.headers.get('Authorization')
             and 'Bearer ' in request.headers.get('Authorization')
             and decode_token(
                 request.headers.get('Authorization')[7:]).get('type')
             == 'refresh'):
         return
     verify_jwt_in_request_optional()
     current_user = User.query.filter_by(id=get_jwt_identity()).first()
     if not current_user.is_expert:
         return abort(422, message='Permissions needed')
     return func(*args, **kwargs)
Пример #17
0
def advance_amounts(day):
    print day
    orders = OrderItem.query.join(
        Customer, OrderItem.custmer_id == Customer.id).add_columns(
            OrderItem.order_date_time, OrderItem.order_id, OrderItem.item_name,
            OrderItem.item_cost, OrderItem.website_shipping_cost,
            OrderItem.order_status_id, Customer.mobile_num, Customer.name,
            OrderItem.linq_shipping_cost, OrderItem.advance_amount,
            OrderItem.linq_order_num).filter(
                OrderItem.store_id == session['store_id']).filter(
                    func(OrderItem.order_date_time) == day)
    return render_template('payments.html', items=orders)
Пример #18
0
 def wrapper(*args, **kwargs):
     if (request.headers.get('Authorization')
             and 'Bearer ' in request.headers.get('Authorization')
             and decode_token(
                 request.headers.get('Authorization')[7:]).get('type')
             == 'refresh'):
         return
     verify_jwt_in_request_optional()
     current_user = User.query.filter_by(id=get_jwt_identity()).first()
     if not current_user:
         return
     return func(current_user)
Пример #19
0
def do_action(action,**kwargs):
    """triggers an action, checks if there are any listeners previously defined
    in add_action and runs those first. If the action called here is defined as
    run in background (defined in add_action) it will send to Gearman.  
    Requires site_id if is a plugin::
    
        do_action("new_user",{'site_id':1,'name':'bob'})
    """
    global actions
    if action in actions:
        actorlist = actions[action]
        for bg,func in actorlist:
            if bg:
                jsond = {'action':str(func.__name__) if func else action}
                for k in kwargs.keys():
                    if isinstance(kwargs[k],(str,unicode,int,long,list)):
                        jsond.update({k:kwargs[k]})
                    else:
                        log.debug('not adding %s type=%s' % (k,type(kwargs[k])))
                do_bg(jsond)
            else:
                func(**kwargs)
Пример #20
0
def process_job():
    """
    Attempt to process one job from the job queue. Returns False if no job was found, True if a job was processed,
    regardless of failure/success.
    """
    logger.debug(f"Looking for a job")
    with session_scope(isolation_level="REPEATABLE READ") as session:
        # a combination of REPEATABLE READ and SELECT ... FOR UPDATE SKIP LOCKED makes sure that only one transaction
        # will modify the job at a time. SKIP UPDATE means that if the job is locked, then we ignore that row, it's
        # easier to use SKIP LOCKED vs NOWAIT in the ORM, with NOWAIT you get an ugly exception from deep inside
        # psycopg2 that's quite annoying to catch and deal with
        job = (session.query(BackgroundJob).filter(
            BackgroundJob.ready_for_retry).with_for_update(
                skip_locked=True).first())

        if not job:
            logger.debug(f"No pending jobs")
            return False

        # we've got a lock for a job now, it's "pending" until we commit or the lock is gone
        logger.info(f"Job #{job.id} grabbed")

        job.try_count += 1

        message_type, func = JOBS[job.job_type]

        try:
            ret = func(message_type.FromString(job.payload))
            job.state = BackgroundJobState.completed
            logger.info(
                f"Job #{job.id} complete on try number {job.try_count}")
        except Exception as e:
            logger.exception(e)
            if job.try_count >= job.max_tries:
                # if we already tried max_tries times, it's permanently failed
                job.state = BackgroundJobState.failed
                logger.info(
                    f"Job #{job.id} failed on try number {job.try_count}")
            else:
                job.state = BackgroundJobState.error
                # exponential backoff
                job.next_attempt_after += timedelta(seconds=15 *
                                                    (2**job.try_count))
                logger.info(
                    f"Job #{job.id} error on try number {job.try_count}, next try at {job.next_attempt_after}"
                )
            # add some info for debugging
            job.failure_info = traceback.format_exc()

        # exiting ctx manager commits and releases the row lock
    return True
    def decorated_function(*args, **kwargs):
        mealplan_id = kwargs[
            'mealplan_id']  # Take parameter from the route using kwargs

        user_owns_mealplan = db.session.query(MealPlans) \
            .filter(MealPlans.user_id == current_user.id) \
            .filter(MealPlans.mealplan_id == mealplan_id) \
            .first()

        if user_owns_mealplan or mealplan_id == 'x':
            return func(*args, **kwargs)
        else:
            flash('Sorry, you do not have access to this meal plan', 'warning')
            return redirect(url_for('main.mealplans_history'))
Пример #22
0
    def inner(*args, **kwargs):
        db = create_engine(
            # Equivalent URL:
            # mysql+pymysql://<db_user>:<db_pass>@/<db_name>?unix_socket=/cloudsql/<cloud_sql_instance_name>
            url,
            pool_size=0,
            max_overflow=10,
            pool_timeout=30,  # 30 seconds
            pool_recycle=1800,  # 30 minutes
        )

        kwargs['db'] = db
        res = func(*args, **kwargs)
        return res
Пример #23
0
	def dispatchReleaseDbBacked(self, item):

		processor_row = self.db_sess.query(db.RssFeedEntry)       \
			.filter(db.RssFeedEntry.feed_name == item['srcname']) \
			.scalar()
		if not processor_row:
			raise RuntimeError("No feed filter system found for {} from url {}.".format(item['srcname'], item['linkUrl']))

		# Pull the function from the database
		func = processor_row.get_func()

		# And then use it.
		ret = func(item)
		return ret
Пример #24
0
 def wrapped_func(*args, **kwargs):
     result = func(*args, **kwargs)
     current_state_name = args[0].state
     if not current_state_name:
         raise Exception('Current state cannot be None')
     current_machine_state = MachineState(current_state_name)
     current_state_transition_map = self.states.get(current_machine_state, {}).get('on')
     if not current_state_transition_map:
         raise Exception(f'Invalid state transition. Trasition definition for state `{current_state_name}` is not found.')
     next_machine_state = current_state_transition_map.get(action_name)
     if not next_machine_state:
         raise Exception(f'Invalid state transition. Cannot apply action `{action_name}` to state `{current_state_name}`')
     args[0].state = next_machine_state.name
     return result
Пример #25
0
 def wrapper(func, self, *args, **kwargs):
     c = cache.get_cache('%s.%s' % 
         (func.__module__, func.__name__))
     funcargs = {
         'key': self.id,
         'createfunc': lambda: func(self, *args, **kwargs)
     }
     if type:
         funcargs['type'] = type
     if expiretime:
         funcargs['expiretime'] = expiretime
     val = c.get_value(**funcargs)
     if addsession:
         if hasattr(val, '__iter__'):
             for r in xrange(0, len(val)):
                 val[r] = Session.merge(val[r], dont_load=True)
         else:
             val = Session.merge(val, dont_load=True)
     return val
Пример #26
0
    def wrapper(self, *args, **kwargs):
        query = func(self, *args, **kwargs)

        # add an orderby clause if given to the decorated function
        orderby = kwargs.get('orderby')
        if orderby:
            query = query.order_by(*orderby)

        # return query to simulate a dynamic relationship
        if self.dynamic:
            return query

        # return a pagination object
        elif self.paginate:
            page = kwargs.get('page',1)
            return query.paginate(page=page, per_page=self.per_page)

        else:
            return query.all()
Пример #27
0
		def rate_limited_function(*args, **kargs):
			curtime = time.clock()
			elapsed = curtime - last_called[0]
			left_to_wait = min_interval - elapsed

			if left_to_wait <= 0:
				# return the actual function so it can be called
				ret = func(*args, **kargs)
				last_called[0] = curtime

				# we want to note in the logs that some calls were skipped,
				# while not printing the log too often -
				# that would slow down the system and defeat the purpose of rate limiting.
				if ((curtime - last_warned[0] >= warn_every) and (num_skips[0] > 0)):
					logging.warning("Skipped %s calls to '%s()' in %s seconds." % (num_skips[0], func.__name__, warn_every))
					last_warned[0] = curtime
					num_skips[0] = 0
			else:
				# ignore the function call and continue
				ret = lambda: True
				num_skips[0] += 1
			return ret
Пример #28
0
 def wrapper(*args, **kwargs):
     token = bottle.request.get_cookie('auth_token', secret=app.settings.get('cookie_key', '1234'))
     if not token:
         logger.debug("No token provided for request")
         return {"error": True, "message": "Access Denied"}
     engine = create_engine(app.settings.connect_string, echo=False)
     session = sessionmaker(bind=engine)
     db = session()
     try:
         # Last arg should be 'db'
         auth_token = db.query(Auth).filter(Auth.token == token).one()
     except NoResultFound:
         logger.debug("No corresponding auth token found")
         return {"error": True, "message": "Access Denied"}
     else:
         if auth_token.expires <= datetime.datetime.now():
             logger.debug("Token expired")
             return {"error": True, "message": "Access Denied"}
         else:
             kwargs['db'] = db
             return func(*args, **kwargs)
     finally:
         db.close()
Пример #29
0
 def wrapper(*args, **kwargs):  # type: ignore
     # Bypass attempt to perform query and just return default value
     is_db_disabled: bool = app_config.get(
         'BROWSE_DISABLE_DATABASE') or False
     if is_db_disabled:
         if logger:
             logger.info(
                 'Database is disabled per BROWSE_DISABLE_DATABASE')
         return default_return_val
     try:
         return func(*args, **kwargs)
     except NoResultFound:
         return default_return_val
     except (OperationalError, DBAPIError) as ex:
         if logger:
             logger.warning(
                 f'Error executing query in {func.__name__}: {ex}')
         return default_return_val
     except Exception as ex:
         if logger:
             logger.warning(
                 f'Unknown exception in {func.__name__}: {ex}')
         raise
Пример #30
0
        def rate_limited_function(*args, **kargs):
            curtime = time.clock()
            elapsed = curtime - last_called[0]
            left_to_wait = min_interval - elapsed

            if left_to_wait <= 0:
                # return the actual function so it can be called
                ret = func(*args, **kargs)
                last_called[0] = curtime

                # we want to note in the logs that some calls were skipped,
                # while not printing the log too often -
                # that would slow down the system and defeat the purpose of rate limiting.
                if ((curtime - last_warned[0] >= warn_every)
                        and (num_skips[0] > 0)):
                    print >> sys.stderr, "WARNING: Skipped %s calls to '%s()' in %s seconds." % (
                        num_skips[0], func.__name__, warn_every)
                    last_warned[0] = curtime
                    num_skips[0] = 0
            else:
                # ignore the function call and continue
                ret = lambda: True
                num_skips[0] += 1
            return ret
Пример #31
0
 def decorated_function(*args,**kwargs):
     if CURR_USER_ID not in session:
         log_out_procedures()
         flash("You must be logged-in to access this resource.", 'danger')
         return redirect(url_for('auth_bp.login', next=request.url))
     return func(*args, **kwargs)
Пример #32
0
 def calculate_stat(gene):
     return int(nature_mod *
         func(base_stat, level=level, iv=gene, effort=effort_in))
Пример #33
0
 def inner(*args, **kwargs):
     response = func(*args, **kwargs)
     response.headers.add('Access-Control-Allow-Origin', '*')
     response.headers.add('Access-Control-Allow-Headers', 'Content-Type,Authorization')
     response.headers.add('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE')
     return response
Пример #34
0
 def inner(*args, **kwargs):
     Session = sessionmaker(bind=db)
     session = Session()
     kwargs['session'] = session
     res = func(*args, **kwargs)
     return res
Пример #35
0
 def inner(*args, **kwargs):
     cls = args[0]
     new_args = args[1:]
     with Db_session(cls._db_name, commit) as session:
         return func(cls, session, *new_args, **kwargs)
Пример #36
0
        
        if not the_schema:
            return_dict['code'] = 500
            return_dict['message'] = 'Invalid form schema specified.'
            return json.dumps(return_dict)

        try:
            form_result = the_schema.to_python(dict(params))
            self.form_result = form_result
        except formencode.Invalid, error:
            return_dict['code'] = 500
            return_dict['message'] = 'Invalid form arguments' % error.value
            return_dict.update(dict([(k, v.message) for k, v in error.error_dict.items()]))
            return json.dumps(return_dict)
        
        return func(self, *args, **kwargs)
    return decorator(wrapper)

# the methods that come out of here should form the definitive plate query API
def nonempty_qlbplates_query(filter_stmt):
    return Session.query(QLBPlate, func.count(QLBWell.id).label('well_count'))\
                  .join(QLBWell)\
                  .join(QLBPlate.plate)\
                  .join(Plate.box2)\
                  .filter(and_(QLBPlate.plate_id != None,
                               QLBWell.file_id != None,
                               QLBWell.file_id != -1))\
                  .filter(filter_stmt)\
                  .options(joinedload_all(QLBPlate.file))\
                  .group_by(QLBWell.plate_id)\
                  .having('well_count > 0')
Пример #37
0
 def update_data(cls, data):
     update_fields = {k.split('_get_')[1]: v for k, v in cls.__dict__.items() if type(v) == FunctionType and k.startswith('_get_') == True}
     for k,func in update_fields.items():
         data[k] = func(cls, data[k])
Пример #38
0
 def decorated_function(*args, **kwargs):
     if session.get('login_user', None) is None:
         return redirect(url_for('home.login', next=request.url))
     return func(*args, **kwargs)
Пример #39
0
 def wrap(*args, **kwargs ):
     if g.user:
         return func( *args, **kwargs )
     else:
         return redirect( url_for('login', next = request.url) )
Пример #40
0
 def wrap(*args, **kwargs):
     time_start = time.time()
     while time.time() - time_start < 0.5:
         time.sleep(0.1)
     return func(*args, **kwargs)
Пример #41
0
 def _fb_error_handler(*args, **kwargs):
     try:
         return func(*args, **kwargs)
     except oauth.OAuthException:
         return "Sorry, Facebook sent us some invalid data. Please go back and attempt to log in again. Sorry!"
Пример #42
0
 def wrap(*args, **kw):
     res = func(*args, **kw)
     return model2dict(res)
Пример #43
0
    from sqlalchemy.sql import exists

    stmt = exists().where(Image.owner_id == User.id)
    for (name,) in session.query(User.name).filter(stmt):
        print name
    stmt = exists().where(User.name == "not exists")
    for (name,) in session.query(User.name).filter(stmt):
        print name
    else:
        print "not exists"


def q_any():
    # any()で自動でexistsの判定をしてくれる。
    for row in session.query(User).filter(User.images.any()):
        print row.name


def q_any_with_filter():
    for row in session.query(User).filter(User.images.any(Image.filename.like("%5%"))):
        print row.name


if __name__ == "__main__":
    locals_dict = dict(locals())
    sample_func_list = [locals_dict[k] for k in sorted(locals_dict.keys()) if k.startswith("q_")]
    for func in sample_func_list:
        header(func.__name__)
        func()
        footer()
Пример #44
0
 def _func(*args):
     return func(*[self.visit_param(_) for _ in args])
Пример #45
0
 def _wrapper(*args, **kw):
     try:
         return func(*args, **kw)
     except exceptions:
         raise IndicoError(str(message))
Пример #46
0
 def inner_func(self, *args, **kwargs):
     if not hasattr(self, cache_name):
         result = func(self, *args, **kwargs)
         setattr(self, cache_name, result)
     return getattr(self, '__{}_cache'.format(func.__name__))
Пример #47
0
 def wrap(*args, **kw):
     try:
         res = func(*args, **kw)
     except Exception as e:
         return []
     return list(map(model2dict, res))
Пример #48
0
    def wrapper(*args, **kwargs):
        # Make sure the client ID is correct
        if request.args.get('client_id', '') != app.config['OAUTH_CLIENT_ID']:
            abort(400)

        func()
Пример #49
0
 def wrapped(*args, **kwargs):
     with self:
         return func(self.session, *args, **kwargs)