Internal¶
Internal names are reserved for fontlib development use, for external use of fontlib use the API.
cli¶
The fontlib library comes with a command line. Use fontlib --help
for a
basic help. Most commands do work with a workspace. If you haven’t used
fontlib before it might be good to create one first:
fontlib workspace init
Which creates a workspace and init this workspace with some defaults registered.
common options:
-c / --config
: git://fontlib/config.ini (see Config)-w / --workspace
: place where application persists its data
fontstack options:
--builtins
: select Builtin fonts--ep-fonts
: Fonts from entry points--google
: Google Fonts
For a more detailed help to one of the sub commands type:
$ fontlib <command> --help
- class fontlib.cli.Context(cli)[source]¶
Bases:
object
Application’s context
- property CONFIG¶
Global configuration of the command line application.
Managed in the main loop by
init_main()
andinit_app()
.
- property WORKSPACE¶
Workspace of the command line application.
Managed in the main loop by
init_app()
.
- fontlib.cli.cli_README(args)[source]¶
prints README to stdout
Use
--verbose
to print URL auf http links.
- fontlib.cli.cli_SCHEMA(args)[source]¶
Turn SQLAlchemy DB Model into a graph.
!!! EXPERIMENTAL !!!
Hint
This feature is available in the develop environment. To install requirements of the develop environment use:
pip install .\[develop,test\]
You will need atleast SQLAlchemy and pydot along with graphviz for this. Graphviz-cairo is higly recommended to get tolerable image quality. Further reading:
- fontlib.cli.cli_config(args)[source]¶
Inspect configuration (working with INI files).
commands:
- show:
print configuration
- install:
install default configuration (optional ARG1: <dest-folder>)
- fontlib.cli.cli_google(args)[source]¶
tools for Google fonts
commands:
list: print out list of known font names from fonts.googleapis.com:
google --format=rst list 'Libre.*39'
add: font to FontStack:
google --format=rst add 'Libre.*39'
The second argument is a optional regular expression to filter font names by matching this expression (default: None).
- fontlib.cli.cli_parse_css(args)[source]¶
Parse
@font-face
rules from <url>.Load CSS (stylesheet) from <url> and filter
@font-face
rules. E.g. google fonts API:css-parse 'https://fonts.googleapis.com/css?family=Cute+Font|Roboto+Slab'
or built-in dejavu fonts from url:
css-parse 'file:%(BUILTINS)s/cantarell/cantarell.css' css-parse 'file:%(BUILTINS)s/dejavu/dejavu.css'
- fontlib.cli.cli_workspace(args)[source]¶
Inspect and init workspace.
commands:
show: show current workspace location
init: init workspace from init-options: –builtins, –google, –ep-fonts:
workspace init ~/.fontlib
Second argument is the destination of the workspace (default: ~/.fontlib).
To register fonts from google fonts infrastructure. Select font families from: https://fonts.google.com
To install fonts (entry points) from the python fonts project (https://pypi.org/project/fonts) you can use e.g.:
$ pip install --user \ font-amatic-sc font-caladea font-font-awesome \ font-fredoka-one font-hanken-grotesk font-intuitive \ font-source-sans-pro font-source-serif-pro
- fontlib.cli.download_progress(_url, font_name, font_format, _cache_file, down_bytes, max_bytes)[source]¶
Callback that prints download progress bar.
- fontlib.cli.init_app(args, verbose=False)[source]¶
Init the application.
init
Context.CONFIG
from arguments & INI fileinit
Context.WORKSPACE
init
log.FONTLIB_LOGGER
init DB engine configured in INI
[DEFAULT]:fontlib_db
- fontlib.cli.map_arg_to_cfg(args, cfg)[source]¶
update application’s CONFIG from command line arguments..
- fontlib.cli.MAP_ARG_TO_CFG = {'builtins': ('fontstack', 'builtin fonts'), 'epfonts': ('fontstack', 'entry points'), 'google': ('google fonts', 'fonts'), 'workspace': ('DEFAULT', 'workspace')}¶
Maps command line arguments to config section & option
config¶
Implementation of application’s configuration class Config
.
- class fontlib.config.Config(*args, **kwargs)[source]¶
Bases:
ConfigParser
Configuration object of
fontlib
- getfqnobj(section, option, *, raw=False, _vars=None, fallback=<object object>, **kwargs)[source]¶
Get python object refered by full qualiffied name (FQN) in the config string.
- getlist(section, option, *, raw=False, _vars=None, fallback=<object object>, **kwargs)[source]¶
Get a list from a comma separated config string.
- getpath(section, option, *, raw=False, _vars=None, fallback=<object object>, **kwargs)[source]¶
Get a
fspath.fspath.FSPath
object from a config string.
- property FONTSTACK¶
Dictionary from config section
[fontstack]
- property GOOGLE_FONTS¶
Dictionary from config section
[google fonts]
- property LOGGING¶
Dictionary from config section
[logging]
- fontlib.config.get_cfg()[source]¶
Returns active
GLOBAL_CONFIG
- fontlib.config.init_cfg(filenames=None, encoding='utf-8')[source]¶
Init
GLOBAL_CONFIG
.Read and parse a filename or an iterable of filenames. Files that cannot be opened are silently ignored [ref].
Return list of successfully read files.
- Parameters:
filenames – Filename or an iterable of filenames (default:
DEFAULT_INI
).encoding – The encoding parameter(default:
utf-8
).
Note
Re-initing means; replace the old value of GLOBAL_CONFIG with a new instance of class
Config
.To extend the
GLOBAL_CONFIG
useconfigparser.ConfigParser.read()
:get_cfg().read(filenames)
- fontlib.config.DEFAULT_INI = '/800GBPCIex4/share/fontlib/fontlib/config.ini'¶
Default
config.ini
- fontlib.config.GLOBAL_CONFIG = <fontlib.config.Config object>¶
Active
Config
object of the applicationThe surrounding process (or thread) sets the active
GLOBAL_CONFIG
, for details seeinit_cfg()
andget_cfg()
.Note
The GLOBAL_CONFIG has no special treatment for threading, its just a simple name auf a python modul. Never import
GLOBAL_CONFIG
in your module, always useget_cfg()
to get activeGLOBAL_CONFIG
!
css¶
CSS helper
- class fontlib.css.AtRule(css_url, *args, **kwargs)[source]¶
Bases:
CSSRule
Internal abstraction of a CSS at-rule.
- rule_type = 'at-rule'¶
String naming the type of the rule
- class fontlib.css.CSSRule(css_url, *args, **kwargs)[source]¶
Bases:
object
Base class for internal abstraction of a CSS rules.
- css_url¶
URL of the CSS (stylesheet) file
- declarations¶
Python dict with CSS declarations
- rule_name = None¶
String with the name of the rule
- rule_type = None¶
String naming the type of the rule
- class fontlib.css.FontFaceRule(css_url, *args, **kwargs)[source]¶
Bases:
AtRule
Internal abstraction of a CSS
@font-face
.- font_family()[source]¶
Return a string with the font-family name
This descriptor defines the font family name that will be used in all CSS font family name matching. It is required for the @font-face rule to be valid (CSS @font-face:font-family).
- src()[source]¶
Returns a dictionary with
src
values.This descriptor specifies the resource containing font data. It is required for the @font-face rule to be valid. Its value is a prioritized, comma-separated list of external references or locally-installed font face names (CSS @font-face:src).
- url:
As with other URLs in CSS, the URL may be relative, in which case it is resolved relative to the location of the style sheet containing the @font-face rule.
In the case of SVG fonts, the URL points to an element within a document containing SVG font definitions.
- local:
When authors would prefer to use a locally available copy of a given font and download it if it’s not, local() can be used.
The local-value in the dictionary contains a comma-separated list of local font-face names (
<font-face-name>, <font-face-name>, ...
)- format:
The format hint contains a comma-separated list of format strings that denote well-known font formats.
- unicode_range()[source]¶
Returns a comma separeted string with unicode ranges.
This descriptor defines the set of Unicode codepoints that may be supported by the font face for which it is declared. The descriptor value is a comma-delimited list of Unicode range (<urange>) values. The union of these ranges defines the set of codepoints that serves as a hint for user agents when deciding whether or not to download a font resgource for a given text run (CSS @font-face:unicode-range).
- rule_name = 'font-face'¶
String with the name of the rule
- fontlib.css.get_css_at_rules(css_url, at_class)[source]¶
Get at-rules of type
at_class
from CSScss_url
.The CSS file is read by
urllib.request.urlopen()
. If the URL points to the google fonts api, the CSS is read bygooglefont.read_google_font_css()
.Both funtions return the byte stream from the URL, which is parsed by
tinycss2.parse_stylesheet_bytes()
. The resulting CSS rules are filtered byat_class
.- Parameters:
css_url (str) – URL of the CSS (stylesheet) file
at_class (css.AtRule) – class of the at-rule
- Return type:
- Returns:
list of
at_class
objects
db¶
Implementation of application’s database.
Fontlib’s SQL Toolkit and Object Relational Mapper is based on the SQLAlchemy (SQLAlchemy-ORM)
- fontlib.db.FontLibSchema¶
alias of
Base
- class fontlib.db.TableUtilsMixIn[source]¶
Bases:
object
MixIn class for SQLAlchemy ORM classes.
usage:
class MyClass(MySchema, TableUtilsMixIn): __tablename__ = 'my_class'
- get_persistent_object(session)[source]¶
Return persistent object from DB or None if ot exists in DB
Does a session query of the self object by it’s primary keys in the DB and returns object if one exists. If primary key does not exists in the database None is returned.
- pkey_exists(session)[source]¶
Check if object with same primary keys exists in the database.
Note
inspect(myobject).identity
will not work:An object which is transient or pending does not have a mapped identity until it is flushed, even if its attributes include primary key values, [ref].
Thats why
pkey_exists()
is based on a real DB query.
- fontlib.db.fontlib_init(config)[source]¶
Init DB engine configured in config.ini
[DEFAULT]:fontlib_db
Create a DB connector to database
[DEFAULT]:fontlib_db
Create a engine with this connector in
fontlib_engine
Create a session maker in
fontlib_sessionmaker
Create DB schema by calling
sqlalchemy.schema.MetaData.create_all
Create a session class in
FontLibSession
.
Hint
The
FontLibSession
is a scoped_session, about session management (transactions) in application’s code seefontlib_scope()
.
- fontlib.db.fontlib_scope()[source]¶
Provide a (new) transactional scope for on ‘fontlib’ DB.
Creates a instance of
FontLibSession
, stores it under the global namefontlib_active_session
and yield it.Hint
For the client site use
fontlib_session()
to get current active session.A typical usage is to start (and end) the transaction in your top function / main loop while all other modules get the active session by calling
fontlib_session()
.By example; suppose you have a main script where you start the transaction scope named
session
and a module which likes to add a newFont
into the database (into the acrive session).:# ---- file: main.py ---- from fontlib import db from fontlib.config import Config import foo cfg = Config() db.init_fontlib(cfg) ... with db.fontlib_scope() as session: ... foo.add_myfont() ... all_fonts = session.query(Font) ...
Modules like the foo below are using the
fontlib_scope()
to get the session which was set by the surrounding application code (main). The foo module itself does not need to now about transaction start and transaction end, this is managed by the outer scope in main, while both are using sthe same session instance:# ---- module: foo.py ---- from fontlib.db import fontlib_session from fontlib.font import Font def add_myfont(): my_font = Font("file:///fontlib/files/dejavu/dejavu.css") fontlib_session().add(font)
- fontlib.db.fontlib_session()[source]¶
Returns current active fontlib session (see
fontlib_scope()
)
- fontlib.db.FontLibSession = None¶
Session class
The global session class is inited by
fontlib_init()
- fontlib.db.fontlib_active_session = None¶
active session of DB
fontlib
The surrounding process (or thread) sets the active session, for details see
fontlib_scope()
andfontlib_session()
- fontlib.db.fontlib_engine = None¶
Engine of DB
fontlib
.
- fontlib.db.fontlib_sessionmaker = None¶
Sessionmaker of DB
fontlib
The global session maker is inited by
fontlib_init()
event¶
Simple observer pattern implementation, where subjects are named events.
Events are managed by a global event dispatcher. The global dispatcher arranges
the events according to their name. Emitters and observers are always use the
get_event()
function to get Event
instances. Application’s
main loop has to init the global dispatcher first (init_dispatcher()
).
Emitter’s POV:
start = 1; end = 42
for i in range(start, end+1):
event.emit('foo-ticker', i, start, end)
...
Observer’s POV:
def my_observer(i, start, end):
print("foo ticker round: %s/[%s]%s" % (i, start, end))
event.add('foo-ticker', my_observer)
Hint
Most of the class Event
was copied from Marcus von Appen
(events) implementation. I really appreciate his simple approach.
– Marcus von Appen (events): https://bitbucket.org/marcusva/python-utils/src/default/utils/events.py
- class fontlib.event.AsyncProcEvent(event_name, maxprocs=None)[source]¶
Bases:
Event
Executes all callbacks in a asynchronous process pool.
Executes all connected callbacks asynchronous. Positional arguments (
*args
) and keyword arguments (**kwargs
) are passed through.It is the responsibility of the caller code to ensure that every object used maintains a consistent state. The AsyncProcEvent class will not apply any locks, synchronous state changes or anything else to the arguments being used. Consider it a fire-and-forget event handling strategy.
Ensure that the arguments to the methods of proxies are picklable. E.g. lambda is not pickable, for more informations read: What can be pickled and unpickled?
Lambda functions can be replaced by objects as functions:
class EventMsg(str): def __call__(self, *args, **kwargs): print(self) get_event('my.event').add( EventMsg('hello: the my.event has beend released.'))
- class fontlib.event.AsyncThreadEvent(event_name)[source]¶
Bases:
Event
Executes all callbacks in asynchronous threads.
Executes all connected callbacks asynchronous. Positional arguments (
*args
) and keyword arguments (**kwargs
) are passed through.It is the responsibility of the caller code to ensure that every object used maintains a consistent state. The AsyncThreadEvent class will not apply any locks, synchronous state changes or anything else to the arguments being used. Consider it a fire-and-forget event handling strategy.
- class fontlib.event.Event(event_name)[source]¶
Bases:
object
A simple event handling class, which manages callbacks to be executed.
usage
>>> my_event = Event("my.event.name") >>> def foo(*args, **kwargs): ... print("foo:: %s // %s" % (args, kwargs)) ... return 42 >>> my_event += foo >>> my_event('hello', name='world') # call the event and foo will print .. foo:: ('hello', ) // {'name': 'world'} >>> my_event -= foo # now unregister the foo handler >>> my_event('hello', name = 'world') # no more handlers / no print output >>>
- fontlib.event.add(name, callback)[source]¶
Add observer (<callback>) to event.
- Parameters:
name (str) – name of the event
func – callback function
The event is taken from the global dispatcher (see
get_event()
)
- fontlib.event.emit(name, *args, **kwargs)[source]¶
Emit event and pass through arguments to the observers.
- Parameters:
name (str) – name of the event
The event is taken from the global dispatcher (see
get_event()
)
- fontlib.event.get_event(event_name)[source]¶
Returns a named
Event
instance from global event dispatcher.The returned object is an instance from the global dispatcher. The event type is set in
init_dispatcher()
- Returns:
event instance from global dispatcher
- Return type:
Event
(synchronous)
- fontlib.event.init_dispatcher(event_cls=None)[source]¶
Init global dispatcher.
- Parameters:
event_cls –
Event factory, a
Event
(sub-)class. Functionget_event()
will return instances of this class.Event
(synchronous)
- fontlib.event.remove(name, callback)[source]¶
Remove observer (<callback>) from event.
- Parameters:
name (str) – name of the event
callback – callback function to remove
The event is taken from the global dispatcher (see
get_event()
)
font¶
Implemtation of class Font
.
- class fontlib.font.Font(origin, **kwargs)[source]¶
Bases:
Base
,TableUtilsMixIn
A font resource identified by URL (ID).
ORM of SQL table ‘font’.
A simple constructor that allows initialization from kwargs.
Sets attributes on the constructed instance using the names and values in
kwargs
.Only keys that are present as attributes of the instance’s class are allowed. These could be, for example, any mapped columns or relationships.
- classmethod from_at_rule(at_rule, css_url)[source]¶
Build Font instances from
css.AtRule
object.- Parameters:
at_rule –
@font-face
rule, object of typecss.AtRule
css_url – URL of the CSS this
@font-face
rule comes from. We need this base URL to calculate relative path names for thesrc
declarations.
- Return type:
[Font]
- Returns:
A generator of
Font
instances.
- classmethod from_entry_point(ep_name)[source]¶
Build Font instances from python entry point.
- Parameters:
ep_name – Name of the python entry point (e.g.
fonts_ttf
orfonts_woff2
)- Return type:
- Returns:
A generator of
Font
instances.
- aliases¶
A list of alias font-names (values of CSS @font-face:font-family)
- blob¶
urlcache.URLBlob
object from urlcache
- format¶
String that represents the format
- id¶
A url-safe hash of font’s resource URL, used as unique resource ID
- name¶
The font-name (value of CSS @font-face:font-family)
- origin¶
The URL from CSS @font-face:src of the font resource.
- src_formats¶
A list of format strings (CSS @font-face:src)
- unicode_range¶
A string with the value of CSS @font-face:unicode-range
- class fontlib.font.FontAlias(**kwargs)[source]¶
Bases:
Base
,TableUtilsMixIn
Object of table ‘font_alias’
A simple constructor that allows initialization from kwargs.
Sets attributes on the constructed instance using the names and values in
kwargs
.Only keys that are present as attributes of the instance’s class are allowed. These could be, for example, any mapped columns or relationships.
- alias_name¶
Alias font-name (value of CSS @font-face:font-family)
- font¶
- id¶
- class fontlib.font.FontSrcFormat(**kwargs)[source]¶
Bases:
Base
,TableUtilsMixIn
Object of table ‘font_src_format.’
A simple constructor that allows initialization from kwargs.
Sets attributes on the constructed instance using the names and values in
kwargs
.Only keys that are present as attributes of the instance’s class are allowed. These could be, for example, any mapped columns or relationships.
- font¶
- id¶
- src_format¶
Format string (CSS @font-face:src)
fontstack¶
Implementation of class FontStack
.
- class fontlib.fontstack.FontStack[source]¶
Bases:
object
A collection of
font.Font
objects- add_font(font)[source]¶
Add
font.Font
object to this stack.- Parameters:
font (.font.Font) – font instance.
- classmethod init_fontstack(config)[source]¶
Init fonstack by configuration <config>.
Register fonts from various resources into the fontlib database.
google fonts:
fonts from fonts.googleapis.com
Configuration
[google fonts]fonts
controls which font families will be registered. Select font families from https://fonts.google.com/available builtin fonts:
available entry points:
fonts_ttf
fonts_otf
fonts_woff
fonts_woff2
E.g. to include all fonts from the fonts-python project install:
$ pip install font-amatic-sc font-caladea font-font-awesome \ font-fredoka-one font-hanken-grotesk font-intuitive \ font-source-sans-pro font-source-serif-pro
- list_fonts(name=None)[source]¶
Return generator of
font.Font
objects selected byname
.- Parameters:
name – Name of the font
- load_css(css_url)[source]¶
Add
font.Font
objects from @font-face rules.- Parameters:
css_url (str) – URL of a CSS (stylesheet) file defining
@font-face
rules
FontStack.load_css
(css_url
) is released each time function is called.
- load_entry_point(ep_name)[source]¶
Add
font.Font
objects fromep_name
.- Parameters:
ep_name – String with the name of the entry point (one of:
fonts_ttf
,fonts_otf
fonts_woff
,fonts_woff2
)
FontStack.load_entry_point
(ep_name
) is released each time funcion is called.
- save_font(font, dest_file)[source]¶
Save BLOB of
font.Font
into file <dest_file>- Parameters:
font (font.Font) – font instance
dest_file (fspath.fspath.FSPath) – Filename of the destination
- fontlib.fontstack.BUILTINS = '/800GBPCIex4/share/fontlib/fontlib/files'¶
Folder where the builtin fonts are in.
googlefont¶
The fontlib.googlefont
module serves stuff to manage fonts from
fonts.google.com
- fontlib.googlefont.is_google_font_url(url)[source]¶
Test if
url
is from google font hostfonts.googleapis.com
- Parameters:
url – URL that match hostname
fonts.googleapis.com
and schemehttp://
orhttps://
- fontlib.googlefont.read_google_font_css(url, format_list=None)[source]¶
Read stylesheet’s (CSS) content from
url
- Parameters:
url (str) – URL of the google CSS that defines the @font-face rules, e.g.: https://fonts.googleapis.com/css?family=Cute+Font|Roboto+Slab
format_list (list) – A list with the formats to fetch (default:
['woff2', 'ttf', 'svg']
)
- Return type:
- Returns:
CSS loaded from URL (request.content)
- fontlib.googlefont.GOOGLE_FONTS_HOST = 'fonts.googleapis.com'¶
Hostname of the google fonts api (url)
- fontlib.googlefont.GOOGLE_FONT_FORMATS = ['woff2', 'ttf', 'svg']¶
list of font formats used from google’s font api
log¶
common logging & setup implementations
mime¶
MIME type implementations
- class fontlib.mime.FontlibMimeTypes[source]¶
Bases:
MimeTypes
A class (
mimetypes.MimeTypes
) with (only) mime types fromfontlib/mime.types
- fontlib.mime.add_types()[source]¶
Add mime types from
fontlib/mime.types
tomimetypes
# -*- coding: utf-8; mode: conf -*- # # Font type MIME types # ==================== # # - [RFC8081] IETF: https://tools.ietf.org/html/rfc8081 # - IANA: https://www.iana.org/assignments/media-types/media-types.xhtml#font # # TTF Font Type # https://tools.ietf.org/html/rfc8081#section-4.4.2 font/ttf ttf # # OpenType Layout (OTF) Font Type # https://tools.ietf.org/html/rfc8081#section-4.4.3 font/otf otf # # Collection Font Type # https://tools.ietf.org/html/rfc8081#section-4.4.4 font/collection collection # # WOFF 1.0 # https://tools.ietf.org/html/rfc8081#section-4.4.5 font/woff woff # # WOFF 2.0 # https://tools.ietf.org/html/rfc8081#section-4.4.6 font/woff2 woff2 # # Generic SFNT Font Type # https://tools.ietf.org/html/rfc8081#section-4.4.1 font/sfnt sfnt
urlcache¶
Font library
- class fontlib.urlcache.NoCache[source]¶
Bases:
URLCache
A dummy cache which never caches
- add_url(origin)[source]¶
Add URL <origin> to cache’s database.
- Parameters:
origin (str) – the URL of the origin
- Returns:
BLOB object
- Return type:
.urlcache.URLBlob
- cache_url(origin)[source]¶
Assure a localy cached copy of the URL response.
- Parameters:
origin (str) – the URL of the origin
- Returns:
BLOB object from persistent
- Return type:
.urlcache.URLBlob
- fname_by_blob(blob)[source]¶
Return file name of cached BLOB data or
None
if blob not already cached.- Parameters:
blob (.urlcache.URLBlob) – BLOB instance
- Returns:
absolute filename of the cached BLOB
- Return type:
- get_blob_obj(origin)[source]¶
Return
URLBlob
for <origin> URL orNone
if URL is unknown.- Parameters:
origin (str) – the URL of the origin
- init(config)[source]¶
Init cache from
fontlib.config.Config
object
- save_url(origin, dest_file)[source]¶
Download (un-cached) BLOB from <origin> into file <dest_file>
- Parameters:
origin (str) – URL of the origin
dest_file (fspath.fspath.FSPath) – Filename of the destination
- update_db(blob)[source]¶
Update status of
URLBlob
in the database.- Parameters:
blob – instance of class
urlcache.URLBlob
- class fontlib.urlcache.SimpleURLCache[source]¶
Bases:
URLCache
Simple URL cache
The BLOBs are stored in folder
[DEFAULT]<workspace>/urlcache
in your <workspace>. The value for <workspace> is taken from the configuration:[DEFAULT] workspace = ~/.fontlib
- fname_by_blob(blob)[source]¶
Return file name of cached BLOB data or
None
if blob not already cached.- Parameters:
blob (.urlcache.URLBlob) – BLOB instance
- Returns:
absolute filename of the cached BLOB
- Return type:
- init(config)[source]¶
Init cache from
fontlib.config.Config
object
- class fontlib.urlcache.URLBlob(origin, **kwargs)[source]¶
Bases:
Base
,TableUtilsMixIn
A simple BLOB object
A simple constructor that allows initialization from kwargs.
Sets attributes on the constructed instance using the names and values in
kwargs
.Only keys that are present as attributes of the instance’s class are allowed. These could be, for example, any mapped columns or relationships.
- STATE_CACHED = 'cached'¶
- STATE_LIST = ['remote', 'local', 'cached']¶
- STATE_LOCAL = 'local'¶
- STATE_REMOTE = 'remote'¶
- font¶
- origin¶
The origin URL
- state¶
State of the BLOB in the cache:
[w]
remote
: BLOB needs replicationlocal
: BLOB is not cached but available from common filesystemcached
: a copy of the BLOB is localy available
- class fontlib.urlcache.URLCache[source]¶
Bases:
object
Abstract key/value hash for cached BLOBs (response) from origin.
The key is origin’s URL and the value is the BLOB (response) from this URL.
- add_url(origin)[source]¶
Add URL <origin> to cache’s database.
- Parameters:
origin (str) – the URL of the origin
- Returns:
BLOB object
- Return type:
.urlcache.URLBlob
- cache_url(origin)[source]¶
Assure a localy cached copy of the URL response.
- Parameters:
origin (str) – the URL of the origin
- Returns:
BLOB object from persistent
- Return type:
.urlcache.URLBlob
- fname_by_blob(blob)[source]¶
Return file name of cached BLOB data or
None
if blob not already cached.- Parameters:
blob (.urlcache.URLBlob) – BLOB instance
- Returns:
absolute filename of the cached BLOB
- Return type:
- get_blob_obj(origin)[source]¶
Return
URLBlob
for <origin> URL orNone
if URL is unknown.- Parameters:
origin (str) – the URL of the origin
- init(config)[source]¶
Init cache from
fontlib.config.Config
object
- save_url(origin, dest_file)[source]¶
Save (possibly cached) BLOB from <origin> into file <dest_file>
- Parameters:
origin (str) – URL of the origin
dest_file – Filename of the destination
If <origin> is not already cached, it is downloaded and cached now.
- update_db(blob)[source]¶
Update status of
URLBlob
in the database.- Parameters:
blob – instance of class
urlcache.URLBlob
- CHUNKSIZE = 1048576¶
- fontlib.urlcache.download_blob(blob, cache_file, chunksize=1048576)[source]¶
Download blob.origin into cache_file.
- Parameters:
cache_file (fspath.fspath.FSPath) – local filename
blob (.urlcache.URLBlob) – URL from blob.origin
chunkize (int) – The default chunksize is 1048576 bytes.
urlcache.download.tick
(url
,font name
,font format
,local file name
,down_bytes
,max_bytes from 'headers:Content-Length' or 0
) is released, each time a chunk has been downloaded. If no more to download, max_bytes is set to -1.
utils¶
utils