text
stringlengths
18
773k
def _file_iter_range(fp, offset, bytes, maxread=1024*1024): ''' Yield chunks from a range in a file. No chunk is bigger than maxread.''' fp.seek(offset) while bytes > 0: part = fp.read(min(bytes, maxread)) if not part: break bytes -= len(part) yield part
def static_file(filename, root, mimetype='auto', download=False, charset='UTF-8'): """ Open a file in a safe way and return :exc:`HTTPResponse` with status code 200, 305, 403 or 404. The ``Content-Type``, ``Content-Encoding``, ``Content-Length`` and ``Last-Modified`` headers are set if possible. ...
def debug(mode=True): """ Change the debug level. There is only one debug level supported at the moment.""" global DEBUG if mode: warnings.simplefilter('default') DEBUG = bool(mode)
def parse_auth(header): """ Parse rfc2617 HTTP authentication header string (basic) and return (user,pass) tuple or None""" try: method, data = header.split(None, 1) if method.lower() == 'basic': user, pwd = touni(base64.b64decode(tob(data))).split(':',1) return user, pwd...
def parse_range_header(header, maxlen=0): ''' Yield (start, end) ranges parsed from a HTTP Range header. Skip unsatisfiable ranges. The end index is non-inclusive.''' if not header or header[:6] != 'bytes=': return ranges = [r.split('-', 1) for r in header[6:].split(',') if '-' in r] for start, ...
def auth_basic(check, realm="private", text="Access denied"): ''' Callback decorator to require HTTP auth (basic). TODO: Add route(check_auth=...) parameter. ''' def decorator(func): def wrapper(*a, **ka): user, password = request.auth or (None, None) if user is None or n...
def view(tpl_name, **defaults): ''' Decorator: renders a template for a handler. The handler can control its behavior like that: - return a dict of template vars to fill out the template - return something other than a dict and the view decorator will not process the templat...
def add(self, rule, method, target, name=None): ''' Add a new rule or replace the target for an existing rule. ''' anons = 0 # Number of anonymous wildcards found keys = [] # Names of keys pattern = '' # Regular expression pattern with named groups filters = [...
def build(self, _name, *anons, **query): ''' Build an URL by filling the wildcards in a rule. ''' builder = self.builder.get(_name) if not builder: raise RouteBuildError("No route with that name.", _name) try: for i, value in enumerate(anons): query['anon%d'%i] = value ...
def match(self, environ): ''' Return a (target, url_agrs) tuple or raise HTTPError(400/404/405). ''' verb = environ['REQUEST_METHOD'].upper() path = environ['PATH_INFO'] or '/' target = None if verb == 'HEAD': methods = ['PROXY', verb, 'GET', 'ANY'] else: ...
def get_undecorated_callback(self): ''' Return the callback. If the callback is a decorated function, try to recover the original function. ''' func = self.callback func = getattr(func, '__func__' if py3k else 'im_func', func) closure_attr = '__closure__' if py3k else 'func_c...
def get_config(self, key, default=None): ''' Lookup a config field and return its value, first checking the route.config, then route.app.config.''' for conf in (self.config, self.app.conifg): if key in conf: return conf[key] return default
def add_hook(self, name, func): ''' Attach a callback to a hook. Three hooks are currently implemented: before_request Executed once before each request. The request context is available, but no routing has happened yet. after_request Exec...
def remove_hook(self, name, func): ''' Remove a callback from a hook. ''' if name in self._hooks and func in self._hooks[name]: self._hooks[name].remove(func) return True
def trigger_hook(self, __name, *args, **kwargs): ''' Trigger a hook and return a list of results. ''' return [hook(*args, **kwargs) for hook in self._hooks[__name][:]]
def hook(self, name): """ Return a decorator that attaches a callback to a hook. See :meth:`add_hook` for details.""" def decorator(func): self.add_hook(name, func) return func return decorator
def mount(self, prefix, app, **options): ''' Mount an application (:class:`Bottle` or plain WSGI) to a specific URL prefix. Example:: root_app.mount('/admin/', admin_app) :param prefix: path prefix or `mount-point`. If it ends in a slash, that slash is m...
def merge(self, routes): ''' Merge the routes of another :class:`Bottle` application or a list of :class:`Route` objects into this application. The routes keep their 'owner', meaning that the :data:`Route.app` attribute is not changed. ''' if isinstance(routes, Bottle...
def reset(self, route=None): ''' Reset all routes (force plugins to be re-applied) and clear all caches. If an ID or route object is given, only that specific route is affected. ''' if route is None: routes = self.routes elif isinstance(route, Route): routes = [route] ...
def add_route(self, route): ''' Add a route object, but do not change the :data:`Route.app` attribute.''' self.routes.append(route) self.router.add(route.rule, route.method, route, name=route.name) if DEBUG: route.prepare()
def _cast(self, out, peek=None): """ Try to convert the parameter into something WSGI compatible and set correct HTTP headers when possible. Support: False, str, unicode, dict, HTTPResponse, HTTPError, file-like, iterable of strings and iterable of unicodes """ # Empty o...
def wsgi(self, environ, start_response): """ The bottle WSGI-interface. """ try: out = self._cast(self._handle(environ)) # rfc2616 section 4.3 if response._status_code in (100, 101, 204, 304)\ or environ['REQUEST_METHOD'] == 'HEAD': if hasa...
def forms(self): """ Form values parsed from an `url-encoded` or `multipart/form-data` encoded POST or PUT request body. The result is returned as a :class:`FormsDict`. All keys and values are strings. File uploads are stored separately in :attr:`files`. """ forms = F...
def params(self): """ A :class:`FormsDict` with the combined values of :attr:`query` and :attr:`forms`. File uploads are stored in :attr:`files`. """ params = FormsDict() for key, value in self.query.allitems(): params[key] = value for key, value in self.forms.all...
def files(self): """ File uploads parsed from `multipart/form-data` encoded POST or PUT request body. The values are instances of :class:`FileUpload`. """ files = FormsDict() for name, item in self.POST.allitems(): if isinstance(item, FileUpload): ...
def json(self): ''' If the ``Content-Type`` header is ``application/json``, this property holds the parsed content of the request body. Only requests smaller than :attr:`MEMFILE_MAX` are processed to avoid memory exhaustion. ''' ctype = self.environ.get('CONTENT_TYPE'...
def POST(self): """ The values of :attr:`forms` and :attr:`files` combined into a single :class:`FormsDict`. Values are either strings (form values) or instances of :class:`cgi.FieldStorage` (file uploads). """ post = FormsDict() # We default to application/x-www-...
def urlparts(self): ''' The :attr:`url` string as an :class:`urlparse.SplitResult` tuple. The tuple contains (scheme, host, path, query_string and fragment), but the fragment is always empty because it is not visible to the server. ''' env = self.environ http ...
def copy(self, cls=None): ''' Returns a copy of self. ''' cls = cls or BaseResponse assert issubclass(cls, BaseResponse) copy = cls() copy.status = self.status copy._headers = dict((k, v[:]) for (k, v) in self._headers.items()) if self._cookies: copy._...
def set_header(self, name, value): ''' Create a new response header, replacing any previously defined headers with the same name. ''' self._headers[_hkey(name)] = [str(value)]
def headerlist(self): ''' WSGI conform list of (header, value) tuples. ''' out = [] headers = list(self._headers.items()) if 'Content-Type' not in self._headers: headers.append(('Content-Type', [self.default_content_type])) if self._status_code in self.bad_headers: ...
def charset(self, default='UTF-8'): """ Return the charset specified in the content-type header (default: utf8). """ if 'charset=' in self.content_type: return self.content_type.split('charset=')[-1].split(';')[0].strip() return default
def set_cookie(self, name, value, secret=None, **options): ''' Create a new cookie or replace an old one. If the `secret` parameter is set, create a `Signed Cookie` (described below). :param name: the name of the cookie. :param value: the value of the cookie. :pa...
def decode(self, encoding=None): ''' Returns a copy with all keys and values de- or recoded to match :attr:`input_encoding`. Some libraries (e.g. WTForms) want a unicode dictionary. ''' copy = FormsDict() enc = copy.input_encoding = encoding or self.input_encoding ...
def getunicode(self, name, default=None, encoding=None): ''' Return the value as a unicode string, or the default. ''' try: return self._fix(self[name], encoding) except (UnicodeError, KeyError): return default
def load_config(self, filename): ''' Load values from an *.ini style config file. If the config file contains sections, their names are used as namespaces for the values within. The two special sections ``DEFAULT`` and ``bottle`` refer to the root namespace (no prefix). ...
def load_dict(self, source, namespace='', make_namespaces=False): ''' Import values from a dictionary structure. Nesting can be used to represent namespaces. >>> ConfigDict().load_dict({'name': {'space': {'key': 'value'}}}) {'name.space.key': 'value'} ''' sta...
def meta_get(self, key, metafield, default=None): ''' Return the value of a meta field for a key. ''' return self._meta.get(key, {}).get(metafield, default)
def meta_set(self, key, metafield, value): ''' Set the meta field for a key to a new value. This triggers the on-change handler for existing keys. ''' self._meta.setdefault(key, {})[metafield] = value if key in self: self[key] = self[key]
def lookup(self, name): ''' Search for a resource and return an absolute file path, or `None`. The :attr:`path` list is searched in order. The first match is returend. Symlinks are followed. The result is cached to speed up future lookups. ''' if name not in self.cac...
def open(self, name, mode='r', *args, **kwargs): ''' Find a resource and return a file object, or raise IOError. ''' fname = self.lookup(name) if not fname: raise IOError("Resource %r not found." % name) return self.opener(fname, mode=mode, *args, **kwargs)
def save(self, destination, overwrite=False, chunk_size=2**16): ''' Save file to disk or copy its content to an open file(-like) object. If *destination* is a directory, :attr:`filename` is added to the path. Existing files are not overwritten by default (IOError). :param de...
def render(self, *args, **kwargs): """ Render the template using keyword arguments as local variables. """ env = {}; stdout = [] for dictarg in args: env.update(dictarg) env.update(kwargs) self.execute(stdout, env) return ''.join(stdout)
def convert_values(args_list): """convert_value in bulk. :param args_list: list of value, source, target currency pairs :return: map of converted values """ rate_map = get_rates(map(itemgetter(1, 2), args_list)) value_map = {} for value, source, target in args_list: args = (value, ...
def convert_value(value, source_currency, target_currency): """Converts the price of a currency to another one using exchange rates :param price: the price value :param type: decimal :param source_currency: source ISO-4217 currency code :param type: str :param target_currency: target ISO-4217...
def convert(price, currency): """Shorthand function converts a price object instance of a source currency to target currency :param price: the price value :param type: decimal :param currency: target ISO-4217 currency code :param type: str :returns: converted price instance :rtype: ``...
def import_class(class_path): """imports and returns given class string. :param class_path: Class path as string :type class_path: str :returns: Class that has given path :rtype: class :Example: >>> import_class('collections.OrderedDict').__name__ 'OrderedDict' """ try: ...
def insert_many(objects, using="default"): """Insert list of Django objects in one SQL query. Objects must be of the same Django model. Note that save is not called and signals on the model are not raised. Mostly from: http://people.iola.dk/olau/python/bulkops.py """ if not objects: ret...
def update_many(objects, fields=[], using="default"): """Update list of Django objects in one SQL query, optionally only overwrite the given fields (as names, e.g. fields=["foo"]). Objects must be of the same Django model. Note that save is not called and signals on the model are not raised. Mostly...
def memoize(ttl=None): """ Cache the result of the function call with given args for until ttl (datetime.timedelta) expires. """ def decorator(obj): cache = obj.cache = {} @functools.wraps(obj) def memoizer(*args, **kwargs): now = datetime.now() key =...
def round_to_quarter(start_time, end_time): """ Return the duration between `start_time` and `end_time` :class:`datetime.time` objects, rounded to 15 minutes. """ # We don't care about the date (only about the time) but Python # can substract only datetime objects, not time ones today = datetime...
def _timesheets_callback(self, callback): """ Call a method on all the timesheets, aggregate the return values in a list and return it. """ def call(*args, **kwargs): return_values = [] for timesheet in self: attr = getattr(timesheet, call...
def load(cls, file_pattern, nb_previous_files=1, parser=None): """ Load a collection of timesheet from the given `file_pattern`. `file_pattern` is a path to a timesheet file that will be expanded with :func:`datetime.date.strftime` and the current date. `nb_previous_files` is the number of ...
def get_files(cls, file_pattern, nb_previous_files, from_date=None): """ Return an :class:`~taxi.utils.structures.OrderedSet` of file paths expanded from `filename`, with a maximum of `nb_previous_files`. See :func:`taxi.utils.file.expand_date` for more information about filename expansion. If ...
def get_new_timesheets_contents(self): """ Return the initial text to be inserted in new timesheets. """ popular_aliases = self.get_popular_aliases() template = ['# Recently used aliases:'] if popular_aliases: contents = '\n'.join(template + ['# ' + entry for...
def entries(self): """ Return the entries (as a {date: entries} dict) of all timesheets in the collection. """ entries_list = self._timesheets_callback('entries')() return reduce(lambda x, y: x + y, entries_list)
def get_popular_aliases(self, *args, **kwargs): """ Return the aggregated results of :meth:`Timesheet.get_popular_aliases`. """ aliases_count_total = defaultdict(int) aliases_counts = self._timesheets_callback('get_popular_aliases')(*args, **kwargs) for aliases_count in ...
def show(ctx, search): """ Resolves any object passed to it (aliases, projects, etc). This will resolve the following: \b - Aliases (my_alias) - Mappings (123/456) - Project ids (123) """ matches = {'aliases': [], 'mappings': [], 'projects': []} projects_db = ctx.ob...
def status(ctx, date, f, pushed): """ Shows the summary of what's going to be committed to the server. """ try: timesheet_collection = get_timesheet_collection_for_context(ctx, f) except ParseError as e: ctx.obj['view'].err(e) else: ctx.obj['view'].show_status( ...
def edit(ctx, file_to_edit, previous_file): """ Opens your timesheet file in your favourite editor. The PREVIOUS_FILE argument can be used to specify which nth previous file to edit. A value of 1 will edit the previous file, 2 will edit the second-previous file, etc. """ timesheet_collectio...
def get_reversed_aliases(self): """ Return the reversed aliases dict. Instead of being in the form {'alias': mapping}, the dict is in the form {mapping: 'alias'}. """ return dict((v, k) for k, v in six.iteritems(self.aliases))
def filter_from_mapping(self, mapping, backend=None): """ Return mappings that either exactly correspond to the given `mapping` tuple, or, if the second item of `mapping` is `None`, include mappings that only match the first item of `mapping` (useful to show all mappings for a gi...
def filter_from_alias(self, alias, backend=None): """ Return aliases that start with the given `alias`, optionally filtered by backend. """ def alias_filter(key_item): key, item = key_item return ((alias is None or alias in key) and (b...
def clean_aliases(ctx, force_yes): """ Removes aliases from your config file that point to inactive projects. """ inactive_aliases = [] for (alias, mapping) in six.iteritems(aliases_database): # Ignore local aliases if mapping.mapping is None: continue project =...
def get_plugin_info(plugin): """ Fetch information about the given package on PyPI and return it as a dict. If the package cannot be found on PyPI, :exc:`NameError` will be raised. """ url = 'https://pypi.python.org/pypi/{}/json'.format(plugin) try: resp = request.urlopen(url) excep...
def get_installed_plugins(): """ Return a dict {plugin_name: version} of installed plugins. """ return { # Strip the first five characters from the plugin name since all # plugins are expected to start with `taxi-` backend.dist.project_name[5:]: backend.dist.version for b...
def list_(ctx): """ Lists installed plugins. """ plugins = plugins_registry.get_plugins() click.echo("\n".join( ["%s (%s)" % p for p in plugins.items()] ))
def install(ctx, plugin): """ Install the given plugin. """ ensure_inside_venv(ctx) plugin_name = get_plugin_name(plugin) try: info = get_plugin_info(plugin_name) except NameError: echo_error("Plugin {} could not be found.".format(plugin)) sys.exit(1) except Valu...
def uninstall(ctx, plugin): """ Uninstall the given plugin. """ ensure_inside_venv(ctx) if plugin not in get_installed_plugins(): echo_error("Plugin {} does not seem to be installed.".format(plugin)) sys.exit(1) plugin_name = get_plugin_name(plugin) try: run_command...
def hours(self): """ Return the number of hours this entry has lasted. If the duration is a tuple with a start and an end time, the difference between the two times will be calculated. If the duration is a number, it will be returned as-is. """ if not isinstance(self.dura...
def get_start_time(self): """ Return the start time of the entry as a :class:`datetime.time` object. If the start time is `None`, the end time of the previous entry will be returned instead. If the current entry doesn't have a duration in the form of a tuple, if there's no previo...
def hash(self): """ Return a value that's used to uniquely identify an entry in a date so we can regroup all entries that share the same hash. """ return u''.join([ self.alias, self.description, str(self.ignored), str(self.flags), ...
def add_flag(self, flag): """ Add flag to the flags and memorize this attribute has changed so we can regenerate it when outputting text. """ super(Entry, self).add_flag(flag) self._changed_attrs.add('flags')
def remove_flag(self, flag): """ Remove flag to the flags and memorize this attribute has changed so we can regenerate it when outputting text. """ super(Entry, self).remove_flag(flag) self._changed_attrs.add('flags')
def add_entry(self, date, entry): """ Add the given entry to the textual representation. """ in_date = False insert_at = 0 for (lineno, line) in enumerate(self.lines): # Search for the date of the entry if isinstance(line, DateLine) and line.date ...
def delete_entries(self, entries): """ Remove the given entries from the textual representation. """ self.lines = trim([ line for line in self.lines if not isinstance(line, Entry) or line not in entries ])
def delete_date(self, date): """ Remove the date line from the textual representation. This doesn't remove any entry line. """ self.lines = [ line for line in self.lines if not isinstance(line, DateLine) or line.date != date ] self.lines =...
def add_date(self, date): """ Add the given date to the textual representation. """ self.lines = self.parser.add_date(date, self.lines)
def init_from_str(self, entries): """ Initialize the structured and textual data based on a string representing the entries. For detailed information about the format of this string, refer to the :func:`~taxi.timesheet.parser.parse_text` function. """ self.lines =...
def filter(self, date=None, regroup=False, ignored=None, pushed=None, unmapped=None, current_workday=None): """ Return the entries as a dict of {:class:`datetime.date`: :class:`~taxi.timesheet.lines.Entry`} items. `date` can either be a single :class:`datetime.date` object to filter onl...
def append(self, x): """ Append the given element to the list and synchronize the textual representation. """ super(EntriesList, self).append(x) if self.entries_collection is not None: self.entries_collection.add_entry(self.date, x)
def projects_database_update_success(self, aliases_after_update, projects_db): """ Display the results of the projects/aliases database update. We need the projects db to extract the name of the projects / activities. """ def show_aliases(...
def is_top_down(lines): """ Return `True` if dates in the given lines go in an ascending order, or `False` if they go in a descending order. If no order can be determined, return `None`. The given `lines` must be a list of lines, ie. :class:`~taxi.timesheet.lines.TextLine`, :class:`taxi.timesheet.lines....
def trim(lines): """ Remove lines at the start and at the end of the given `lines` that are :class:`~taxi.timesheet.lines.TextLine` instances and don't have any text. """ trim_top = None trim_bottom = None _lines = lines[:] for (lineno, line) in enumerate(_lines): if hasattr(lin...
def commit(ctx, f, force_yes, date): """ Commits your work to the server. The [date] option can be used either as a single date (eg. 20.01.2014), as a range (eg. 20.01.2014-22.01.2014), or as a range with one of the dates omitted (eg. -22.01.2014). """ timesheet_collection = get_timesheet_collec...
async def _request(self, path): """Make the actual request and return the parsed response.""" url = '{}{}'.format(self.base_url, path) data = None try: async with self.websession.get(url, auth=self._auth, timeout=self._timeout) as response: if response.status...
async def update(self): """Fetch the latest data from IP Webcam.""" status_data = await self._request('/status.json?show_avail=1') if status_data: self.status_data = status_data sensor_data = await self._request('/sensors.json') if sensor_data: ...
def current_settings(self): """Return dict with all config include.""" settings = {} if not self.status_data: return settings for (key, val) in self.status_data.get('curvals', {}).items(): try: val = float(val) except ValueError: ...
def available_settings(self): """Return dict of lists with all available config settings.""" available = {} if not self.status_data: return available for (key, val) in self.status_data.get('avail', {}).items(): available[key] = [] for subval in val: ...
def export_sensor(self, sensor): """Return (value, unit) from a sensor node.""" value = None unit = None try: container = self.sensor_data.get(sensor) unit = container.get('unit') data_point = container.get('data', [[0, [0.0]]]) if data_poi...
def change_setting(self, key, val): """Change a setting. Return a coroutine. """ if isinstance(val, bool): payload = 'on' if val else 'off' else: payload = val return self._request('/settings/{}?set={}'.format(key, payload))
def record(self, record=True, tag=None): """Enable/disable recording. Return a coroutine. """ path = '/startvideo?force=1' if record else '/stopvideo?force=1' if record and tag is not None: path = '/startvideo?force=1&tag={}'.format(URL(tag).raw_path) return...
def set_orientation(self, orientation='landscape'): """Set the video orientation. Return a coroutine. """ if orientation not in ALLOWED_ORIENTATIONS: _LOGGER.debug('%s is not a valid orientation', orientation) return False return self.change_setting('orie...
def set_scenemode(self, scenemode='auto'): """Set the video scene mode. Return a coroutine. """ if scenemode not in self.available_settings['scenemode']: _LOGGER.debug('%s is not a valid scenemode', scenemode) return False return self.change_setting('scen...
def get_timesheet_collection_for_context(ctx, entries_file=None): """ Return a :class:`~taxi.timesheet.TimesheetCollection` object with the current timesheet(s). Since this depends on the settings (to get the entries files path, the number of previous files, etc) this uses the settings object from the c...
def create_config_file(filename): """ Create main configuration file if it doesn't exist. """ import textwrap from six.moves.urllib import parse if not os.path.exists(filename): old_default_config_file = os.path.join(os.path.dirname(filename), ...
def date_options(func): """ Decorator to add support for `--today/--not-today`, `--from` and `--to` options to the given command. The calculated date is then passed as a parameter named `date`. """ @click.option( '--until', type=Date(), help="Only show entries until the given date." ) ...
def months_ago(date, nb_months=1): """ Return the given `date` with `nb_months` substracted from it. """ nb_years = nb_months // 12 nb_months = nb_months % 12 month_diff = date.month - nb_months if month_diff > 0: new_month = month_diff else: new_month = 12 + month_diff...
def time_ago_to_date(value): """ Parse a date and return it as ``datetime.date`` objects. Examples of valid dates: * Relative: 2 days ago, today, yesterday, 1 week ago * Absolute: 25.10.2017 """ today = datetime.date.today() if value == 'today': return today elif value ...
def list_(ctx, search_string, reverse, backend, used, inactive): """ List configured aliases. Aliases in red belong to inactive projects and trying to push entries to these aliases will probably result in an error. """ if not reverse: list_aliases(ctx, search_string, backend, used, inactive=...