text
stringlengths
81
112k
Include Django.js javascript library initialization in the page def django_js_init(context, jquery=False, i18n=True, csrf=True, init=True): '''Include Django.js javascript library initialization in the page''' return { 'js': { 'jquery': _boolean(jquery), 'i18n': _boolean(i18n), ...
Serialize the context as a dictionnary from a given request. def as_dict(self): ''' Serialize the context as a dictionnary from a given request. ''' data = {} if settings.JS_CONTEXT_ENABLED: for context in RequestContext(self.request): for key, value ...
Fix language code when set to non included default `en` and add the extra variables ``LANGUAGE_NAME`` and ``LANGUAGE_NAME_LOCAL``. def process_LANGUAGE_CODE(self, language_code, data): ''' Fix language code when set to non included default `en` and add the extra variables ``LANGUAGE_NAM...
Insert user informations in data Override it to add extra user attributes. def handle_user(self, data): ''' Insert user informations in data Override it to add extra user attributes. ''' # Default to unauthenticated anonymous user data['user'] = { '...
Get a python class object from its name def class_from_string(name): ''' Get a python class object from its name ''' module_name, class_name = name.rsplit('.', 1) __import__(module_name) module = sys.modules[module_name] return getattr(module, class_name)
Glob a pattern or a list of pattern static storage relative(s). def glob(cls, files=None): ''' Glob a pattern or a list of pattern static storage relative(s). ''' files = files or [] if isinstance(files, str): files = os.path.normpath(files) matches = lam...
Execute a subprocess yielding output lines def execute(self, command): ''' Execute a subprocess yielding output lines ''' process = Popen(command, stdout=PIPE, stderr=STDOUT, universal_newlines=True) while True: if process.poll() is not None: self.ret...
Execute PhantomJS by giving ``args`` as command line arguments. If test are run in verbose mode (``-v/--verbosity`` = 2), it output: - the title as header (with separators before and after) - modules and test names - assertions results (with ``django.utils.termcolors`` support) ...
Run a phantomjs test suite. - ``phantomjs_runner`` is mandatory. - Either ``url`` or ``url_name`` needs to be defined. def run_suite(self): ''' Run a phantomjs test suite. - ``phantomjs_runner`` is mandatory. - Either ``url`` or ``url_name`` needs to be defined. ...
Write rows/keyed_rows to table def write(self, rows, keyed=False): """Write rows/keyed_rows to table """ for row in rows: keyed_row = row if not keyed: keyed_row = dict(zip(self.__schema.field_names, row)) keyed_row = self.__convert_row(keyed_...
Prepare bloom for existing checks def __prepare_bloom(self): """Prepare bloom for existing checks """ self.__bloom = pybloom_live.ScalableBloomFilter() columns = [getattr(self.__table.c, key) for key in self.__update_keys] keys = select(columns).execution_options(stream_results=...
Insert rows to table def __insert(self): """Insert rows to table """ if len(self.__buffer) > 0: # Insert data statement = self.__table.insert() if self.__autoincrement: statement = statement.returning( getattr(self.__table....
Update rows in table def __update(self, row): """Update rows in table """ expr = self.__table.update().values(row) for key in self.__update_keys: expr = expr.where(getattr(self.__table.c, key) == row[key]) if self.__autoincrement: expr = expr.returning(ge...
Check if row exists in table def __check_existing(self, row): """Check if row exists in table """ if self.__update_keys is not None: key = tuple(row[key] for key in self.__update_keys) if key in self.__bloom: return True self.__bloom.add(key) ...
https://github.com/frictionlessdata/tableschema-sql-py#storage def buckets(self): """https://github.com/frictionlessdata/tableschema-sql-py#storage """ buckets = [] for table in self.__metadata.sorted_tables: bucket = self.__mapper.restore_bucket(table.name) if b...
ERROR: type should be string, got "https://github.com/frictionlessdata/tableschema-sql-py#storage\n\ndef create(self, bucket, descriptor, force=False, indexes_fields=None):\n \"\"\"https://github.com/frictionlessdata/tableschema-sql-py#storage\n \"\"\"\n\n # Make lists\n buckets = bucket\n if isinstance(bucket, six.string_types):\n buckets = [bucket]\n descriptors = descriptor\n if isinstance(descriptor, dict):\n descriptors = [descriptor]\n if indexes_fields is None or len(indexes_fields) == 0:\n indexes_fields = [()] * len(descriptors)\n elif type(indexes_fields[0][0]) not in {list, tuple}:\n indexes_fields = [indexes_fields]\n\n # Check dimensions\n if not (len(buckets) == len(descriptors) == len(indexes_fields)):\n raise tableschema.exceptions.StorageError('Wrong argument dimensions')\n\n # Check buckets for existence\n for bucket in reversed(self.buckets):\n if bucket in buckets:\n if not force:\n message = 'Bucket \"%s\" already exists.' % bucket\n raise tableschema.exceptions.StorageError(message)\n self.delete(bucket)\n\n # Define buckets\n for bucket, descriptor, index_fields in zip(buckets, descriptors, indexes_fields):\n tableschema.validate(descriptor)\n table_name = self.__mapper.convert_bucket(bucket)\n columns, constraints, indexes, fallbacks, table_comment = self.__mapper \\\n .convert_descriptor(bucket, descriptor, index_fields, self.__autoincrement)\n Table(table_name, self.__metadata, *(columns + constraints + indexes),\n comment=table_comment)\n self.__descriptors[bucket] = descriptor\n self.__fallbacks[bucket] = fallbacks\n\n # Create tables, update metadata\n self.__metadata.create_all()"
ERROR: type should be string, got "https://github.com/frictionlessdata/tableschema-sql-py#storage\n\ndef delete(self, bucket=None, ignore=False):\n \"\"\"https://github.com/frictionlessdata/tableschema-sql-py#storage\n \"\"\"\n\n # Make lists\n buckets = bucket\n if isinstance(bucket, six.string_types):\n buckets = [bucket]\n elif bucket is None:\n buckets = reversed(self.buckets)\n\n # Iterate\n tables = []\n for bucket in buckets:\n\n # Check existent\n if bucket not in self.buckets:\n if not ignore:\n message = 'Bucket \"%s\" doesn\\'t exist.' % bucket\n raise tableschema.exceptions.StorageError(message)\n return\n\n # Remove from buckets\n if bucket in self.__descriptors:\n del self.__descriptors[bucket]\n\n # Add table to tables\n table = self.__get_table(bucket)\n tables.append(table)\n\n # Drop tables, update metadata\n self.__metadata.drop_all(tables=tables)\n self.__metadata.clear()\n self.__reflect()"
https://github.com/frictionlessdata/tableschema-sql-py#storage def describe(self, bucket, descriptor=None): """https://github.com/frictionlessdata/tableschema-sql-py#storage """ # Set descriptor if descriptor is not None: self.__descriptors[bucket] = descriptor # G...
https://github.com/frictionlessdata/tableschema-sql-py#storage def iter(self, bucket): """https://github.com/frictionlessdata/tableschema-sql-py#storage """ # Get table and fallbacks table = self.__get_table(bucket) schema = tableschema.Schema(self.describe(bucket)) # ...
https://github.com/frictionlessdata/tableschema-sql-py#storage def write(self, bucket, rows, keyed=False, as_generator=False, update_keys=None): """https://github.com/frictionlessdata/tableschema-sql-py#storage """ # Check update keys if update_keys is not None and len(update_keys) == ...
Get table by bucket def __get_table(self, bucket): """Get table by bucket """ table_name = self.__mapper.convert_bucket(bucket) if self.__dbschema: table_name = '.'.join((self.__dbschema, table_name)) return self.__metadata.tables[table_name]
Reflect metadata def __reflect(self): """Reflect metadata """ def only(name, _): return self.__only(name) and self.__mapper.restore_bucket(name) is not None self.__metadata.reflect(only=only)
Create SQL comment from field's title and description :param field: tableschema-py Field, with optional 'title' and 'description' values :param separator: :return: >>> _get_field_comment(tableschema.Field({'title': 'my_title', 'description': 'my_desc'})) 'my_title - my_desc' >>> _get_field_com...
Convert descriptor to SQL def convert_descriptor(self, bucket, descriptor, index_fields=[], autoincrement=None): """Convert descriptor to SQL """ # Prepare columns = [] indexes = [] fallbacks = [] constraints = [] column_mapping = {} table_name =...
Convert row to SQL def convert_row(self, keyed_row, schema, fallbacks): """Convert row to SQL """ for key, value in list(keyed_row.items()): field = schema.get_field(key) if not field: del keyed_row[key] if key in fallbacks: va...
Convert type to SQL def convert_type(self, type): """Convert type to SQL """ # Default dialect mapping = { 'any': sa.Text, 'array': None, 'boolean': sa.Boolean, 'date': sa.Date, 'datetime': sa.DateTime, 'duration':...
Restore bucket from SQL def restore_bucket(self, table_name): """Restore bucket from SQL """ if table_name.startswith(self.__prefix): return table_name.replace(self.__prefix, '', 1) return None
Restore descriptor from SQL def restore_descriptor(self, table_name, columns, constraints, autoincrement_column=None): """Restore descriptor from SQL """ # Fields fields = [] for column in columns: if column.name == autoincrement_column: continue ...
Restore row from SQL def restore_row(self, row, schema): """Restore row from SQL """ row = list(row) for index, field in enumerate(schema.fields): if self.__dialect == 'postgresql': if field.type in ['array', 'object']: continue ...
Restore type from SQL def restore_type(self, type): """Restore type from SQL """ # All dialects mapping = { ARRAY: 'array', sa.Boolean: 'boolean', sa.Date: 'date', sa.DateTime: 'datetime', sa.Float: 'number', sa.In...
CreateFileType 0 - Creates no new object. 1 - Creates a notebook with the specified name at the specified location. 2 - Creates a section group with the specified name at the specified location. 3 - Creates a section with the specified name at the specified location. def open_hi...
NewPageStyle 0 - Create a Page that has Default Page Style 1 - Create a blank page with no title 2 - Createa blank page that has no title def create_new_page (self, section_id, new_page_style=0): """ NewPageStyle 0 - Create a Page that has Default Page Style ...
PageInfo 0 - Returns only basic page content, without selection markup and binary data objects. This is the standard value to pass. 1 - Returns page content with no selection markup, but with all binary data. 2 - Returns page content with selection markup, but no binary data. 3 -...
PublishFormat 0 - Published page is in .one format. 1 - Published page is in .onea format. 2 - Published page is in .mht format. 3 - Published page is in .pdf format. 4 - Published page is in .xps format. 5 - Published page is in .doc or .docx format. ...
SpecialLocation 0 - Gets the path to the Backup Folders folder location. 1 - Gets the path to the Unfiled Notes folder location. 2 - Gets the path to the Default Notebook folder location. def get_special_location(self, special_location=0): """ SpecialLocation 0...
Determine memory specifications of the machine. Returns ------- mem_info : dictonary Holds the current values for the total, free and used memory of the system. def memory(): """Determine memory specifications of the machine. Returns ------- mem_info : dictonary Holds the ...
Given a two-dimensional array with a dimension of size 'N', determine the number of rows or columns that can fit into memory. Parameters ---------- N : int The size of one of the dimensions of a two-dimensional array. n : int The number of arrays of size 'N' times 'chunk_siz...
Determine whether or not to use a compression on the array stored in a hierarchical data format, and which compression library to use to that purpose. Compression reduces the HDF5 file size and also helps improving I/O efficiency for large datasets. Parameters ---------- byte_co...
Return the adjacency matrix to a hypergraph, in sparse matrix representation. Parameters ---------- cluster_runs : array of shape (n_partitions, n_samples) Returns ------- hypergraph_adjacency : compressed sparse row matrix Represents the hypergraph associated with an ensemble ...
Write an hypergraph adjacency to disk to disk in an HDF5 data structure. Parameters ---------- hypergraph_adjacency : compressed sparse row matrix hdf5_file_name : file handle or string def store_hypergraph_adjacency(hypergraph_adjacency, hdf5_file_name): """Write an hypergraph adjacency ...
Parameters ---------- hdf5_file_name : file handle or string Returns ------- hypergraph_adjacency : compressed sparse row matrix def load_hypergraph_adjacency(hdf5_file_name): """ Parameters ---------- hdf5_file_name : file handle or string Returns ------- ...
Call up to three different functions for heuristic ensemble clustering (namely CSPA, HGPA and MCLA) then select as the definitive consensus clustering the one with the highest average mutual information score between its vector of consensus labels and the vectors of labels associated to each ...
Compute a weighted average of the mutual information with the known labels, the weights being proportional to the fraction of known labels. Parameters ---------- cluster_runs : array of shape (n_partitions, n_samples) Each row of this matrix is such that the i-th entry corresponds to the ...
Ensure that a cluster labelling is in a valid format. Parameters ---------- cluster_run : array of shape (n_samples,) A vector of cluster IDs for each of the samples selected for a given round of clustering. The samples not selected are labelled with NaN. verbose : Boolean, optional (...
Alter a vector of cluster labels to a dense mapping. Given that this function is herein always called after passing a vector to the function checkcl, one_to_max relies on the assumption that cluster_run does not contain any NaN entries. Parameters ---------- array_in : a list or ...
Check that a matrix is a proper similarity matrix and bring appropriate changes if applicable. Parameters ---------- similarities : array of shape (n_samples, n_samples) A matrix of pairwise similarities between (sub)-samples of the data-set. verbose : Boolean, optional (default = Fa...
Cluster-based Similarity Partitioning Algorithm for a consensus function. Parameters ---------- hdf5_file_name : file handle or string cluster_runs : array of shape (n_partitions, n_samples) verbose : bool, optional (default = False) N_clusters_max : int, optional (default = ...
HyperGraph-Partitioning Algorithm for a consensus function. Parameters ---------- hdf5_file_name : string or file handle cluster_runs: array of shape (n_partitions, n_samples) verbose : bool, optional (default = False) N_clusters_max : int, optional (default = None) ...
Meta-CLustering Algorithm for a consensus function. Parameters ---------- hdf5_file_name : file handle or string cluster_runs : array of shape (n_partitions, n_samples) verbose : bool, optional (default = False) N_clusters_max : int, optional (default = None) Returns...
For a label vector represented by cluster_run, constructs the binary membership indicator matrix. Such matrices, when concatenated, contribute to the adjacency matrix for a hypergraph representation of an ensemble of clusterings. Parameters ---------- cluster_run : array of s...
METIS algorithm by Karypis and Kumar. Partitions the induced similarity graph passed by CSPA. Parameters ---------- hdf5_file_name : string or file handle N_clusters_max : int Returns ------- labels : array of shape (n_samples,) A vector of labels denoting the clu...
Gives cluster labels ranging from 1 to N_clusters_max for hypergraph partitioning required for HGPA. Parameters ---------- hdf5_file_name : file handle or string N_clusters_max : int w : array, optional (default = None) Returns ------- labels : array of shape (n_...
Write a graph file in a format apposite to later use by METIS or HMETIS. Parameters ---------- hdf5_file_name : file handle or string w : list or array, optional (default = None) method : int, optional (default = 0) Returns ------- file_name : string def wgraph(hdf5_...
Runs METIS or hMETIS and returns the labels found by those (hyper-)graph partitioning algorithms. Parameters ---------- N_clusters_max : int file_name : string Returns ------- labels : array of shape (n_samples,) A vector of labels denoting the cluster to ...
Writes on disk (in an HDF5 file whose handle is provided as the first argument to this function) a stack of matrices, each describing for a particular run the overlap of cluster ID's that are matching each of the cluster ID's stored in 'consensus_labels' (the vector of labels obtained by e...
Obfuscate the auth details to avoid easy snatching. It's best to use a throw away account for these alerts to avoid having your authentication put at risk by storing it locally. def obfuscate(p, action): """Obfuscate the auth details to avoid easy snatching. It's best to use a throw away account for ...
Go through and establish the defaults on the file system. The approach here was stolen from the CLI tool provided with the module. Idea being that the user should not always need to provide a username and password in order to run the script. If the configuration file is already present ...
Attempt to authenticate the user through a session file. This process is done to avoid having to authenticate the user every single time. It uses a session file that is saved when a valid session is captured and then reused. Because sessions can expire, we need to test the session prior...
Create a logger to be used between processes. :returns: Logging instance. def _logger(self): """Create a logger to be used between processes. :returns: Logging instance. """ logger = logging.getLogger(self.NAME) logger.setLevel(self.LOG_LEVEL) shandler = loggin...
Override the default log level of the class def set_log_level(self, level): """Override the default log level of the class""" if level == 'info': level = logging.INFO if level == 'debug': level = logging.DEBUG if level == 'error': level = logging.ERRO...
Process the application state configuration. Google Alerts manages the account information and alert data through some custom state configuration. Not all values have been completely enumerated. def _process_state(self): """Process the application state configuration. Google A...
Authenticate the user and setup our state. def authenticate(self): """Authenticate the user and setup our state.""" valid = self._session_check() if self._is_authenticated and valid: self._log.debug("[!] User has already authenticated") return init = self._sessio...
List alerts configured for the account. def list(self, term=None): """List alerts configured for the account.""" if not self._state: raise InvalidState("State was not properly obtained from the app") self._process_state() if not self._state[1]: self._log.info("No...
Create a monitor using passed configuration. def create(self, term, options): """Create a monitor using passed configuration.""" if not self._state: raise InvalidState("State was not properly obtained from the app") options['action'] = 'CREATE' payload = self._build_payload(...
Create a monitor using passed configuration. def modify(self, monitor_id, options): """Create a monitor using passed configuration.""" if not self._state: raise InvalidState("State was not properly obtained from the app") monitors = self.list() # Get the latest set of monitors ...
Delete a monitor by ID. def delete(self, monitor_id): """Delete a monitor by ID.""" if not self._state: raise InvalidState("State was not properly obtained from the app") monitors = self.list() # Get the latest set of monitors bit = None for monitor in monitors: ...
Run the core. def main(): """Run the core.""" parser = ArgumentParser() subs = parser.add_subparsers(dest='cmd') setup_parser = subs.add_parser('setup') setup_parser.add_argument('-e', '--email', dest='email', required=True, help='Email of the Google user.', type=str) ...
Gather details from installed distributions. Print distribution name, version, location, and installed files. Installed files requires a pip generated 'installed-files.txt' in the distributions '.egg-info' directory. def search_packages_info(query): """ Gather details from installed distributions. ...
Collect data on Class-Based Views def process_view(self, request, view_func, view_args, view_kwargs): """ Collect data on Class-Based Views """ # Purge data in view method cache # Python 3's keys() method returns an iterator, so force evaluation before iterating. view_k...
Let's handle old-style response processing here, as usual. def process_response(self, request, response): """Let's handle old-style response processing here, as usual.""" # For debug only. if not settings.DEBUG: return response # Check for responses where the data can't be...
Return the job class def get_job_class(klass_str): """ Return the job class """ mod_name, klass_name = klass_str.rsplit('.', 1) try: mod = importlib.import_module(mod_name) except ImportError as e: logger.error("Error importing job module %s: '%s'", mod_name, e) return ...
Return the data for this function (using the cache if possible). This method is not intended to be overidden def get(self, *raw_args, **raw_kwargs): """ Return the data for this function (using the cache if possible). This method is not intended to be overidden """ # W...
Mark a cached item invalid and trigger an asynchronous job to refresh the cache def invalidate(self, *raw_args, **raw_kwargs): """ Mark a cached item invalid and trigger an asynchronous job to refresh the cache """ args = self.prepare_args(*raw_args) kwargs = sel...
Remove an item from the cache def delete(self, *raw_args, **raw_kwargs): """ Remove an item from the cache """ args = self.prepare_args(*raw_args) kwargs = self.prepare_kwargs(**raw_kwargs) key = self.key(*args, **kwargs) item = self.cache.get(key) if ite...
Retrieve the item (tuple of value and expiry) that is actually in the cache, without causing a refresh. def raw_get(self, *raw_args, **raw_kwargs): """ Retrieve the item (tuple of value and expiry) that is actually in the cache, without causing a refresh. """ args = sel...
Manually set the cache value with its appropriate expiry. def set(self, *raw_args, **raw_kwargs): """ Manually set the cache value with its appropriate expiry. """ if self.set_data_kwarg in raw_kwargs: data = raw_kwargs.pop(self.set_data_kwarg) else: raw_...
Add a result to the cache :key: Cache key to use :expiry: The expiry timestamp after which the result is stale :data: The data to cache def store(self, key, expiry, data): """ Add a result to the cache :key: Cache key to use :expiry: The expiry timestamp after ...
Fetch the result SYNCHRONOUSLY and populate the cache def refresh(self, *args, **kwargs): """ Fetch the result SYNCHRONOUSLY and populate the cache """ result = self.fetch(*args, **kwargs) self.store(self.key(*args, **kwargs), self.expiry(*args, **kwargs), result) return...
Trigger an asynchronous job to refresh the cache def async_refresh(self, *args, **kwargs): """ Trigger an asynchronous job to refresh the cache """ # We trigger the task with the class path to import as well as the # (a) args and kwargs for instantiating the class # (b) ...
Return whether to refresh an item synchronously when it is found in the cache but stale def should_stale_item_be_fetched_synchronously(self, delta, *args, **kwargs): """ Return whether to refresh an item synchronously when it is found in the cache but stale """ if self.f...
Return the cache key to use. If you're passing anything but primitive types to the ``get`` method, it's likely that you'll need to override this method. def key(self, *args, **kwargs): """ Return the cache key to use. If you're passing anything but primitive types to the ``get...
Generate a hash of the given iterable. This is for use in a cache key. def hash(self, value): """ Generate a hash of the given iterable. This is for use in a cache key. """ if is_iterable(value): value = tuple(to_bytestring(v) for v in value) return...
Re-populate cache using the given job class. The job class is instantiated with the passed constructor args and the refresh method is called with the passed call args. That is:: data = klass(*obj_args, **obj_kwargs).refresh( *call_args, **call_kwargs) :klass_str: ...
Decorate function to cache its return value. :lifetime: How long to cache items for :fetch_on_miss: Whether to perform a synchronous fetch when no cached result is found :cache_alias: The Django cache alias to store the result into. :job_class: The class to use for running the cache...
Return the angle in radians between vectors 'v1' and 'v2'. def angle(v1, v2): """Return the angle in radians between vectors 'v1' and 'v2'.""" v1_u = unit_vector(v1) v2_u = unit_vector(v2) return np.arccos(np.clip(np.dot(v1_u, v2_u), -1.0, 1.0))
Keep vertices with angles higher then given minimum. def keep_high_angle(vertices, min_angle_deg): """Keep vertices with angles higher then given minimum.""" accepted = [] v = vertices v1 = v[1] - v[0] accepted.append((v[0][0], v[0][1])) for i in range(1, len(v) - 2): v2 = v[i + 1] - v[...
Set property values for Polygon. def set_contourf_properties(stroke_width, fcolor, fill_opacity, contour_levels, contourf_idx, unit): """Set property values for Polygon.""" return { "stroke": fcolor, "stroke-width": stroke_width, "stroke-opacity": 1, "fill": fcolor, "fil...
Transform matplotlib.contour to geojson. def contour_to_geojson(contour, geojson_filepath=None, min_angle_deg=None, ndigits=5, unit='', stroke_width=1, geojson_properties=None, strdump=False, serialize=True): """Transform matplotlib.contour to geojson.""" collectio...
Transform matplotlib.contourf to geojson with overlapping filled contours. def contourf_to_geojson_overlap(contourf, geojson_filepath=None, min_angle_deg=None, ndigits=5, unit='', stroke_width=1, fill_opacity=.9, geojson_properties=None, strdump=False, se...
Transform matplotlib.contourf to geojson with MultiPolygons. def contourf_to_geojson(contourf, geojson_filepath=None, min_angle_deg=None, ndigits=5, unit='', stroke_width=1, fill_opacity=.9, geojson_properties=None, strdump=False, serialize=True): """Transform matplo...
Get a qualified URL for the provider to return to upon authorization param: endpoint: Absolute path to append to the application's host def get_authorize_callback(endpoint, provider_id): """Get a qualified URL for the provider to return to upon authorization param: endpoint: Absolute path to append to th...
Remove a single connection to a provider for the specified user. def delete_connection(self, **kwargs): """Remove a single connection to a provider for the specified user.""" conn = self.find_connection(**kwargs) if not conn: return False self.delete(conn) return Tru...
Remove a single connection to a provider for the specified user. def delete_connections(self, **kwargs): """Remove a single connection to a provider for the specified user.""" rv = False for c in self.find_connections(**kwargs): self.delete(c) rv = True return rv
Starts the provider login OAuth flow def login(provider_id): """Starts the provider login OAuth flow""" provider = get_provider_or_404(provider_id) callback_url = get_authorize_callback('login', provider_id) post_login = request.form.get('next', get_post_login_redirect()) session[config_value('POST...
Starts the provider connection OAuth flow def connect(provider_id): """Starts the provider connection OAuth flow""" provider = get_provider_or_404(provider_id) callback_url = get_authorize_callback('connect', provider_id) allow_view = get_url(config_value('CONNECT_ALLOW_VIEW')) pc = request.form.ge...
Remove all connections for the authenticated user to the specified provider def remove_all_connections(provider_id): """Remove all connections for the authenticated user to the specified provider """ provider = get_provider_or_404(provider_id) ctx = dict(provider=provider.name, user=current_us...
Remove a specific connection for the authenticated user to the specified provider def remove_connection(provider_id, provider_user_id): """Remove a specific connection for the authenticated user to the specified provider """ provider = get_provider_or_404(provider_id) ctx = dict(provider=provi...
Shared method to handle the connection process :param connection_values: A dictionary containing the connection values :param provider_id: The provider ID the connection shoudl be made to def connect_handler(cv, provider): """Shared method to handle the connection process :param connection_values: A ...
Shared method to handle the signin process def login_handler(response, provider, query): """Shared method to handle the signin process""" connection = _datastore.find_connection(**query) if connection: after_this_request(_commit) token_pair = get_token_pair_from_oauth_response(provider, r...
Initialize the application with the Social extension :param app: The Flask application :param datastore: Connection datastore instance def init_app(self, app, datastore=None): """Initialize the application with the Social extension :param app: The Flask application :param data...