Code
stringlengths
103
85.9k
Summary
listlengths
0
94
Please provide a description of the function:def by_prefix(self, prefix, zipcode_type=ZipcodeType.Standard, sort_by=SimpleZipcode.zipcode.name, ascending=True, returns=DEFAULT_LIMIT): return self.query( ...
[ "\n Search zipcode information by first N digits.\n\n Returns multiple results.\n " ]
Please provide a description of the function:def by_pattern(self, pattern, zipcode_type=ZipcodeType.Standard, sort_by=SimpleZipcode.zipcode.name, ascending=True, returns=DEFAULT_LIMIT): return self.query( ...
[ "\n Search zipcode by wildcard.\n\n Returns multiple results.\n " ]
Please provide a description of the function:def by_state(self, state, zipcode_type=ZipcodeType.Standard, sort_by=SimpleZipcode.zipcode.name, ascending=True, returns=DEFAULT_LIMIT): return self.query( state...
[ "\n Search zipcode information by fuzzy State name.\n\n My engine use fuzzy match and guess what is the state you want.\n " ]
Please provide a description of the function:def by_coordinates(self, lat, lng, radius=25.0, zipcode_type=ZipcodeType.Standard, sort_by=SORT_BY_DIST, ascending=True, ...
[ "\n Search zipcode information near a coordinates on a map.\n\n Returns multiple results.\n\n :param lat: center latitude.\n :param lng: center longitude.\n :param radius: only returns zipcode within X miles from ``lat``, ``lng``.\n\n **中文文档**\n\n 1. 计算出在中心坐标处, 每一经度和...
Please provide a description of the function:def by_population(self, lower=-1, upper=2 ** 31, zipcode_type=ZipcodeType.Standard, sort_by=SimpleZipcode.population.name, ascending=False, ret...
[ "\n Search zipcode information by population range.\n " ]
Please provide a description of the function:def by_population_density(self, lower=-1, upper=2 ** 31, zipcode_type=ZipcodeType.Standard, sort_by=SimpleZipcode.population_density.name, ...
[ "\n Search zipcode information by population density range.\n\n `population density` is `population per square miles on land`\n " ]
Please provide a description of the function:def by_land_area_in_sqmi(self, lower=-1, upper=2 ** 31, zipcode_type=ZipcodeType.Standard, sort_by=SimpleZipcode.land_area_in_sqmi.name, ...
[ "\n Search zipcode information by land area / sq miles range.\n " ]
Please provide a description of the function:def by_water_area_in_sqmi(self, lower=-1, upper=2 ** 31, zipcode_type=ZipcodeType.Standard, sort_by=SimpleZipcode.water_area_in_sqmi.name, ...
[ "\n Search zipcode information by water area / sq miles range.\n " ]
Please provide a description of the function:def by_housing_units(self, lower=-1, upper=2 ** 31, zipcode_type=ZipcodeType.Standard, sort_by=SimpleZipcode.housing_units.name, ascending=False, ...
[ "\n Search zipcode information by house of units.\n " ]
Please provide a description of the function:def by_occupied_housing_units(self, lower=-1, upper=2 ** 31, zipcode_type=ZipcodeType.Standard, sort_by=SimpleZipcode.occupied_housing_unit...
[ "\n Search zipcode information by occupied house of units.\n " ]
Please provide a description of the function:def by_median_home_value(self, lower=-1, upper=2 ** 31, zipcode_type=ZipcodeType.Standard, sort_by=SimpleZipcode.median_home_value.name, ...
[ "\n Search zipcode information by median home value.\n " ]
Please provide a description of the function:def by_median_household_income(self, lower=-1, upper=2 ** 31, zipcode_type=ZipcodeType.Standard, sort_by=SimpleZipcode.median_household...
[ "\n Search zipcode information by median household income.\n " ]
Please provide a description of the function:def select_single_column(engine, column): s = select([column]) return column.name, [row[0] for row in engine.execute(s)]
[ "\n Select data from single column.\n\n Example::\n\n >>> select_single_column(engine, table_user.c.id)\n [1, 2, 3]\n\n >>> select_single_column(engine, table_user.c.name)\n [\"Alice\", \"Bob\", \"Cathy\"]\n " ]
Please provide a description of the function:def select_many_column(engine, *columns): if isinstance(columns[0], Column): pass elif isinstance(columns[0], (list, tuple)): columns = columns[0] s = select(columns) headers = [str(column) for column in columns] data = [tuple(row) fo...
[ "\n Select data from multiple columns.\n\n Example::\n\n >>> select_many_column(engine, table_user.c.id, table_user.c.name)\n\n\n :param columns: list of sqlalchemy.Column instance\n\n :returns headers: headers\n :returns data: list of row\n\n **中文文档**\n\n 返回多列中的数据。\n " ]
Please provide a description of the function:def select_distinct_column(engine, *columns): if isinstance(columns[0], Column): pass elif isinstance(columns[0], (list, tuple)): # pragma: no cover columns = columns[0] s = select(columns).distinct() if len(columns) == 1: return...
[ "\n Select distinct column(columns).\n\n :returns: if single column, return list, if multiple column, return matrix.\n\n **中文文档**\n\n distinct语句的语法糖函数。\n " ]
Please provide a description of the function:def select_random(engine, table_or_columns, limit=5): s = select(table_or_columns).order_by(func.random()).limit(limit) return engine.execute(s).fetchall()
[ "\n Randomly select some rows from table.\n " ]
Please provide a description of the function:def smart_insert(engine, table, data, minimal_size=5): insert = table.insert() if isinstance(data, list): # 首先进行尝试bulk insert try: engine.execute(insert, data) # 失败了 except IntegrityError: # 分析数据量 ...
[ "\n An optimized Insert strategy. Guarantee successful and highest insertion\n speed. But ATOMIC WRITE IS NOT ENSURED IF THE PROGRAM IS INTERRUPTED.\n\n **中文文档**\n\n 在Insert中, 如果已经预知不会出现IntegrityError, 那么使用Bulk Insert的速度要\n 远远快于逐条Insert。而如果无法预知, 那么我们采用如下策略:\n\n 1. 尝试Bulk Insert, Bulk Insert由于在结束前不...
Please provide a description of the function:def get_file_extension_type(filename): ext = get_file_extension(filename) if ext: for name, group in EXTENSIONS.items(): if ext in group: return name return "OTHER"
[ "\n Return the group associated to the file\n :param filename:\n :return: str\n " ]
Please provide a description of the function:def get_driver_class(provider): if "." in provider: parts = provider.split('.') kls = parts.pop() path = '.'.join(parts) module = import_module(path) if not hasattr(module, kls): raise ImportError('{0} provider not...
[ "\n Return the driver class\n :param provider: str - provider name\n :return:\n " ]
Please provide a description of the function:def get_provider_name(driver): kls = driver.__class__.__name__ for d, prop in DRIVERS.items(): if prop[1] == kls: return d return None
[ "\n Return the provider name from the driver class\n :param driver: obj\n :return: str\n " ]
Please provide a description of the function:def init_app(self, app): provider = app.config.get("STORAGE_PROVIDER", None) key = app.config.get("STORAGE_KEY", None) secret = app.config.get("STORAGE_SECRET", None) container = app.config.get("STORAGE_CONTAINER", None) allow...
[ "\n To initiate with Flask\n :param app: Flask object\n :return:\n " ]
Please provide a description of the function:def use(self, container): kw = self._kw.copy() kw["container"] = container s = Storage(**kw) yield s del s
[ "\n A context manager to temporarily use a different container on the same driver\n :param container: str - the name of the container (bucket or a dir name if local)\n :yield: Storage\n " ]
Please provide a description of the function:def get(self, object_name): if object_name in self: return Object(obj=self.container.get_object(object_name)) return None
[ "\n Return an object or None if it doesn't exist\n :param object_name:\n :return: Object\n " ]
Please provide a description of the function:def create(self, object_name, size=0, hash=None, extra=None, meta_data=None): obj = BaseObject(container=self.container, driver=self.driver, name=object_name, size=size, ...
[ "\n create a new object\n :param object_name:\n :param size:\n :param hash:\n :param extra:\n :param meta_data:\n :return: Object\n " ]
Please provide a description of the function:def upload(self, file, name=None, prefix=None, extensions=None, overwrite=False, public=False, random_name=False, **kwargs): tmp_file = No...
[ "\n To upload file\n :param file: FileStorage object or string location\n :param name: The name of the object.\n :param prefix: A prefix for the object. Can be in the form of directory tree\n :param extensions: list of extensions to allow. If empty, it will use all extension.\n ...
Please provide a description of the function:def _download_from_url(self, url): ext = get_file_extension(url) if "?" in url: ext = get_file_extension(os.path.splitext(url.split("?")[0])) filepath = "/tmp/%s.%s" % (uuid.uuid4().hex, ext) request.urlretrieve(url, filep...
[ "\n Download a url and return the tmp path\n :param url:\n :return:\n " ]
Please provide a description of the function:def _safe_object_name(self, object_name): extension = get_file_extension(object_name) file_name = os.path.splitext(object_name)[0] while object_name in self: nuid = uuid.uuid4().hex object_name = "%s__%s.%s" % (file_na...
[ " Add a UUID if to a object name if it exists. To prevent overwrites\n :param object_name:\n :return str:\n " ]
Please provide a description of the function:def _register_file_server(self, app): if isinstance(self.driver, local.LocalStorageDriver) \ and self.config["serve_files"]: server_url = self.config["serve_files_url"].strip("/").strip() if server_url: ...
[ "\n File server\n Only local files can be served\n It's recommended to serve static files through NGINX instead of Python\n Use this for development only\n :param app: Flask app instance\n\n " ]
Please provide a description of the function:def info(self): return { "name": self.name, "size": self.size, "extension": self.extension, "url": self.url, "full_url": self.full_url, "type": self.type, "path": self.path, ...
[ "\n Return all the info of this object\n :return: dict\n " ]
Please provide a description of the function:def get_url(self, secure=False, longurl=False): driver_name = self.driver.name.lower() try: # Currently only Cloudfiles and Local supports it url = self._obj.get_cdn_url() if "local" in driver_name: ...
[ "\n Return the url \n :param secure: bool - To use https\n :param longurl: bool - On local, reference the local path with the domain\n ie: http://site.com/files/object.png otherwise /files/object.png\n :return: str\n " ]
Please provide a description of the function:def full_path(self): if "local" in self.driver.name.lower(): return "%s/%s" % self.container.key, self.path return self.path
[ "\n Return the full path of the local object\n If not local, it will return self.path\n :return: str\n " ]
Please provide a description of the function:def save_to(self, destination, name=None, overwrite=False, delete_on_failure=True): if not os.path.isdir(destination): raise IOError("'%s' is not a valid directory") obj_path = "%s/%s" % (destination, self._obj.name) if name: ...
[ "\n To save the object in a local path\n :param destination: str - The directory to save the object to\n :param name: str - To rename the file name. Do not add extesion\n :param overwrite:\n :param delete_on_failure:\n :return: The new location of the file or None\n ...
Please provide a description of the function:def download_url(self, timeout=60, name=None): if "local" in self.driver.name.lower(): return url_for(SERVER_ENDPOINT, object_name=self.name, dl=1, name=name, ...
[ "\n Trigger a browse download\n :param timeout: int - Time in seconds to expire the download\n :param name: str - for LOCAL only, to rename the file being downloaded\n :return: str\n " ]
Please provide a description of the function:def load_keys(): consumer_key = os.environ.get('CONSUMER_KEY') consumer_secret = os.environ.get('CONSUMER_SECRET') access_token = os.environ.get('ACCESS_TOKEN') access_token_secret = os.environ.get('ACCESS_TOKEN_SECRET') return consumer_key, consume...
[ "Loads Twitter keys.\n\n Returns:\n tuple: consumer_key, consumer_secret, access_token, access_token_secret\n " ]
Please provide a description of the function:def search(self, q): results = self._api.search(q=q) return results
[ "Search tweets by keyword.\n\n Args:\n q: keyword\n\n Returns:\n list: tweet list\n " ]
Please provide a description of the function:def search_by_user(self, screen_name, count=100): results = self._api.user_timeline(screen_name=screen_name, count=count) return results
[ "Search tweets by user.\n\n Args:\n screen_name: screen name\n count: the number of tweets\n\n Returns:\n list: tweet list\n " ]
Please provide a description of the function:def on_successful_login(self, subject, authc_token, account_id): # always clear any previous identity: self.forget_identity(subject) # now save the new identity: if authc_token.is_remember_me: self.remember_identity(subje...
[ "\n Reacts to the successful login attempt by first always\n forgetting any previously stored identity. Then if the authc_token\n is a ``RememberMe`` type of token, the associated identity\n will be remembered for later retrieval during a new user session.\n\n :param subject: the...
Please provide a description of the function:def remember_identity(self, subject, authc_token, account_id): try: identifiers = self.get_identity_to_remember(subject, account_id) except AttributeError: msg = "Neither account_id nor identifier arguments passed" ...
[ "\n Yosai consolidates rememberIdentity, an overloaded method in java,\n to a method that will use an identifier-else-account logic.\n\n Remembers a subject-unique identity for retrieval later. This\n implementation first resolves the exact identifying attributes to\n remember. ...
Please provide a description of the function:def convert_bytes_to_identifiers(self, encrypted, subject_context): # unlike Shiro, Yosai assumes that the message is encrypted: decrypted = self.decrypt(encrypted) return self.serialization_manager.deserialize(decrypted)
[ "\n If a cipher_service is available, it will be used to first decrypt the\n serialized message. Then, the bytes are deserialized and returned.\n\n :param serialized: the bytes to decrypt and then deserialize\n :param subject_context: the contextual data, that is being\n ...
Please provide a description of the function:def on_remembered_identifiers_failure(self, exc, subject_context): msg = ("There was a failure while trying to retrieve remembered " "identifier. This could be due to a configuration problem or " "corrupted identifier. This co...
[ "\n Called when an exception is thrown while trying to retrieve identifier.\n The default implementation logs a debug message and forgets ('unremembers')\n the problem identity by calling forget_identity(subject_context) and\n then immediately re-raises the exception to allow the calling...
Please provide a description of the function:def encrypt(self, serialized): fernet = Fernet(self.encryption_cipher_key) return fernet.encrypt(serialized)
[ "\n Encrypts the serialized message using Fernet\n\n :param serialized: the serialized object to encrypt\n :type serialized: bytes\n :returns: an encrypted bytes returned by Fernet\n " ]
Please provide a description of the function:def decrypt(self, encrypted): fernet = Fernet(self.decryption_cipher_key) return fernet.decrypt(encrypted)
[ "\n decrypts the encrypted message using Fernet\n\n :param encrypted: the encrypted message\n :returns: the decrypted, serialized identifier collection\n " ]
Please provide a description of the function:def apply_realms(self): self.authenticator.init_realms(self.realms) self.authorizer.init_realms(self.realms)
[ "\n :realm_s: an immutable collection of one or more realms\n :type realm_s: tuple\n " ]
Please provide a description of the function:def is_permitted_collective(self, identifiers, permission_s, logical_operator): return self.authorizer.is_permitted_collective(identifiers, permission_s, ...
[ "\n :type identifiers: SimpleIdentifierCollection\n\n :param permission_s: a collection of 1..N permissions\n :type permission_s: List of Permission object(s) or String(s)\n\n :param logical_operator: indicates whether all or at least one\n permission ch...
Please provide a description of the function:def check_permission(self, identifiers, permission_s, logical_operator): return self.authorizer.check_permission(identifiers, permission_s, logical_operator)
[ "\n :type identifiers: SimpleIdentifierCollection\n\n :param permission_s: a collection of 1..N permissions\n :type permission_s: List of Permission objects or Strings\n\n :param logical_operator: indicates whether all or at least one\n permission check ...
Please provide a description of the function:def has_role_collective(self, identifiers, role_s, logical_operator): return self.authorizer.has_role_collective(identifiers, role_s, logical_operator)
[ "\n :type identifiers: SimpleIdentifierCollection\n\n :param logical_operator: indicates whether all or at least one\n permission check is true (any)\n :type: any OR all (from python standard library)\n\n :param role_s: 1..N role identifier\n :typ...
Please provide a description of the function:def check_role(self, identifiers, role_s, logical_operator): return self.authorizer.check_role(identifiers, role_s, logical_operator)
[ "\n :type identifiers: SimpleIdentifierCollection\n\n :param role_s: 1..N role identifier\n :type role_s: a Set of Strings\n\n :param logical_operator: indicates whether all or at least one\n permission check is true (any)\n :type: any OR all (fr...
Please provide a description of the function:def create_subject(self, authc_token=None, account_id=None, existing_subject=None, subject_context=None): if subject_context is None: # this that means a successful ...
[ "\n Creates a ``Subject`` instance for the user represented by the given method\n arguments.\n\n It is an overloaded method, due to porting java to python, and is\n consequently highly likely to be refactored.\n\n It gets called in one of two ways:\n 1) when creating an ano...
Please provide a description of the function:def login(self, subject, authc_token): try: # account_id is a SimpleIdentifierCollection account_id = self.authenticator.authenticate_account(subject.identifiers, authc_...
[ "\n Login authenticates a user using an AuthenticationToken. If authentication is\n successful AND the Authenticator has determined that authentication is\n complete for the account, login constructs a Subject instance representing\n the authenticated account's identity. Once a subject ...
Please provide a description of the function:def do_create_subject(self, subject_context): security_manager = subject_context.resolve_security_manager() session = subject_context.resolve_session() session_creation_enabled = subject_context.session_creation_enabled # passing the...
[ "\n By the time this method is invoked, all possible\n ``SubjectContext`` data (session, identifiers, et. al.) has been made\n accessible using all known heuristics.\n\n :returns: a Subject instance reflecting the data in the specified\n SubjectContext data map\n ...
Please provide a description of the function:def ensure_security_manager(self, subject_context): if (subject_context.resolve_security_manager() is not None): msg = ("Subject Context resolved a security_manager " "instance, so not re-assigning. Returning.") lo...
[ "\n Determines whether there is a ``SecurityManager`` instance in the context,\n and if not, adds 'self' to the context. This ensures that do_create_subject\n will have access to a ``SecurityManager`` during Subject construction.\n\n :param subject_context: the subject context data that...
Please provide a description of the function:def resolve_session(self, subject_context): if (subject_context.resolve_session() is not None): msg = ("Context already contains a session. Returning.") logger.debug(msg) return subject_context try: #...
[ "\n This method attempts to resolve any associated session based on the\n context and returns a context that represents this resolved Session to\n ensure it may be referenced, if needed, by the invoked do_create_subject\n that performs actual ``Subject`` construction.\n\n If there...
Please provide a description of the function:def resolve_identifiers(self, subject_context): session = subject_context.session identifiers = subject_context.resolve_identifiers(session) if (not identifiers): msg = ("No identity (identifier_collection) found in the " ...
[ "\n ensures that a subject_context has identifiers and if it doesn't will\n attempt to locate them using heuristics\n " ]
Please provide a description of the function:def logout(self, subject): if (subject is None): msg = "Subject argument cannot be None." raise ValueError(msg) self.before_logout(subject) identifiers = copy.copy(subject.identifiers) # copy is new to yosai ...
[ "\n Logs out the specified Subject from the system.\n\n Note that most application developers should not call this method unless\n they have a good reason for doing so. The preferred way to logout a\n Subject is to call ``Subject.logout()``, not by calling ``SecurityManager.logout``\n ...
Please provide a description of the function:def get_remembered_identity(self, subject_context): rmm = self.remember_me_manager if rmm is not None: try: return rmm.get_remembered_identifiers(subject_context) except Exception as ex: msg = (...
[ "\n Using the specified subject context map intended to build a ``Subject``\n instance, returns any previously remembered identifiers for the subject\n for automatic identity association (aka 'Remember Me').\n " ]
Please provide a description of the function:def do_clear_cache(self, identifier): msg = "Clearing cache for: " + str(identifier) logger.debug(msg) self.clear_cached_authc_info(identifier) self.clear_cached_authorization_info(identifier)
[ "\n :param identifier: the identifier of a specific source, extracted from\n the SimpleIdentifierCollection (identifiers)\n " ]
Please provide a description of the function:def clear_cached_authc_info(self, identifier): msg = "Clearing cached authc_info for [{0}]".format(identifier) logger.debug(msg) self.cache_handler.delete('authentication:' + self.name, identifier)
[ "\n When cached credentials are no longer needed, they can be manually\n cleared with this method. However, account credentials may be\n cached with a short expiration time (TTL), making the manual clearing\n of cached credentials an alternative use case.\n\n :param identifier: t...
Please provide a description of the function:def clear_cached_authorization_info(self, identifier): msg = "Clearing cached authz_info for [{0}]".format(identifier) logger.debug(msg) key = 'authorization:permissions:' + self.name self.cache_handler.delete(key, identifier)
[ "\n This process prevents stale authorization data from being used.\n If any authorization data for an account is changed at runtime, such as\n adding or removing roles and/or permissions, the subclass implementation\n of AccountStoreRealm should clear the cached AuthorizationInfo for th...
Please provide a description of the function:def lock_account(self, identifier): locked_time = int(time.time() * 1000) # milliseconds self.account_store.lock_account(identifier, locked_time)
[ "\n :type account: Account\n " ]
Please provide a description of the function:def get_authentication_info(self, identifier): account_info = None ch = self.cache_handler def query_authc_info(self): msg = ("Could not obtain cached credentials for [{0}]. " "Will try to acquire credentials ...
[ "\n The default authentication caching policy is to cache an account's\n credentials that are queried from an account store, for a specific\n user, so to facilitate any subsequent authentication attempts for\n that user. Naturally, in order to cache one must have a CacheHandler.\n ...
Please provide a description of the function:def authenticate_account(self, authc_token): try: identifier = authc_token.identifier except AttributeError: msg = 'Failed to obtain authc_token.identifiers' raise AttributeError(msg) tc = authc_token.__cl...
[ "\n :type authc_token: authc_abcs.AuthenticationToken\n :rtype: dict\n :raises IncorrectCredentialsException: when authentication fails\n " ]
Please provide a description of the function:def assert_credentials_match(self, verifier, authc_token, account): cred_type = authc_token.token_info['cred_type'] try: verifier.verify_credentials(authc_token, account['authc_info']) except IncorrectCredentialsException: ...
[ "\n :type verifier: authc_abcs.CredentialsVerifier\n :type authc_token: authc_abcs.AuthenticationToken\n :type account: account_abcs.Account\n :returns: account_abcs.Account\n :raises IncorrectCredentialsException: when authentication fails,\n ...
Please provide a description of the function:def get_authzd_permissions(self, identifier, perm_domain): related_perms = [] keys = ['*', perm_domain] def query_permissions(self): msg = ("Could not obtain cached permissions for [{0}]. " "Will try to acquir...
[ "\n :type identifier: str\n :type domain: str\n\n :returns: a list of relevant json blobs, each a list of permission dicts\n " ]
Please provide a description of the function:def is_permitted(self, identifiers, permission_s): identifier = identifiers.primary_identifier for required in permission_s: domain = Permission.get_domain(required) # assigned is a list of json blobs: assigned =...
[ "\n If the authorization info cannot be obtained from the accountstore,\n permission check tuple yields False.\n\n :type identifiers: subject_abcs.IdentifierCollection\n\n :param permission_s: a collection of one or more permissions, represented\n as string-b...
Please provide a description of the function:def has_role(self, identifiers, required_role_s): identifier = identifiers.primary_identifier # assigned_role_s is a set assigned_role_s = self.get_authzd_roles(identifier) if not assigned_role_s: msg = 'has_role: no ro...
[ "\n Confirms whether a subject is a member of one or more roles.\n\n If the authorization info cannot be obtained from the accountstore,\n role check tuple yields False.\n\n :type identifiers: subject_abcs.IdentifierCollection\n\n :param required_role_s: a collection of 1..N Role...
Please provide a description of the function:def on_start(self, session, session_context): session_id = session.session_id web_registry = session_context['web_registry'] if self.is_session_id_cookie_enabled: web_registry.session_id = session_id logger.debug("Set...
[ "\n Stores the Session's ID, usually as a Cookie, to associate with future\n requests.\n\n :param session: the session that was just ``createSession`` created\n " ]
Please provide a description of the function:def on_expiration(self, session, ese=None, session_key=None): super().on_expiration(session, ese, session_key) self.on_invalidation(session_key)
[ "\n :type session: session_abcs.Session\n :type ese: ExpiredSessionException\n :type session_key: session_abcs.SessionKey\n " ]
Please provide a description of the function:def on_invalidation(self, session_key, session=None, ise=None): if session: super().on_invalidation(session, ise, session_key) web_registry = session_key.web_registry del web_registry.session_id
[ "\n :type session_key: session_abcs.SessionKey\n :type session: session_abcs.Session\n :type ese: InvalidSessionException\n " ]
Please provide a description of the function:def create_exposed_session(self, session, key=None, context=None): if key: return WebDelegatingSession(self, key) web_registry = context['web_registry'] session_key = WebSessionKey(session.session_id, ...
[ "\n This was an overloaded method ported from java that should be refactored. (TBD)\n Until it is refactored, it is called in one of two ways:\n 1) passing it session and session_context\n 2) passing it session and session_key\n " ]
Please provide a description of the function:def new_csrf_token(self, session_key): try: csrf_token = self._generate_csrf_token() session = self._lookup_required_session(session_key) session.set_internal_attribute('csrf_token', csrf_token) self.session_h...
[ "\n :rtype: str\n :returns: a CSRF token\n " ]
Please provide a description of the function:def pop_flash(self, queue='default'): flash_messages = self.get_internal_attribute('flash_messages') messages = flash_messages.pop(queue, None) self.set_internal_attribute('flash_messages', flash_messages) return messages
[ "\n :rtype: list\n " ]
Please provide a description of the function:def is_session_storage_enabled(self, subject=None): if subject.get_session(False): # then use what already exists return True if not self.session_storage_enabled: # honor global setting: return False ...
[ "\n Returns ``True`` if session storage is generally available (as determined\n by the super class's global configuration property is_session_storage_enabled\n and no request-specific override has turned off session storage, False\n otherwise.\n\n This means session storage is dis...
Please provide a description of the function:def default_marshaller(obj): if hasattr(obj, '__getstate__'): return obj.__getstate__() try: return obj.__dict__ except AttributeError: raise TypeError('{!r} has no __dict__ attribute and does not implement __getstate__()' ...
[ "\n Retrieve the state of the given object.\n\n Calls the ``__getstate__()`` method of the object if available, otherwise returns the\n ``__dict__`` of the object.\n\n :param obj: the object to marshal\n :return: the marshalled object state\n\n " ]
Please provide a description of the function:def default_unmarshaller(instance, state): if hasattr(instance, '__setstate__'): instance.__setstate__(state) else: try: instance.__dict__.update(state) except AttributeError: raise TypeError('{!r} has no __dict__ ...
[ "\n Restore the state of an object.\n\n If the ``__setstate__()`` method exists on the instance, it is called with the state object\n as the argument. Otherwise, the instance's ``__dict__`` is replaced with ``state``.\n\n :param instance: an uninitialized instance\n :param state: the state object, as...
Please provide a description of the function:def init_realms(self, realms): self.realms = tuple(realm for realm in realms if isinstance(realm, realm_abcs.AuthenticatingRealm)) self.register_cache_clear_listener() self.token_realm_resolver = self.init_token_re...
[ "\n :type realms: Tuple\n " ]
Please provide a description of the function:def authenticate_account(self, identifiers, authc_token, second_factor_token=None): msg = ("Authentication submission received for authentication " "token [" + str(authc_token) + "]") logger.debug(msg) # the following conditio...
[ "\n :type identifiers: SimpleIdentifierCollection or None\n\n :returns: account_id (identifiers) if the account authenticates\n :rtype: SimpleIdentifierCollection\n " ]
Please provide a description of the function:def do_authenticate_account(self, authc_token): try: realms = self.token_realm_resolver[authc_token.__class__] except KeyError: raise KeyError('Unsupported Token Type Provided: ', authc_token.__class__.__name__) if (l...
[ "\n Returns an account object only when the current token authenticates AND\n the authentication process is complete, raising otherwise\n\n :returns: Account\n :raises AdditionalAuthenticationRequired: when additional tokens are required,\n ...
Please provide a description of the function:def clear_cache(self, items=None, topic=EVENT_TOPIC): try: for realm in self.realms: identifier = items.identifiers.from_source(realm.name) if identifier: realm.clear_cached_authc_info(identifie...
[ "\n expects event object to be in the format of a session-stop or\n session-expire event, whose results attribute is a\n namedtuple(identifiers, session_key)\n " ]
Please provide a description of the function:def validate_locked(self, authc_token, failed_attempts): if self.locking_limit and len(failed_attempts) > self.locking_limit: msg = ('Authentication attempts breached threshold. Account' ' is now locked for: ' + str(authc_toke...
[ "\n :param failed_attempts: the failed attempts for this type of credential\n " ]
Please provide a description of the function:def extra_from_record(self, record): return { attr_name: record.__dict__[attr_name] for attr_name in record.__dict__ if attr_name not in BUILTIN_ATTRS }
[ "Returns `extra` dict you passed to logger.\n\n The `extra` keyword argument is used to populate the `__dict__` of\n the `LogRecord`.\n\n " ]
Please provide a description of the function:def json_record(self, message, extra, record, traceback): extra['message'] = message if 'time' not in extra: extra['time'] = datetime.now(pytz.utc) if traceback is not None: extra['traceback'] = traceback retur...
[ "Prepares a JSON payload which will be logged.\n\n Override this method to change JSON log format.\n\n :param message: Log message, e.g., `logger.info(msg='Sign up')`.\n :param extra: Dictionary that was passed as `extra` param\n `logger.info('Sign up', extra={'referral_code': '52d6c...
Please provide a description of the function:def identifiers(self, identifiers): if (isinstance(identifiers, subject_abcs.IdentifierCollection) or identifiers is None): self._identifiers = identifiers else: raise ValueError('must use IdentifierCollection'...
[ "\n :type identifiers: subject_abcs.IdentifierCollection\n " ]
Please provide a description of the function:def is_permitted(self, permission_s): if self.authorized: self.check_security_manager() return (self.security_manager.is_permitted( self.identifiers, permission_s)) msg = 'Cannot check permission when user...
[ "\n :param permission_s: a collection of 1..N permissions\n :type permission_s: List of authz_abcs.Permission object(s) or String(s)\n\n :returns: a List of tuple(s), containing the authz_abcs.Permission and a\n Boolean indicating whether the permission is granted\n " ]
Please provide a description of the function:def is_permitted_collective(self, permission_s, logical_operator=all): sm = self.security_manager if self.authorized: return sm.is_permitted_collective(self.identifiers, permission_s, ...
[ "\n :param permission_s: a List of authz_abcs.Permission objects\n\n :param logical_operator: indicates whether *all* or at least one\n permission check is true, *any*\n :type: any OR all (functions from python stdlib)\n\n :returns: a Boolean\n "...
Please provide a description of the function:def check_permission(self, permission_s, logical_operator=all): self.assert_authz_check_possible() if self.authorized: self.security_manager.check_permission(self.identifiers, permission_...
[ "\n :param permission_s: a collection of 1..N permissions\n :type permission_s: List of authz_abcs.Permission objects or Strings\n\n :param logical_operator: indicates whether all or at least one\n permission check is true (any)\n :type: any OR all (from...
Please provide a description of the function:def has_role(self, role_s): if self.authorized: return self.security_manager.has_role(self.identifiers, role_s) msg = 'Cannot check permission when identifiers aren\'t set!' raise ValueError(msg)
[ "\n :param role_s: 1..N role identifiers (strings)\n :type role_s: Set of Strings\n\n :returns: a set of tuple(s), containing the role and a Boolean\n indicating whether the user is a member of the Role\n " ]
Please provide a description of the function:def has_role_collective(self, role_s, logical_operator=all): if self.authorized: return self.security_manager.has_role_collective(self.identifiers, role_s, ...
[ "\n :param role_s: 1..N role identifier\n :type role_s: a Set of Strings\n\n :param logical_operator: indicates whether all or at least one\n permission check is true (any)\n :type: any OR all (from python standard library)\n\n :returns: a Boolea...
Please provide a description of the function:def check_role(self, role_ids, logical_operator=all): if self.authorized: self.security_manager.check_role(self.identifiers, role_ids, logical_operator) ...
[ "\n :param role_ids: 1 or more RoleIds\n :type role_ids: a Set of Strings\n\n :param logical_operator: indicates whether all or at least one\n permission check is true (any)\n :type: any OR all (from python stdlib)\n\n :raises UnauthorizedExcepti...
Please provide a description of the function:def login(self, authc_token): self.clear_run_as_identities_internal() # login raises an AuthenticationException if it fails to authenticate: subject = self.security_manager.login(subject=self, aut...
[ "\n :type authc_token: authc_abcs.AuthenticationToken\n\n authc_token's password is cleartext that is stored as a bytearray.\n The authc_token password is cleared in memory, within the authc_token,\n when authentication is successful.\n " ]
Please provide a description of the function:def get_session(self, create=True): msg = ("{0} attempting to get session; create = {1}; \'session is None\' =" "{2} ; \'session has id\' = {3}". format(self.__class__.__name__, create, (self.session is None), str( ...
[ "\n :type create: bool\n " ]
Please provide a description of the function:def run_as(self, identifiers): if (not self.has_identifiers): msg = ("This subject does not yet have an identity. Assuming the " "identity of another Subject is only allowed for Subjects " "with an existing ...
[ "\n :type identifiers: subject_abcs.IdentifierCollection\n " ]
Please provide a description of the function:def get_previous_identifiers(self): previous_identifiers = None stack = self.get_run_as_identifiers_stack() # TBD: must confirm logic if stack: if (len(stack) == 1): previous_identifiers = self.identifiers ...
[ "\n :returns: SimpleIdentifierCollection\n " ]
Please provide a description of the function:def get_run_as_identifiers_stack(self): session = self.get_session(False) try: return session.get_internal_attribute(self.run_as_identifiers_session_key) except AttributeError: return None
[ "\n :returns: an IdentifierCollection\n " ]
Please provide a description of the function:def push_identity(self, identifiers): if (not identifiers): msg = ("Specified Subject identifiers cannot be None or empty " "for 'run as' functionality.") raise ValueError(msg) stack = self.get_run_as_ident...
[ "\n :type identifiers: subject_abcs.IdentifierCollection\n " ]
Please provide a description of the function:def pop_identity(self): popped = None stack = self.get_run_as_identifiers_stack() if (stack): popped = stack.pop() if (stack): # persist the changed stack to the session session = self....
[ "\n :returns: SimpleIdentifierCollection\n " ]
Please provide a description of the function:def save(self, subject): if (self.is_session_storage_enabled(subject)): self.merge_identity(subject) else: msg = ("Session storage of subject state for Subject [{0}] has " "been disabled: identity and authen...
[ "\n Saves the subject's state to the subject's ``Session`` only\n if session storage is enabled for the subject. If session storage is\n not enabled for the specific Subject, this method does nothing.\n\n In either case, the argument Subject is returned directly (a new\n ``Subjec...
Please provide a description of the function:def merge_identity(self, subject): current_identifiers = None if subject.is_run_as: # avoid the other steps of attribute access when referencing by # property by referencing the underlying attribute directly: curr...
[ "\n Merges the Subject's identifying attributes (principals) and authc status\n into the Subject's session\n\n :type subject: subject_abcs.Subject\n " ]
Please provide a description of the function:def delete(self, subject): session = subject.get_session(False) if (session): session.remove_internal_attribute(self.dsc_ask) session.remove_internal_attribute(self.dsc_isk)
[ "\n :type subject: subject_abcs.Subject\n " ]
Please provide a description of the function:def _get_subject(self): subject_context = SubjectContext(yosai=self, security_manager=self.security_manager) subject = self.security_manager.create_subject(subject_context=subject_context) global_subject_context.stack.append(subject) ...
[ "\n Returns the currently accessible Subject available to the calling code\n depending on runtime environment.\n\n :returns: the Subject currently accessible to the calling code\n " ]
Please provide a description of the function:def requires_authentication(fn): @functools.wraps(fn) def wrap(*args, **kwargs): subject = Yosai.get_current_subject() if not subject.authenticated: msg = "The current Subject is not authenticated. ACCESS DE...
[ "\n Requires that the calling Subject be authenticated before allowing access.\n\n :raises UnauthenticatedException: indicating that the decorated method is\n not allowed to be executed because the\n Subject failed to au...