text
stringlengths
81
112k
Fetch all the rows def fetchall(self): """Fetch all the rows""" self._check_executed() if self._rows is None: return () if self.rownumber: result = self._rows[self.rownumber:] else: result = self._rows self.rownumber = len(self._rows) ...
Fetch next row def fetchone(self): """Fetch next row""" self._check_executed() row = self.read_next() if row is None: return None self.rownumber += 1 return row
Fetch many def fetchmany(self, size=None): """Fetch many""" self._check_executed() if size is None: size = self.arraysize rows = [] for i in range_type(size): row = self.read_next() if row is None: break rows.appen...
Returns a DATETIME or TIMESTAMP column value as a datetime object: >>> datetime_or_None('2007-02-25 23:06:20') datetime.datetime(2007, 2, 25, 23, 6, 20) >>> datetime_or_None('2007-02-25T23:06:20') datetime.datetime(2007, 2, 25, 23, 6, 20) Illegal values are returned as None: >>> dat...
Returns a TIME column as a timedelta object: >>> timedelta_or_None('25:06:17') datetime.timedelta(1, 3977) >>> timedelta_or_None('-25:06:17') datetime.timedelta(-2, 83177) Illegal values are returned as None: >>> timedelta_or_None('random crap') is None True Note that MyS...
Returns a TIME column as a time object: >>> time_or_None('15:06:17') datetime.time(15, 6, 17) Illegal values are returned as None: >>> time_or_None('-25:06:17') is None True >>> time_or_None('random crap') is None True Note that MySQL always returns TIME columns as (+|-)H...
Returns a DATE column as a date object: >>> date_or_None('2007-02-26') datetime.date(2007, 2, 26) Illegal values are returned as None: >>> date_or_None('2007-02-31') is None True >>> date_or_None('0000-00-00') is None True def convert_date(obj): """Returns a DATE column a...
Write the given bytes or bytearray object *b* to the socket and return the number of bytes written. This can be less than len(b) if not all data could be written. If the socket is non-blocking and no bytes could be written None is returned. def write(self, b): """Write the given bytes...
Close the SocketIO object. This doesn't close the underlying socket, except if all references to it have disappeared. def close(self): """Close the SocketIO object. This doesn't close the underlying socket, except if all references to it have disappeared. """ if self.closed: ...
Read the first 'size' bytes in packet and advance cursor past them. def read(self, size): """Read the first 'size' bytes in packet and advance cursor past them.""" result = self._data[self._position:(self._position+size)] if len(result) != size: error = ('Result length not requested...
Read all remaining data in the packet. (Subsequent read() will return errors.) def read_all(self): """Read all remaining data in the packet. (Subsequent read() will return errors.) """ result = self._data[self._position:] self._position = None # ensure no subsequent r...
Advance the cursor in data buffer 'length' bytes. def advance(self, length): """Advance the cursor in data buffer 'length' bytes.""" new_position = self._position + length if new_position < 0 or new_position > len(self._data): raise Exception('Invalid advance amount (%s) for cursor....
Set the position of the data buffer cursor to 'position'. def rewind(self, position=0): """Set the position of the data buffer cursor to 'position'.""" if position < 0 or position > len(self._data): raise Exception("Invalid position to rewind cursor to: %s." % position) self._positi...
Read a 'Length Coded Binary' number from the data buffer. Length coded numbers can be anywhere from 1 to 9 bytes depending on the value of the first byte. def read_length_encoded_integer(self): """Read a 'Length Coded Binary' number from the data buffer. Length coded numbers can be an...
Parse the 'Field Descriptor' (Metadata) packet. This is compatible with MySQL 4.1+ (not compatible with MySQL 4.0). def _parse_field_descriptor(self, encoding): """Parse the 'Field Descriptor' (Metadata) packet. This is compatible with MySQL 4.1+ (not compatible with MySQL 4.0). """ ...
Provides a 7-item tuple compatible with the Python PEP249 DB Spec. def description(self): """Provides a 7-item tuple compatible with the Python PEP249 DB Spec.""" return ( self.name, self.type_code, None, # TODO: display_length; should this be self.length? ...
Send the quit message and close the socket. See `Connection.close() <https://www.python.org/dev/peps/pep-0249/#Connection.close>`_ in the specification. :raise Error: If the connection is already closed. def close(self): """ Send the quit message and close the socket. ...
Close connection without QUIT message def _force_close(self): """Close connection without QUIT message""" if self._sock: try: self._sock.close() except: # noqa pass self._sock = None self._rfile = None
Set whether or not to commit after every execute() def _send_autocommit_mode(self): """Set whether or not to commit after every execute()""" self._execute_command(COMMAND.COM_QUERY, "SET AUTOCOMMIT = %s" % self.escape(self.autocommit_mode)) self._read_ok_packet()
Escape whatever value you pass to it. Non-standard, for internal use; do not use this in your applications. def escape(self, obj, mapping=None): """Escape whatever value you pass to it. Non-standard, for internal use; do not use this in your applications. """ if isinstance(obj...
Check if the server is alive. :param reconnect: If the connection is closed, reconnect. :raise Error: If the connection is closed and reconnect=False. def ping(self, reconnect=True): """ Check if the server is alive. :param reconnect: If the connection is closed, reconnect. ...
Read an entire "mysql packet" in its entirety from the network and return a MysqlPacket type that represents the results. :raise OperationalError: If the connection to the MySQL server is lost. :raise InternalError: If the packet sequence number is wrong. def _read_packet(self, packet_type=Mys...
:raise InterfaceError: If the connection is closed. :raise ValueError: If no username was specified. def _execute_command(self, command, sql): """ :raise InterfaceError: If the connection is closed. :raise ValueError: If no username was specified. """ if not self._sock: ...
Send data packets from the local file to the server def send_data(self): """Send data packets from the local file to the server""" if not self.connection._sock: raise err.InterfaceError("(0, '')") conn = self.connection try: with open(self.filename, 'rb') as ope...
Scramble used for mysql_native_password def scramble_native_password(password, message): """Scramble used for mysql_native_password""" if not password: return b'' stage1 = sha1_new(password).digest() stage2 = sha1_new(stage1).digest() s = sha1_new() s.update(message[:SCRAMBLE_LENGTH]) ...
Encrypt password with salt and public_key. Used for sha256_password and caching_sha2_password. def sha2_rsa_encrypt(password, salt, public_key): """Encrypt password with salt and public_key. Used for sha256_password and caching_sha2_password. """ if not _have_cryptography: raise RuntimeEr...
Scramble algorithm used in cached_sha2_password fast path. XOR(SHA256(password), SHA256(SHA256(SHA256(password)), nonce)) def scramble_caching_sha2(password, nonce): # (bytes, bytes) -> bytes """Scramble algorithm used in cached_sha2_password fast path. XOR(SHA256(password), SHA256(SHA256(SHA256(pass...
Model factory for the transitive closure extension. def ClosureTable(model_class, foreign_key=None, referencing_class=None, referencing_key=None): """Model factory for the transitive closure extension.""" if referencing_class is None: referencing_class = model_class if foreign_key...
Usage: # Format string *must* be pcnalx # Second parameter to bm25 specifies the index of the column, on # the table being queries. bm25(matchinfo(document_tbl, 'pcnalx'), 1) AS rank def bm25(raw_match_info, *args): """ Usage: # Format string *must* be pcnalx #...
Full-text search using selected `term`. def search(cls, term, weights=None, with_score=False, score_alias='score', explicit_ordering=False): """Full-text search using selected `term`.""" return cls._search( term, weights, with_score, score_...
Full-text search for selected `term` using BM25 algorithm. def search_bm25(cls, term, weights=None, with_score=False, score_alias='score', explicit_ordering=False): """Full-text search for selected `term` using BM25 algorithm.""" return cls._search( term, wei...
Full-text search for selected `term` using BM25 algorithm. def search_bm25f(cls, term, weights=None, with_score=False, score_alias='score', explicit_ordering=False): """Full-text search for selected `term` using BM25 algorithm.""" return cls._search( term, w...
Full-text search for selected `term` using BM25 algorithm. def search_lucene(cls, term, weights=None, with_score=False, score_alias='score', explicit_ordering=False): """Full-text search for selected `term` using BM25 algorithm.""" return cls._search( term, ...
Simple helper function to indicate whether a search query is a valid FTS5 query. Note: this simply looks at the characters being used, and is not guaranteed to catch all problematic queries. def validate_query(query): """ Simple helper function to indicate whether a search query is a ...
Clean a query of invalid tokens. def clean_query(query, replace=chr(26)): """ Clean a query of invalid tokens. """ accum = [] any_invalid = False tokens = _quote_re.findall(query) for token in tokens: if token.startswith('"') and token.endswith('"'): ...
Full-text search using selected `term`. def search(cls, term, weights=None, with_score=False, score_alias='score', explicit_ordering=False): """Full-text search using selected `term`.""" return cls.search_bm25( FTS5Model.clean_query(term), weights, wit...
Full-text search using selected `term`. def search_bm25(cls, term, weights=None, with_score=False, score_alias='score', explicit_ordering=False): """Full-text search using selected `term`.""" if not weights: rank = SQL('rank') elif isinstance(weights, dict): ...
Close the underlying connection without returning it to the pool. def manual_close(self): """ Close the underlying connection without returning it to the pool. """ if self.is_closed(): return False # Obtain reference to the connection in-use by the calling thread. ...
Get a breakdown of top pages per interval, i.e. day url count 2014-01-01 /blog/ 11 2014-01-02 /blog/ 14 2014-01-03 /blog/ 9 def top_pages_by_time_period(self, interval='day'): """ Get a breakdown of top pages per interval, i.e. day url...
Retrieve the cookies header from all the users who visited. def cookies(self): """ Retrieve the cookies header from all the users who visited. """ return (self.get_query() .select(PageView.ip, PageView.headers['Cookie']) .where(PageView.headers['Cookie']....
Retrieve user-agents, sorted by most common to least common. def user_agents(self): """ Retrieve user-agents, sorted by most common to least common. """ return (self.get_query() .select( PageView.headers['User-Agent'], fn.Count(Pag...
Retrieve languages, sorted by most common to least common. The Accept-Languages header sometimes looks weird, i.e. "en-US,en;q=0.8,is;q=0.6,da;q=0.4" We will split on the first semi- colon. def languages(self): """ Retrieve languages, sorted by most common to least common. The ...
Get all visitors by IP and then list the pages they visited in order. def trail(self): """ Get all visitors by IP and then list the pages they visited in order. """ inner = (self.get_query() .select(PageView.ip, PageView.url) .order_by(PageView.timestam...
What domains send us the most traffic? def top_referrers(self, domain_only=True): """ What domains send us the most traffic? """ referrer = self._referrer_clause(domain_only) return (self.get_query() .select(referrer, fn.Count(PageView.id)) .group...
Add entry def add_entry(): """Add entry""" print('Enter your entry. Press ctrl+d when finished.') data = sys.stdin.read().strip() if data and raw_input('Save entry? [Yn] ') != 'n': Entry.create(content=data) print('Saved successfully.')
View previous entries def view_entries(search_query=None): """View previous entries""" query = Entry.select().order_by(Entry.timestamp.desc()) if search_query: query = query.where(Entry.content.contains(search_query)) for entry in query: timestamp = entry.timestamp.strftime('%A %B %d, ...
Generate HTML representation of the markdown-formatted blog entry, and also convert any media URLs into rich media objects such as video players or images. def html_content(self): """ Generate HTML representation of the markdown-formatted blog entry, and also convert any media U...
Convert a model instance (and any related objects) to a dictionary. :param bool recurse: Whether foreign-keys should be recursed. :param bool backrefs: Whether lists of related objects should be recursed. :param only: A list (or set) of field instances indicating which fields should be included. ...
Lightweight factory which returns a method that builds an Expression consisting of the left-hand and right-hand operands, using `op`. def _e(op, inv=False): """ Lightweight factory which returns a method that builds an Expression consisting of the left-hand and right-hand operands, usin...
Returns the intraday exchange rate for any pair of physical currency (e.g., EUR) or physical currency (e.g., USD). Keyword Arguments: from_symbol: The currency you would like to get the exchange rate for. For example: from_currency=EUR or from_currency=USD. ...
Decorator for forming the api call with the arguments of the function, it works by taking the arguments given to the function and building the url to call the api on it Keyword Arguments: func: The function to be decorated def _call_api_on_func(cls, func): """ Decorator fo...
Decorator in charge of giving the output its right format, either json or pandas Keyword Arguments: func: The function to be decorated override: Override the internal format of the call, default None def _output_format(cls, func, override=None): """ Decorator in charg...
Convert to the alpha vantage math type integer. It returns an integer correspondent to the type of math to apply to a function. It raises ValueError if an integer greater than the supported math types is given. Keyword Arguments: matype: The math type of the alpha vantage a...
Handle the return call from the api and return a data and meta_data object. It raises a ValueError on problems Keyword Arguments: url: The url of the service data_key: The key for getting the data from the jso object meta_data_key: The key for getting the meta da...
Decorator in charge of giving the output its right format, either json or pandas (replacing the % for usable floats, range 0-1.0) Keyword Arguments: func: The function to be decorated override: Override the internal format of the call, default None Returns: A...
Return the moving average convergence/divergence time series in two json objects as data and meta_data. It raises ValueError when problems arise Keyword Arguments: symbol: the symbol for the equity we want to get its data interval: time interval between two conscutive ...
Return the moving average convergence/divergence time series in two json objects as data and meta_data. It raises ValueError when problems arise Keyword Arguments: symbol: the symbol for the equity we want to get its data interval: time interval between two conscutive ...
Return the stochatic oscillator values in two json objects as data and meta_data. It raises ValueError when problems arise Keyword Arguments: symbol: the symbol for the equity we want to get its data interval: time interval between two conscutive values, ...
Return the stochatic relative strength index in two json objects as data and meta_data. It raises ValueError when problems arise Keyword Arguments: symbol: the symbol for the equity we want to get its data interval: time interval between two conscutive values, ...
Return the absolute price oscillator values in two json objects as data and meta_data. It raises ValueError when problems arise Keyword Arguments: symbol: the symbol for the equity we want to get its data interval: time interval between two conscutive values, ...
Return the bollinger bands values in two json objects as data and meta_data. It raises ValueError when problems arise Keyword Arguments: symbol: the symbol for the equity we want to get its data interval: time interval between two conscutive values, sup...
Return a three tuple of data, code, and headers def unpack(value): """Return a three tuple of data, code, and headers""" if not isinstance(value, tuple): return value, 200, {} try: data, code, headers = value return data, code, headers except ValueError: pass try: ...
Makes a Flask response with a XML encoded body def output_xml(data, code, headers=None): """Makes a Flask response with a XML encoded body""" resp = make_response(dumps({'response' :data}), code) resp.headers.extend(headers or {}) return resp
Makes a Flask response with a JSON encoded body def output_json(data, code, headers=None): """Makes a Flask response with a JSON encoded body""" settings = current_app.config.get('RESTFUL_JSON', {}) # If we're in debug mode, and the indent is not set, we set it to a # reasonable value here. Note tha...
Raise a HTTPException for the given http_status_code. Attach any keyword arguments to the exception for later processing. def abort(http_status_code, **kwargs): """Raise a HTTPException for the given http_status_code. Attach any keyword arguments to the exception for later processing. """ #noinspec...
Takes raw data (in the form of a dict, list, object) and a dict of fields to output and filters the data based on those fields. :param data: the actual object(s) from which the fields are taken from :param fields: a dict of whose keys will make up the final serialized response output ...
Initialize this class with the given :class:`flask.Flask` application or :class:`flask.Blueprint` object. :param app: the Flask application or blueprint object :type app: flask.Flask :type app: flask.Blueprint Examples:: api = Api() api.add_resource(......
This method is used to defer the construction of the final url in the case that the Api is created with a Blueprint. :param url_part: The part of the url the endpoint is registered with :param registration_prefix: The part of the url contributed by the blueprint. Generally speaking...
Perform initialization actions with the given :class:`flask.Flask` object. :param app: The flask application object :type app: flask.Flask def _init_app(self, app): """Perform initialization actions with the given :class:`flask.Flask` object. :param app: The flask appl...
Tests if an endpoint name (not path) belongs to this Api. Takes in to account the Blueprint name part of the endpoint name. :param endpoint: The name of the endpoint being checked :return: bool def owns_endpoint(self, endpoint): """Tests if an endpoint name (not path) belongs to this ...
Determine if error should be handled with FR or default Flask The goal is to return Flask error handlers for non-FR-related routes, and FR errors (with the correct media type) for FR endpoints. This method currently handles 404 and 405 errors. :return: bool def _should_use_fr_error_ha...
Encapsulating the rules for whether the request was to a Flask endpoint def _has_fr_route(self): """Encapsulating the rules for whether the request was to a Flask endpoint""" # 404's, 405's, which might not have a url_rule if self._should_use_fr_error_handler(): return True ...
This function decides whether the error occured in a flask-restful endpoint or not. If it happened in a flask-restful endpoint, our handler will be dispatched. If it happened in an unrelated view, the app's original error handler will be dispatched. In the event that the error occurred i...
Error handler for the API transforms a raised exception into a Flask response, with the appropriate HTTP status code and body. :param e: the raised Exception object :type e: Exception def handle_error(self, e): """Error handler for the API transforms a raised exception into a Flask ...
Adds a resource to the api. :param resource: the class name of your resource :type resource: :class:`Type[Resource]` :param urls: one or more url routes to match for the resource, standard flask routing rules apply. Any url variables will be passed to...
Wraps a :class:`~flask_restful.Resource` class, adding it to the api. Parameters are the same as :meth:`~flask_restful.Api.add_resource`. Example:: app = Flask(__name__) api = restful.Api(app) @api.resource('/foo') class Foo(Resource): d...
Wraps a resource (as a flask view function), for cases where the resource does not directly return a response object :param resource: The resource as a flask view function def output(self, resource): """Wraps a resource (as a flask view function), for cases where the resource does not ...
Generates a URL to the given resource. Works like :func:`flask.url_for`. def url_for(self, resource, **values): """Generates a URL to the given resource. Works like :func:`flask.url_for`.""" endpoint = resource.endpoint if self.blueprint: endpoint = '{0}.{1}'.forma...
Looks up the representation transformer for the requested media type, invoking the transformer to create a response object. This defaults to default_mediatype if no transformer is found for the requested mediatype. If default_mediatype is None, a 406 Not Acceptable response will be sent ...
Returns a list of requested mediatypes sent in the Accept header def mediatypes(self): """Returns a list of requested mediatypes sent in the Accept header""" return [h for h, q in sorted(request.accept_mimetypes, key=operator.itemgetter(1), reverse=True)]
Allows additional representation transformers to be declared for the api. Transformers are functions that must be decorated with this method, passing the mediatype the transformer represents. Three arguments are passed to the transformer: * The data to be represented in the response bod...
Pulls values off the request in the provided location :param request: The flask request object to parse arguments from def source(self, request): """Pulls values off the request in the provided location :param request: The flask request object to parse arguments from """ if isin...
Called when an error is raised while parsing. Aborts the request with a 400 status and an error message :param error: the error that was raised :param bundle_errors: do not abort when first error occurs, return a dict with the name of the argument and the error message to be ...
Parses argument value(s) from the request, converting according to the argument's type. :param request: The flask request object to parse arguments from :param bundle_errors: Do not abort when first error occurs, return a dict with the name of the argument and the error message to b...
Adds an argument to be parsed. Accepts either a single instance of Argument or arguments to be passed into :class:`Argument`'s constructor. See :class:`Argument`'s constructor for documentation on the available options. def add_argument(self, *args, **kwargs): """Adds an argum...
Parse all arguments from the provided request and return the results as a Namespace :param req: Can be used to overwrite request from Flask :param strict: if req includes args not in parser, throw 400 BadRequest exception :param http_error_code: use custom error code for `flask_restful....
Creates a copy of this RequestParser with the same set of arguments def copy(self): """ Creates a copy of this RequestParser with the same set of arguments """ parser_copy = self.__class__(self.argument_class, self.namespace_class) parser_copy.args = deepcopy(self.args) parser_copy.trim...
Replace the argument matching the given name with a new version. def replace_argument(self, name, *args, **kwargs): """ Replace the argument matching the given name with a new version. """ new_arg = self.argument_class(name, *args, **kwargs) for index, arg in enumerate(self.args[:]): ...
Remove the argument matching the given name. def remove_argument(self, name): """ Remove the argument matching the given name. """ for index, arg in enumerate(self.args[:]): if name == arg.name: del self.args[index] break return self
Helper for converting an object to a dictionary only if it is not dictionary already or an indexable object nor a simple type def to_marshallable_type(obj): """Helper for converting an object to a dictionary only if it is not dictionary already or an indexable object nor a simple type""" if obj is None...
Pulls the value for the given key from the object, applies the field's formatting and returns the result. If the key is not found in the object, returns the default value. Field classes that create values which do not require the existence of the key in the object should override this an...
Validate a URL. :param string value: The URL to validate :returns: The URL if valid. :raises: ValueError def url(value): """Validate a URL. :param string value: The URL to validate :returns: The URL if valid. :raises: ValueError """ if not url_regex.search(value): message ...
Normalize datetime intervals. Given a pair of datetime.date or datetime.datetime objects, returns a 2-tuple of tz-aware UTC datetimes spanning the same interval. For datetime.date objects, the returned interval starts at 00:00:00.0 on the first date and ends at 00:00:00.0 on the second. Naive dat...
Do some nasty try/except voodoo to get some sort of datetime object(s) out of the string. def _parse_interval(value): """Do some nasty try/except voodoo to get some sort of datetime object(s) out of the string. """ try: return sorted(aniso8601.parse_interval(value)) except ValueError: ...
Parses ISO 8601-formatted datetime intervals into tuples of datetimes. Accepts both a single date(time) or a full interval using either start/end or start/duration notation, with the following behavior: - Intervals are defined as inclusive start, exclusive end - Single datetimes are translated into th...
Restrict input type to the natural numbers (0, 1, 2, 3...) def natural(value, argument='argument'): """ Restrict input type to the natural numbers (0, 1, 2, 3...) """ value = _get_integer(value) if value < 0: error = ('Invalid {arg}: {value}. {arg} must be a non-negative ' 'integer...
Restrict input type to the positive integers (1, 2, 3...) def positive(value, argument='argument'): """ Restrict input type to the positive integers (1, 2, 3...) """ value = _get_integer(value) if value < 1: error = ('Invalid {arg}: {value}. {arg} must be a positive ' 'integer'.for...
Parse the string ``"true"`` or ``"false"`` as a boolean (case insensitive). Also accepts ``"1"`` and ``"0"`` as ``True``/``False`` (respectively). If the input is from the request JSON body, the type is already a native python boolean, and will be passed through without further parsing. def boolean(val...
Helper method for special keys. Source: http://stackoverflow.com/questions/11045814/emulate-media-key-press-on-mac def _specialKeyEvent(key, upDown): """ Helper method for special keys. Source: http://stackoverflow.com/questions/11045814/emulate-media-key-press-on-mac """ assert upDown in ('up', ...
Performs a keyboard key press without the release. This will put that key in a held down state. NOTE: For some reason, this does not seem to cause key repeats like would happen if a keyboard key was held down on a text field. Args: key (str): The key to be pressed down. The valid names are liste...