cofan Reference

class cofan.providers.base_provider.BaseProvider

basic provider class. each time a request is intended to this provider, the provider should return a response code, headers and body. it defines one method:

  • short_response(): helper method to send a response code and its description.

You should override methods that respond to http requests you want to handle. A handler for an http request with method <method> has to be handle_<method>(). E.g. handle_get() for GET requests, handle_put() for PUT requests, and so on. A default handler is handle_default() which handles any request that does not have a handler defined.

All handler methods take the same arguments and should return the same values. refer to handle_default() documentation below for arguments.

You probably want to use one of BaseProvider subclasses or inherit it in your own class.

classmethod handle_default(url, query=None, body_data=None, full_url='')

Handles all incoming requests that do not have a defined handler method. Default implementation raises NotImplementedError.

args:

  • handler (http.server.BaseHTTPRequestHandler): The object that called this method.
  • url (str): The url that was requested after removing all prefixes by other providers. Look at Patterner for information of how prefixes are stripped.
  • query (dict): Request query arguments. Defaults to empty dictionary. full_url (str): The full url that was requested without removing prefixes.
  • body_data: the request body. BaseHandler implementation supplies this argument as a dict only if the request is multipart/form-data. Otherwise, BaseHandler passes an empty dict.

returns:

  • response (http.HTTPStatus): Response code.
  • headers (dict): Response headers.
  • content (binary file-like object): The response content.
  • postproc (callable): A callable that will be called after serving the content. This callable will be called as long as this handler method succeded regardless whether sending the content to the client succeded or not. The intention of this callable is to close all files other than content in case there are open files. For example, if content is a file inside a zip file, closing content is not enough without closing the parent zip file.
handle_method(handler)

returns the handler for the incoming request based on the request method. e.g. returns self.handle_get() for GET request, self.handle_put() method for PUT request, and so on. if no handler for the request method is defined, returns self.handle_default().

static short_response(response=<HTTPStatus.OK: 200>, body=None)

Convinience method which can be used to send a status code and its description. It returns the same values as handle_get but the code is specified as a parameter and the body defaults to a description of the code.

args:

  • response (http.HTTPStatus): Response code to send. Defaults to http.HTTPStatus.OK.
  • body: The value to send in the body. It defaults to None which sends a short description of the code. If the body is not a bytes object, it is converted to a string and then encoded to utf8.

returns:

  • response (http.HTTPStatus): Response code given in the args.
  • headers (dict): Response headers dict with text/html in Content-Type header and the length of the body in Content-Length header.
  • content (binary file-like object): Description of response as a utf-8 encoded string if body arg is None. Otherwise, returns body represented as utf-8 encoded string.
  • postproc: Always a value of None.
class cofan.providers.filer.Filer(root, iconer=None, icons_prefix='__icons__/', default_format='html', tfman=None)

Lists directory contents and serves files from local file system based on the recieved url.

Allows uploading files to this directory.

For file uploads, consider using a TPChecker to prevent unauthorized uploads.

exists(url)

Returns True if the url points to an existing file or directory under self.root. Otherwise returns False.

args:

  • url (path-like object): The recieved url to check.
returns: True if url is an existing file or subdirectory in
self.root. False otherwise.
get_file_list(url)

Called by self.handle_get. Returns a dictionary containing 2 members:

  • dirs: A list of directories under the directory pointed by url.
  • files: A list of files under the directory pointed by url.

args:

  • url (path-like object): The directory url to list its content.
handle_get(handler, url, query=None, body_data=None, full_url='')

Serves files and directories. If url points to a file, the file is sent in the response. If url points to a directory, its content is sent as an html page if query[‘format’] is the string html or as a JSON file if query[‘format’] is the string json.

is_dir(url)

Returns True if the url points to an existing directory under self.root. Otherwise returns False.

args:

  • url (path-like object): The recieved url to check.
return: True if url is an existing subdirectory of self.root. False
otherwise.
is_file(url)

Returns True if the url points to an existing file under self.root. Otherwise returns False.

args:

  • url (path-like object): The recieved url to check.
returns: True if url is an existing file in self.root or one of its
subdirectories. False otherwise.
serve_dir(handler, url, query, full_url)

Overrides JFiler.serve_dir(). Sends an html file containing subdirectories and files present in the requested directory in a similar way to file browsers. Icons are taken from self.iconer.

class cofan.providers.iconer.Iconer(root=None, theme='humanity')

Same as Ziper but used to serve file icons used in Filer and Ziper. Defines methods to help other objects find icon urls for files of different types. The root of Iconer is a zip file which contains image files in its toplevel. The name of each image file should be in the form <name>.<ext> where <ext> can be any extension and <name> can be any of the following:

  • The string directory. It makes the image used as the icon for directories.
  • A file extension. It makes the image used for file of this extension.
  • General mimetype (such as audio, video, text, …). It makes the image used for this mimetype if the file extension image does not exist.
  • The string generic. It makes the image used as a fallback icon if none of the above was found.

Any file without extension in self.root is ignored.

get_icon(name)

This method is to be used in other content providers to get icons. Returns the url of an icon for name. The icon is constructed in the following way:

  • The extension is extracted from name. If name has no extension, the full value of name is taken.
  • If there is a file in self.root named as the extension of name extracted in the previous step, the url of this file is returned. For example, if name is foo.mp4, this method will look for a file named mp4.<extension> where <extension> may be any string. The extension is case insensitive so foo.mp4 will be the same as foo.MP4.
  • If there is no file found in the previous step, the mimetype is guessed and the general type is taken (such as audio, video, etc…).
  • If there is a file in self.root with the same name as the generel mimetype extracted in the previous step, the url of this file is returned. For example, if name is foo.mp4, this method will look for a file named mp4.<anything> first. If it there is no such file in self.root, the method will look for video.<anything>. <anything> may be any string.
  • If there is no file found in the previous step, this method looks for a file named generic.<anything> and the url of this file is returned.
  • If there is no file found in the previous step, an empty string is returned.
get_icons()

Used in self.__init__(). Looks at the toplevel content of self.root for any files and makes a dictionary for each file. The keys of the dictionary are file names without extensions and the values are the file names with extensions. Any files without extension are ignored. The dictionary is used to look for icons without opening the zip file.

handle_get(handler, url, query=None, full_url='')

Overrides Filer.handle_get(). Gives the same result as Filer.handle_get() but looks at the content of a zip file instead of a directory.

class cofan.providers.ip_patterner.IPPatterner

The same as Patterner but relays requests based on IP address patterns instead of url.

find_provider(addr)

Searches the pattern list for a pattern that matches the beginning of the url and returns the corresponding provider and the pattern.

handle_default(handler, *args, **kwargs)

Handles all incoming requests that do not have a defined handler method. Default implementation raises NotImplementedError.

args:

  • handler (http.server.BaseHTTPRequestHandler): The object that called this method.
  • url (str): The url that was requested after removing all prefixes by other providers. Look at Patterner for information of how prefixes are stripped.
  • query (dict): Request query arguments. Defaults to empty dictionary. full_url (str): The full url that was requested without removing prefixes.
  • body_data: the request body. BaseHandler implementation supplies this argument as a dict only if the request is multipart/form-data. Otherwise, BaseHandler passes an empty dict.

returns:

  • response (http.HTTPStatus): Response code.
  • headers (dict): Response headers.
  • content (binary file-like object): The response content.
  • postproc (callable): A callable that will be called after serving the content. This callable will be called as long as this handler method succeded regardless whether sending the content to the client succeded or not. The intention of this callable is to close all files other than content in case there are open files. For example, if content is a file inside a zip file, closing content is not enough without closing the parent zip file.
class cofan.providers.password_checker.PasswordChecker(provider, password, max_delay=60, safe_methods=('GET', 'HEAD'))

Prevents unauthorized requests by checking password. Made mainly to be used with Filer uploads. Provides basic protection and should not be considered safe in any means.

handle_default(handler, *args, **kwargs)

Handles all incoming requests that do not have a defined handler method. Default implementation raises NotImplementedError.

args:

  • handler (http.server.BaseHTTPRequestHandler): The object that called this method.
  • url (str): The url that was requested after removing all prefixes by other providers. Look at Patterner for information of how prefixes are stripped.
  • query (dict): Request query arguments. Defaults to empty dictionary. full_url (str): The full url that was requested without removing prefixes.
  • body_data: the request body. BaseHandler implementation supplies this argument as a dict only if the request is multipart/form-data. Otherwise, BaseHandler passes an empty dict.

returns:

  • response (http.HTTPStatus): Response code.
  • headers (dict): Response headers.
  • content (binary file-like object): The response content.
  • postproc (callable): A callable that will be called after serving the content. This callable will be called as long as this handler method succeded regardless whether sending the content to the client succeded or not. The intention of this callable is to close all files other than content in case there are open files. For example, if content is a file inside a zip file, closing content is not enough without closing the parent zip file.
exception cofan.providers.patterner.NoMatchFoundError
class cofan.providers.patterner.Patterner

BaseProvider subclass that relays requests to other providers based on requested url pattern. The other providers are added to the Patterner instance with the request url pattern they should get. When the Patterner gets a request, it searches for a pattern that matches the beginning of the url. When found, the Patterner calls handle_get() method of the target provider, giving it the same parameters but with the prefix stripped from the beginning of the url.

add(pattern, provider, title='')

Adds a pattern and a provider to the Patterner.

args:

  • pattern (str): A string containing the url prefix of the provider.
  • provider (BaseProvider): The provider to relay the request to.
find_provider(url)

Searches the pattern list for a pattern that matches the beginning of the url and returns the corresponding provider and the pattern.

get_patterns()

Returns the pattern strings added to the Patterner.

get_title(pattern)

Returns the pattern title.

args:

  • pattern (str): the pattern to look for its title.

returns:

The pattern title.
handle_default(handler, url, *args, **kwargs)

Handles all incoming requests that do not have a defined handler method. Default implementation raises NotImplementedError.

args:

  • handler (http.server.BaseHTTPRequestHandler): The object that called this method.
  • url (str): The url that was requested after removing all prefixes by other providers. Look at Patterner for information of how prefixes are stripped.
  • query (dict): Request query arguments. Defaults to empty dictionary. full_url (str): The full url that was requested without removing prefixes.
  • body_data: the request body. BaseHandler implementation supplies this argument as a dict only if the request is multipart/form-data. Otherwise, BaseHandler passes an empty dict.

returns:

  • response (http.HTTPStatus): Response code.
  • headers (dict): Response headers.
  • content (binary file-like object): The response content.
  • postproc (callable): A callable that will be called after serving the content. This callable will be called as long as this handler method succeded regardless whether sending the content to the client succeded or not. The intention of this callable is to close all files other than content in case there are open files. For example, if content is a file inside a zip file, closing content is not enough without closing the parent zip file.
remove(pattern)

Removes a pattern and its provider from the pattern list. If a pattern exists multiple times (which you should not do anyway), only the first occurance is removed.

args:
pattern (str): Pattern to remove.
class cofan.providers.pattern_lister.PatternLister(patterner, iconer=None, icons_prefix='__icons__/', default_format='html', exclude='__.*__', include='..*')

Similar to Filer but instead of showing content of a directory, shows the prefixes added to a Patterner. It also provides icon urls for the prefixes. See Patterner for more details of the Patterner provider.

exists(url)

overrides Filer.exists().

args:

  • url (path-like object): The recieved url to check.

returns: True if url is an empty string

get_file_list(url)

Overrides Filer.get_file_list() where the returned dict contains:

  • dirs: An empty list.
  • files: A list of patterns under self.

args:

  • url (path-like object): The directory url to list its content.
is_dir(url)

overrides Filer.is_dir(). same as self.exists().

args:

  • url (path-like object): The recieved url to check.

returns: True if url is an empty string

is_file(url='')

overrides Filer.is_file(). always returns False

args:

  • url (path-like object): The recieved url to check.

returns: False

class cofan.providers.statuser.Statuser(response=<HTTPStatus.NOT_FOUND: 404>)

A subclass of BaseProvider. This provider is very similar to BaseProvider. The only difference is that it takes the response code in its constructor and sends this response code instead of OK.

handle_default(handler, url, query=None, body_data=None, full_url='')

Handles all incoming requests that do not have a defined handler method. Default implementation raises NotImplementedError.

args:

  • handler (http.server.BaseHTTPRequestHandler): The object that called this method.
  • url (str): The url that was requested after removing all prefixes by other providers. Look at Patterner for information of how prefixes are stripped.
  • query (dict): Request query arguments. Defaults to empty dictionary. full_url (str): The full url that was requested without removing prefixes.
  • body_data: the request body. BaseHandler implementation supplies this argument as a dict only if the request is multipart/form-data. Otherwise, BaseHandler passes an empty dict.

returns:

  • response (http.HTTPStatus): Response code.
  • headers (dict): Response headers.
  • content (binary file-like object): The response content.
  • postproc (callable): A callable that will be called after serving the content. This callable will be called as long as this handler method succeded regardless whether sending the content to the client succeded or not. The intention of this callable is to close all files other than content in case there are open files. For example, if content is a file inside a zip file, closing content is not enough without closing the parent zip file.
class cofan.providers.ziper.Ziper(root, iconer=None, icons_prefix='__icons__/', default_format='html', tfman=None)

Same as Filer but serves the content of a zip file instead of a directory. The root in the constructor must be a zip file. Files served from this class are not seekable so resuming download is not possible for the content of a Ziper.

exists(url, root)

Overrides Filer.exists(). Looks at the content of the zip file instead of a directory.

get_file_list(url, parent=False, root=None)

Overrides Filer.get_file_list(). Looks at the content of the zip file instead of a directory.

handle_get(handler, url, query=None, body_data=None, full_url='')

Overrides Filer.handle_get(). Gives the same result as Filer.handle_get() but looks at the content of a zip file instead of a directory.

is_dir(url, root)

Overrides Filer.is_dir(). Looks at the content of the zip file instead of a directory.

is_file(url, root)

Overrides Filer.is_file(). Looks at the content of the zip file instead of a directory.

serve_dir(handler, url, query, full_url, root)

Overrides JFiler.serve_dir(). Sends an html file containing subdirectories and files present in the requested directory in a similar way to file browsers. Icons are taken from self.iconer.

serve_file(handler, url, query, full_url, root)

Overrides JFiler.serve_dir(). Looks at the content of the zip file instead of a directory.

This method has an additional optional argument:

root(zipfile.ZipFile) Opened self.root. It is used in self.handle_get() to avoid opening and closing self.root multiple times. Defaults to None which means self.root will be opened and a new zipfile.ZipFile instance will be created.
cofan.utils.misc.tree_patterner(path, env=None)

creates url prefixes for the directory tree under path. each prefix is handled by the provider returned from the provider.py file in the directory.

class cofan.utils.tfman.TFMan(max_files=10, timeout=300)

Temporary file manager. Used in cofan by Filer to create a temporary file for each partially uploaded file until the upload completes. Then moves the temporary file to its upload path.