code
stringlengths
1
18.2k
def system_image_type(self, system_image_type): """ Sets the system_image_type of this BuildEnvironmentRest. :param system_image_type: The system_image_type of this BuildEnvironmentRest. :type: str """ allowed_values = ["DOCKER_IMAGE", "VIRTUAL_MACHINE_RAW", "VIRTUAL_MACHINE_QCOW2", "LOCAL_WORKSPACE"] if system_image_t...
def get_public_cms_app_namespaces(): """ :return: a tuple() with all cms app namespaces """ qs = Page.objects.public() qs = qs.exclude(application_namespace=None) qs = qs.order_by('application_namespace') try: application_namespaces = list( qs.distinct('application_namespace').values_list( 'application_namespace', flat...
def get_public_cms_page_urls(*, language_code): """ :param language_code: e.g.: "en" or "de" :return: Tuple with all public urls in the given language """ pages = Page.objects.public() urls = [page.get_absolute_url(language=language_code) for page in pages] urls.sort() return tuple(urls)
def group_by_source(self): """Return a dict of all of the docs, with the source associated with the doc as a key""" from collections import defaultdict docs = defaultdict(list) for k, v in self.items(): if 'source' in v: docs[v.source].append(dict(v.items())) return docs
def preauthChild(self, path): """ Use me if `path' might have slashes in it, but you know they're safe. (NOT slashes at the beginning. It still needs to be a _child_). """ newpath = abspath(joinpath(self.path, normpath(path))) if not newpath.startswith(self.path): raise InsecurePath("%s is not a child of %s" % (newpath...
def childSearchPreauth(self, *paths): """Return my first existing child with a name in 'paths'. paths is expected to be a list of *pre-secured* path fragments; in most cases this will be specified by a system administrator and not an arbitrary user. If no appropriately-named children exist, this will return None. """ p...
def siblingExtensionSearch(self, *exts): """Attempt to return a path with my name, given multiple possible extensions. Each extension in exts will be tested and the first path which exists will be returned. If no path exists, None will be returned. If '' is in exts, then if the file referred to by this path exists, 'se...
def globChildren(self, pattern): """ Assuming I am representing a directory, return a list of FilePaths representing my children that match the given pattern. """ import glob path = self.path[-1] == '/' and self.path + pattern or slash.join([self.path, pattern]) return map(self.clonePath, glob.glob(path))
def create(self): """Exclusively create a file, only if this file previously did not exist. """ fdint = os.open(self.path, (os.O_EXCL | os.O_CREAT | os.O_RDWR)) # XXX TODO: 'name' attribute of returned files is not mutable or # settable via fdopen, so this file is slighly less functional than the # one returned from 'o...
def temporarySibling(self): """ Create a path naming a temporary sibling of this path in a secure fashion. """ sib = self.parent().child(_secureEnoughString() + self.basename()) sib.requireCreate() return sib
def parseDiskStatLine(L): """ Parse a single line from C{/proc/diskstats} into a two-tuple of the name of the device to which it corresponds (ie 'hda') and an instance of the appropriate record type (either L{partitionstat} or L{diskstat}). """ parts = L.split() device = parts[2] if len(parts) == 7: factory = partition...
def discoverCurrentWorkingDevice(procMounts='/proc/self/mounts'): """ Return a short string naming the device which backs the current working directory, ie C{/dev/hda1}. """ possibilities = [] cwd = os.getcwd() with file(procMounts, 'rb') as f: for L in f: parts = L.split() if cwd.startswith(parts[1]): possibilities.ap...
def makeBenchmarkRunner(path, args): """ Make a function that will run two Python processes serially: first one which calls the setup function from the given file, then one which calls the execute function from the given file. """ def runner(): return BenchmarkProcess.spawn( executable=sys.executable, args=['-Wignore']...
def start(): """ Start recording stats. Call this from a benchmark script when your setup is done. Call this at most once. @raise RuntimeError: Raised if the parent process responds with anything other than an acknowledgement of this message. """ os.write(BenchmarkProcess.BACKCHANNEL_OUT, BenchmarkProcess.START) respon...
def stop(): """ Stop recording stats. Call this from a benchmark script when the code you want benchmarked has finished. Call this exactly the same number of times you call L{start} and only after calling it. @raise RuntimeError: Raised if the parent process responds with anything other than an acknowledgement of this ...
def main(): """ Run me with the filename of a benchmark script as an argument. I will time it and append the results to a file named output in the current working directory. """ name = sys.argv[1] path = filepath.FilePath('.stat').temporarySibling() path.makedirs() func = makeBenchmarkRunner(path, sys.argv[1:]) try: be...
def spawn(cls, executable, args, path, env, spawnProcess=None): """ Run an executable with some arguments in the given working directory with the given environment variables. Returns a Deferred which fires with a two-tuple of (exit status, output list) if the process terminates without timing out or being killed by a s...
def get(orcid_id): """ Get an author based on an ORCID identifier. """ resp = requests.get(ORCID_PUBLIC_BASE_URL + unicode(orcid_id), headers=BASE_HEADERS) json_body = resp.json() return Author(json_body)
def _contextualize(contextFactory, contextReceiver): """ Invoke a callable with an argument derived from the current execution context (L{twisted.python.context}), or automatically created if none is yet present in the current context. This function, with a better name and documentation, should probably be somewhere in...
callable object, called with the result of calling the contextFactory, or retrieving the contextFactory from the context. """ value = context.get(contextFactory, _NOT_SPECIFIED) if value is not _NOT_SPECIFIED: return contextReceiver(value) else: return context.call({contextFactory: contextFactory()}, _contextualize, co...
def record(*a, **kw): """ Are you tired of typing class declarations that look like this:: class StuffInfo: def __init__(self, a=None, b=None, c=None, d=None, e=None, f=None, g=None, h=None, i=None, j=None): self.a = a self.b = b self.c = c self.d = d # ... Epsilon can help! That's right - for a limited time only, this...
arbitrary number of keyword arguments, which map attribute names to their default values. If no positional argument is provided, the names of attributes will be inferred from the names of the defaults instead. """ if len(a) == 1: attributeNames = a[0].split() elif len(a) == 0: if not kw: raise TypeError("Attempted to d...
default is not _NOT_SPECIFIED: defaults.append(default) else: # This space left intentionally blank. pass if kw: raise TypeError("The following defaults did not apply: %r" % (kw,)) return type('Record<%s>' % (' '.join(attributeNames),), (StructBehavior,), dict(__names__=attributeNames, __defaults__=defaults))
def recursiveRepr(self, stuff, thunk=repr): """ Recursive repr(). """ ID = id(stuff) if ID in self.active: return '%s(...)' % (stuff.__class__.__name__,) else: try: self.active[ID] = stuff return thunk(stuff) finally: del self.active[ID]
def parse(content): """ Reference: https://github.com/osdlyrics/osdlyrics/blob/master/python/lrc.py >>> parse("[00:00.00] 作曲 : 周杰伦\\n[00:01.00] 作词 : 周杰伦\\n") {0.0: ' 作曲 : 周杰伦', 1000.0: ' 作词 : 周杰伦'} """ ms_sentence_map = dict() sentence_pattern = re.compile(r'\[(\d+(:\d+){0,2}(\.\d+)?)\]') lines = content.splitlines() f...
def create_product(name, abbreviation, **kwargs): """ Create a new Product """ data = create_product_raw(name, abbreviation, **kwargs) if data: return utils.format_json(data)
def update_product(product_id, **kwargs): """ Update a Product with new information """ content = update_product_raw(product_id, **kwargs) if content: return utils.format_json(content)
def get_product(id=None, name=None): """ Get a specific Product by name or ID """ content = get_product_raw(id, name) if content: return utils.format_json(content)
def list_versions_for_product(id=None, name=None, page_size=200, page_index=0, sort='', q=''): """ List all ProductVersions for a given Product """ content = list_versions_for_product_raw(id, name, page_size, page_index, sort, q) if content: return utils.format_json_list(content)
def list_products(page_size=200, page_index=0, sort="", q=""): """ List all Products """ content = list_products_raw(page_size, page_index, sort, q) if content: return utils.format_json_list(content)
def geocode(self): """A Generator that reads from the address generators and returns geocode results. The generator yields ( address, geocode_results, object) """ submit_set = [] data_map = {} for address, o in self.gen: submit_set.append(address) data_map[address] = o if len(submit_set) >= self.submit_size: results = ...
def migrate(connection, dsn): """ Collects all migrations and applies missed. Args: connection (sqlalchemy connection): """ all_migrations = _get_all_migrations() logger.debug('Collected migrations: {}'.format(all_migrations)) for version, modname in all_migrations: if _is_missed(connection, version) and version <= SCH...
def create_migration_template(name): """ Creates migration file. Returns created file name. Args: name (str): name of the migration. Returns: str: name of the migration file. """ assert name, 'Name of the migration can not be empty.' from . import migrations # Find next number # package = migrations prefix = package.__...
def get_stored_version(connection): """ Returns database version. Args: connection (sqlalchemy connection): Raises: Assuming user_version pragma (sqlite case) and user_version table (postgresql case) exist because they created with the database creation. Returns: int: version of the database. """ if connection.engine.n...
def _validate_version(connection, dsn): """ Performs on-the-fly schema updates based on the models version. Raises: DatabaseError: if user uses old sqlite database. """ try: version = get_stored_version(connection) except VersionIsNotStored: logger.debug('Version not stored in the db: assuming new database creation.') ...
def _migration_required(connection): """ Returns True if ambry models do not match to db tables. Otherwise returns False. """ stored_version = get_stored_version(connection) actual_version = SCHEMA_VERSION assert isinstance(stored_version, int) assert isinstance(actual_version, int) assert stored_version <= actual_vers...
def _update_version(connection, version): """ Updates version in the db to the given version. Args: connection (sqlalchemy connection): sqlalchemy session where to update version. version (int): version of the migration. """ if connection.engine.name == 'sqlite': connection.execute('PRAGMA user_version = {}'.format(ver...
def _get_all_migrations(): """ Returns sorted list of all migrations. Returns: list of (int, str) tuples: first elem of the tuple is migration number, second if module name. """ from . import migrations package = migrations prefix = package.__name__ + '.' all_migrations = [] for importer, modname, ispkg in pkgutil.iter...
def create(self): """Create the database from the base SQL.""" if not self.exists(): self._create_path() self.create_tables() return True return False
def _create_path(self): """Create the path to hold the database, if one wwas specified.""" if self.driver == 'sqlite' and 'memory' not in self.dsn and self.dsn != 'sqlite://': dir_ = os.path.dirname(self.path) if dir_ and not os.path.exists(dir_): try: # Multiple process may try to make, so it could already # exist os....
def exists(self): """Return True if the database exists, or for Sqlite, which will create the file on the first reference, the file has been initialized with the root config """ if self.driver == 'sqlite' and not os.path.exists(self.path): return False # init engine self.engine try: # Since we are using the connection,...
def engine(self): """return the SqlAlchemy engine for this database.""" if not self._engine: if 'postgres' in self.driver: if 'connect_args' not in self.engine_kwargs: self.engine_kwargs['connect_args'] = { 'application_name': '{}:{}'.format(self._application_prefix, os.getpid()) } # For most use, a small pool is good ...
to pid %s, attempting to check out in pid %s" % (connection_record.info['pid'], pid)) if self.driver == 'sqlite': @event.listens_for(self._engine, 'connect') def pragma_on_connect(dbapi_con, con_record): """ISSUE some Sqlite pragmas when the connection is created.""" # dbapi_con.execute('PRAGMA foreign_keys = ON;') # N...
def connection(self): """Return an SqlAlchemy connection.""" if not self._connection: logger.debug('Opening connection to: {}'.format(self.dsn)) self._connection = self.engine.connect() logger.debug('Opened connection to: {}'.format(self.dsn)) # logger.debug("Opening connection to: {}".format(self.dsn)) return self._co...
def session(self): """Return a SqlAlchemy session.""" from sqlalchemy.orm import sessionmaker from sqlalchemy.event import listen if not self.Session: self.Session = sessionmaker(bind=self.engine) if not self._session: self._session = self.Session() # set the search path if self._schema: def after_begin(session, transa...
def metadata(self): """Return an SqlAlchemy MetaData object, bound to the engine.""" from sqlalchemy import MetaData metadata = MetaData(bind=self.engine, schema=self._schema) metadata.reflect(self.engine) return metadata
def _add_config_root(self): """ Adds the root dataset, which holds configuration values for the database. """ try: self.session.query(Dataset).filter_by(id=ROOT_CONFIG_NAME).one() self.close_session() except NoResultFound: o = Dataset( id=ROOT_CONFIG_NAME, vid=ROOT_CONFIG_NAME_V, name=ROOT_CONFIG_NAME, vname=ROOT_CONFI...
def new_dataset(self, *args, **kwargs): """ Creates a new dataset :param args: Positional args passed to the Dataset constructor. :param kwargs: Keyword args passed to the Dataset constructor. :return: :class:`ambry.orm.Dataset` :raises: :class:`ambry.orm.ConflictError` if the a Dataset records already exists with the ...
def root_dataset(self): """Return the root dataset, which hold configuration values for the library""" ds = self.dataset(ROOT_CONFIG_NAME_V) ds._database = self return ds
def package_dataset(self): """For sqlite bundle packages, return the first ( and only ) dataset""" return self.session.query(Dataset).filter(Dataset.vid != ROOT_CONFIG_NAME_V).one()
def dataset(self, ref, load_all=False, exception=True): """Return a dataset, given a vid or id :param ref: Vid or id for a dataset. If an id is provided, will it will return the one with the largest revision number :param load_all: Use a query that eagerly loads everything. :return: :class:`ambry.orm.Dataset` """ ref =...
elif exception: raise NotFoundError('No dataset in library for vid : {} '.format(ref)) else: return None
def datasets(self): """ Return all datasets :return: """ return self.session.query(Dataset).filter(Dataset.vid != ROOT_CONFIG_NAME_V).all()
def delete_tables_partitions(self, ds): """Fast delete of all of a datasets codes, columns, partitions and tables""" from ambry.orm import Code, Column, Table, Partition, ColumnStat, Process ssq = self.session.query ssq(Process).filter(Process.d_vid == ds.vid).delete() ssq(Code).filter(Code.d_vid == ds.vid).delete() ss...
def delete_partitions(self, ds): """Fast delete of all of a datasets codes, columns, partitions and tables""" from ambry.orm import Partition ssq = self.session.query ssq(Process).filter(Process.d_vid == ds.vid).delete() ssq(Code).filter(Code.d_vid == ds.vid).delete() ssq(ColumnStat).filter(ColumnStat.d_vid == ds.vid)....
def copy_dataset(self, ds, incver=False, cb=None, **kwargs): """ Copy a dataset into the database. :param ds: The source dataset to copy :param cb: A progress callback, taking two parameters: cb(message, num_records) :return: """ from ambry.orm import Table, Column, Partition, File, ColumnStat, Code, \ DataSource, Sour...
def copy_dataset_files(self, ds, incver=False, cb=None, **kwargs): """ Copy only files and configs into the database. :param ds: The source dataset to copy :param cb: A progress callback, taking two parameters: cb(message, num_records) :return: """ from ambry.orm import File tables = [File] return self._copy_dataset_co...
def next_sequence_id(self, parent_table_class, parent_vid, child_table_class): """Get the next sequence id for child objects for a parent object that has a child sequence field""" from sqlalchemy import text # Name of sequence id column in the child c_seq_col = child_table_class.sequence_id.property.columns[0].name p_s...
v else: # Must be postgres, or something else that supports "RETURNING" sql = text(""" UPDATE {p_table} SET {p_seq_col} = {p_seq_col} + 1 WHERE {p_vid_col} = '{parent_vid}' RETURNING {p_seq_col} """.format(p_table=parent_table_class.__tablename__, p_seq_col=p_seq_col, p_vid_col=p_vid_col, parent_vid=parent_vid)) self.c...
def create_table(table, connection, schema=None): """Create a single table, primarily used din migrations""" orig_schemas = {} # These schema shenanigans are almost certainly wrong. # But they are expedient. For Postgres, it puts the library # tables in the Library schema. We need to change the schema for all tables in...
def _deferGenerator(g, deferred=None): """ See L{waitForDeferred}. """ result = None while 1: if deferred is None: deferred = defer.Deferred() try: result = g.next() except StopIteration: deferred.callback(result) return deferred except: deferred.errback() return deferred # Deferred.callback(Deferred) raises an error; ...
# and return from the loop waiting[0] = False return deferred result = None
def return_locals(func): '''Modifies decorated function to return its locals''' @functools.wraps(func) def wrap(*args, **kwargs): frames = [] def tracer(frame, event, arg): # pragma: no cover # coverage does not work in this function because the tracer # is deactivated here frames.append(frame) sys.settrace(old_tracer)...
def multidb_binds(databases, package=None, engine_params=None): '''Creates dictionary to be passed as `binds` parameter to `sqlalchemy.orm.sessionmaker()` from dictionary mapping models module name to connection URI that should be used for these models. Models module must have `metadata` attribute. `package` when set m...
for table in metadata.sorted_tables: binds[table] = engine return binds
def requiredAttribute(requiredAttributeName): """ Utility for defining attributes on base classes/mixins which require their values to be supplied by their derived classes. C{None} is a common, but almost never suitable default value for these kinds of attributes, as it may cause operations in the derived class to fail...
value on '<BrokenFooTestCase instance>'. ... >>> class WorkingFooTestCase(TestCase, FooTestMixin): ... expectedResult = 7 ... >>> workingFoo = WorkingFooTestCase() >>> print workingFoo.expectedResult ... 7 >>> """ class RequiredAttribute(attribute): def get(self): if requiredAttributeName not in self.__dict__: raise At...
def list_builds(page_size=200, page_index=0, sort="", q=""): """ List all builds :param page_size: number of builds returned per query :param sort: RSQL sorting query :param q: RSQL query :return: """ response = utils.checked_api_call(pnc_api.builds_running, 'get_all', page_size=page_size, page_index=page_index, sort=s...
def generate_repo_list(product_name=None, product_version=None, product_milestone=None): """ Generates list of artifacts for offline repository. """ if not validate_input_parameters(product_name, product_version, product_milestone): sys.exit(1) product_version = pnc_api.product_versions.get_all(q="version=='"+ product_...
def login(username=None, password=None): """ Log in to PNC using the supplied username and password. The keycloak token will be saved for all subsequent pnc-cli operations until login is called again :return: """ global user user = UserConfig() if username: user.username = username else: user.username = user.input_user...
def cancel(self): """Unschedule this call @raise AlreadyCancelled: Raised if this call has already been unscheduled. @raise AlreadyCalled: Raised if this call has already been made. """ if self.cancelled: raise error.AlreadyCancelled elif self.called: raise error.AlreadyCalled else: self.canceller(self) self.cancelled ...
def reset(self, secondsFromNow): """Reschedule this call for a different time @type secondsFromNow: C{float} @param secondsFromNow: The number of seconds from the time of the C{reset} call at which this call will be scheduled. @raise AlreadyCancelled: Raised if this call has been cancelled. @raise AlreadyCalled: Raised...
def delay(self, secondsLater): """Reschedule this call for a later time @type secondsLater: C{float} @param secondsLater: The number of seconds after the originally scheduled time for which to reschedule this call. @raise AlreadyCancelled: Raised if this call has been cancelled. @raise AlreadyCalled: Raised if this cal...
def main(): """ Start the AMP server and the reactor. """ startLogging(stdout) checker = InMemoryUsernamePasswordDatabaseDontUse() checker.addUser("testuser", "examplepass") realm = AdditionRealm() factory = CredAMPServerFactory(Portal(realm, [checker])) reactor.listenTCP(7805, factory) reactor.run()
def set_meta(self, instance): """ Set django-meta stuff from LandingPageModel instance. """ self.use_title_tag = True self.title = instance.title
def check(self, field): ''' Returns permissions determined by object itself ''' if self.permissions is None: return field.parent.permissions return self.permissions
def _load_view(self, template_engine_name, template_dir): """ Load view by name and return an instance. """ file_name = template_engine_name.lower() class_name = "{}View".format(template_engine_name.title()) try: view_module = import_module("rails.views.{}".format(file_name)) except ImportError: raise Exception("Templa...
def terminate(pid, sig, timeout): '''Terminates process with PID `pid` and returns True if process finished during `timeout`. Current user must have permission to access process information.''' os.kill(pid, sig) start = time.time() while True: try: # This is requireed if it's our child to avoid zombie. Also # is_runnin...
def doublefork(pidfile, logfile, cwd, umask): # pragma: nocover '''Daemonize current process. After first fork we return to the shell and removing our self from controling terminal via `setsid`. After second fork we are not session leader any more and cant get controlling terminal when opening files.''' try: if os.fork...
def match(self, search, **kwargs): """ Searches for Repository Configurations based on internal or external url, ignoring the protocol and \".git\" suffix. Only exact matches are returned. This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please define a `callback` function ...
def search(self, search, **kwargs): """ Search for Repository Configurations based on internal or external url, ignoring the protocol and \".git\" suffix. The matching is done using LIKE. This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please define a `callback` function t...
def make_mead(config=None, run_build=False, environment=1, suffix="", product_name=None, product_version=None, look_up_only="",clean_group=False): """ Create Build group based on Make-Mead configuration file :param config: Make Mead config name :return: """ ret=make_mead_impl(config, run_build, environment, suffix, pro...
def partition(self, id_): """Get a partition by the id number. Arguments: id_ -- a partition id value Returns: A partitions.Partition object Throws: a Sqlalchemy exception if the partition either does not exist or is not unique Because this method works on the bundle, the id_ ( without version information ) is equivale...
orm_partition = q.one() return self.bundle.wrap_partition(orm_partition) except NoResultFound: orm_partition = None return orm_partition
def _find_orm(self, pnq): """Return a Partition object from the database based on a PartitionId. An ORM object is returned, so changes can be persisted. """ # import sqlalchemy.orm.exc from ambry.orm import Partition as OrmPartition # , Table from sqlalchemy.orm import joinedload # , joinedload_all assert isinstance(pn...
if pnq.segment is not NameQuery.ANY: q = q.filter(OrmPartition.segment == pnq.segment) if pnq.table is not NameQuery.ANY: if pnq.table is None: q = q.filter(OrmPartition.t_id is None) else: tr = self.bundle.table(pnq.table) if not tr: raise ValueError("Didn't find table named {} in {} bundle path = {}".format( pnq.tabl...
def new_db_from_pandas(self, frame, table=None, data=None, load=True, **kwargs): """Create a new db partition from a pandas data frame. If the table does not exist, it will be created """ from ..orm import Column # from dbexceptions import ConfigurationError # Create the table from the information in the data frame. wi...
def update_project(id, **kwargs): """ Update an existing Project with new information """ content = update_project_raw(id, **kwargs) if content: return utils.format_json(content)
def get_project(id=None, name=None): """ Get a specific Project by ID or name """ content = get_project_raw(id, name) if content: return utils.format_json(content)
def delete_project(id=None, name=None): """ Delete a Project by ID or name. """ content = delete_project_raw(id, name) if content: return utils.format_json(content)
def list_projects(page_size=200, page_index=0, sort="", q=""): """ List all Projects """ content = list_projects_raw(page_size=page_size, page_index=page_index, sort=sort, q=q) if content: return utils.format_json_list(content)
def cancel(self, build_record_id, **kwargs): """ Build record push results. This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please define a `callback` function to be invoked when receiving the response. >>> def callback_function(response): >>> pprint(response) >>> >>> thre...
def get(self, build_record_id, **kwargs): """ Get Build Record Push Result by Id.. This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please define a `callback` function to be invoked when receiving the response. >>> def callback_function(response): >>> pprint(response) >>> >...
def push(self, **kwargs): """ Push build record results to Brew. This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please define a `callback` function to be invoked when receiving the response. >>> def callback_function(response): >>> pprint(response) >>> >>> thread = api.pu...
def push_0(self, build_record_id, **kwargs): """ Build record push results. This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please define a `callback` function to be invoked when receiving the response. >>> def callback_function(response): >>> pprint(response) >>> >>> thre...
def push_record_set(self, **kwargs): """ Push build config set record to Brew. This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please define a `callback` function to be invoked when receiving the response. >>> def callback_function(response): >>> pprint(response) >>> >>> t...
def status(self, build_record_id, **kwargs): """ Latest push result of BuildRecord. This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please define a `callback` function to be invoked when receiving the response. >>> def callback_function(response): >>> pprint(response) >>> ...
def set_handler(self, handler): """ Set transport handler @param handler: Handler, should derive from the C{sockjs.cyclone.transports.base.BaseTransportMixin} """ if self.handler is not None: raise Exception('Attempted to overwrite BaseSession handler') self.handler = handler self.transport_name = self.handler.name if ...
def verify_state(self): """ Verify if session was not yet opened. If it is, open it and call connection's C{connectionMade} """ if self.state == SESSION_STATE.CONNECTING: self.state = SESSION_STATE.OPEN self.conn.connectionMade(self.conn_info)
def close(self, code=3000, message='Go away!'): """ Close session or endpoint connection. @param code: Closing code @param message: Close message """ if self.state != SESSION_STATE.CLOSED: try: self.conn.connectionLost() except Exception as e: log.msg("Failed to call connectionLost(): %r." % e) finally: self.state = SE...