ae.pythonanywhere

PythonAnywhere Web API Client

this portion provides the class PythonanywhereApip . an instance of this class are used as a client to interact with the PythonAnywhere web server API, which gives you access on web servers like ``www.pythonanywhere.com` and eu.pythonanywhere.com, for managing and inspecting deployed project files.

initialize an API client with connection details for a specific project passed as arguments to the class constructor:

* the :paramref:`~PythonanywhereApi.web_domain` argument expects the used remote web host domain address

(e.g., eu.pythonanywhere.com).

  • the remote connection username in the web_user argument, and

  • the personal user credential token string in web_token.

  • the project_name argument gets the name of the web project package, which is also used as the sub-folder name, situated underneath of the remote user’s home directory.

the find_project_files() method of a client instance searches for files within the deployed project directory. this method is designed to overcome the PythonAnywhere API limit of 1000 files per request by recursively calling the API on subdirectories (see `API: File Storage`_). its arguments are:

* :paramref:`~PythonanywhereApi.path_mask`: the file mask including relative path to the package project root to

be searched. passing an empty string (the default) returns all files in the project root directory.

  • collector: file collector callable (see the class Collector).

  • skip_file_path: selector callable that accepts a file/folder path (relative to the project root) and returns True to exclude it from the search result. calls for folders have a /. suffix.

the find_project_files() method returns a set of file paths relative to the project root, or None if an error occurred.

usage examples

the following examples demonstrate key functionality, including how to initialize the PythonanywhereApi and list deployed files/folders, excluding common temporary directories:

from ae.paths import Collector
from ae.pythonanywhere import PythonanywhereApi

# 1. initialize the API client
WEB_DOMAIN = 'www.pythonanywhere.com'
WEB_USER = 'YourUsername'
WEB_TOKEN = 'your-secret-token'
PROJECT_NAME = 'your_django_project'
api = PythonanywhereApi(WEB_DOMAIN, WEB_USER, WEB_TOKEN, PROJECT_NAME)

# 2. declare a function to skip e.g. hidden files/folders or common cache, venv and temp files
def skip_temp_files(path: str) -> bool:
    if path.startswith(('.', '/.')):  # skips hidden files and folders
        return True
    if '__pycache__' in path or '.venv' in path:
        return True
    return False

# 3. find all project files, excluding temp directories
all_files = api.find_project_files(path_mask="**/*", skip_file_path=skip_temp_files)

if api.error_message:
    print(f"Error fetching files: {api.error_message}")
elif all_files:
    print(f"Found {len(all_files)} files:")
    print("
“.join(sorted(list(all_files))))
else:

print(“No files found or project directory is empty.”)

more useful methods

the most useful methods of the PythonanywhereAPI class are (check the source code for more):~

  • deployed_file_content(): determine the file content of a file, deployed to the web server.

  • deploy_file(): add or update a project file to the web server.

  • delete_file_or_folder(): delete a file or folder on the web server.

..hint::

PythonAnywhere File Storage API documents: `https://help.pythonanywhere.com/pages/API/`__

Hint

a similar package can be found at `https://gitlab.com/texperience/pythonanywhereapiclient`_.

Classes

PythonanywhereApi(web_domain, web_user, ...)

remote host api to a project package on the web hosts eu.pythonanywhere.com and pythonanywhere.com.

class PythonanywhereApi(web_domain, web_user, web_token, project_name)[source]

Bases: ErrorMsgMixin

remote host api to a project package on the web hosts eu.pythonanywhere.com and pythonanywhere.com.

__init__(web_domain, web_user, web_token, project_name)[source]

initialize web host api and the deployed project package name.

Parameters:
  • web_domain (str) – remote web host domain (including subdomains).

  • web_user (str) – remote connection username.

  • web_token (str) – personal user credential token string on remote host.

  • project_name (str) – name of the web project package (and of the sub-folder in the web users home directory).

property project_name: str

project main package name string property.

Getter:

return the currently connected/configured project package name of the web host server.

Setter:

set/change the currently connected/configured project name of the web host server.

_folder_items(folder_path)[source]

determine the files in the specified folder path.

Parameters:

folder_path (str) – the remote path of the folder to search in.

Return type:

Optional[list[dict[str, str]]]

Returns:

list of found files or None if an error occurred (check self.error_message for error details). each list item contains a dict with the item ‘file_path` to keep the absolute path of the found file, and a ‘type’ item with the file type (like returned by the Pythonanywhere API).

_from_json(response)[source]

convert JSON in response to python type (list/dict).

Parameters:

response (Response) – response from requests to convert into python data type.

Return type:

Union[list[dict[str, Any]], dict[str, dict[str, Any]], dict[str, str], None]

Returns:

list|dict of dictionaries|str converted from the response content or None on error.

_prepare_collector(skipper)[source]

prepare the file collector.

Parameters:

skipper (Callable[[str], bool]) – callback receiving a string argument with the file path and returning a boolean True if the file has to be excluded from the file search result.

Return type:

Callable[[str], Iterable[tuple[Optional[str], Any]]]

Returns:

callable receiving a string argument with the file path and returning an Iterable of tuples, to be used as the item_collector argument of the file/folder Collector class.

_request(url_path, task, method=<function get>, success_codes=(200, 201), **request_kwargs)[source]

send a https request specified via the method argument and return the response.

Parameters:
  • url_path (str) – sub url path to send request to.

  • task (str) – string describing the task to archive (used to compile an error message).

  • method (Callable) – requests method (get, post, push, delete, patch, …).

  • success_codes (Container) – container of response.status_code success codes.

  • request_kwargs – additional request method arguments.

Return type:

Response

Returns:

request response. if on error occurred then the instance string attribute error_message contains an error message. if the caller is not checking for errors and not resetting the error message string, then this function will accumulate further errors to error_message, separated by two new line characters.

available_consoles()[source]

determine the available consoles.

Return type:

list[dict[str, Any]]

Returns:

list of available console dictionaries or empty list if an error occurred.

console_execute(con_id, command)[source]

execute command on server console

Parameters:
  • con_id (int) – console id.

  • command (str) – command to execute.

Return type:

str

Returns:

console output.

deployed_code_files(path_masks, skip_file_path=<function PythonanywhereApi.<lambda>>)[source]

determine all deployed code files of given package name deployed to the pythonanywhere server.

Parameters:
  • path_masks (Iterable[str]) – root package paths with glob wildcards to collect deployed code files from.

  • skip_file_path (Callable[[str], bool]) – called for each found file/folder with the path_mask relative to the package root folder as argument, returning True to exclude the specified item from the returned result set. calls of a folder have a prefix of a slash character followed by a dot (“/.”) and help to minimize the number of calls against the web server api.

Return type:

Optional[set[str]]

Returns:

set of file paths of the package deployed on the web, relative to the project root or None if an error occurred.

deployed_file_content(file_path)[source]

determine the file content of a file deployed to a web server.

Parameters:

file_path (str) – path of a deployed file relative to the project root.

Return type:

Optional[bytes]

Returns:

file content as bytes or None if error occurred (check self.error_message).

deploy_file(file_path, file_content)[source]

add or update a project file to the web server.

Parameters:
  • file_path (str) – path relative to the project root of the file to be deployed (added or updated).

  • file_content (bytes) – file content to deploy/upload.

Return type:

str

Returns:

error message if update/add failed else on success an empty string.

delete_file_or_folder(file_path)[source]

delete a file or folder on the web server.

Parameters:

file_path (str) – path relative to the project root of the file to be deleted.

Return type:

str

Returns:

error message if deletion failed else on success an empty string.

files_iterator(path_mask, level_index=0)[source]

find files matching the path mask string passed as the path_mask argument.

Parameters:
  • path_mask (str) – file path pattern/mask with optional wildcards. passing an empty string will return the files of the project/package root directory, as well as passing ‘.’ or ‘*’. also absolute path masks will be relative to the project root directory. file path mask matches are case-sensitive (done with the function fnmatch.fnmatchcase()).

  • level_index (int) – folder level depth in passed file path mask to start searching (only specified in recursive call).

Return type:

Iterable[Any]

Returns:

iterator/generator yielding dicts. each dict has a file_path key containing the path string of the found file relative to the project root folder and a type key containing the string ‘directory’ or ‘file’.

find_project_files(path_mask='', skip_file_path=<function PythonanywhereApi.<lambda>>, collector=None)[source]

determine the server files matching the glob pattern provided in path_mask.

not using the files tree api endpoints/function (files/tree/?path=/home/{self.web_user}/{project_name}) because their response is limited to 1000 files (see https://help.pythonanywhere.com/pages/API#apiv0userusernamefilestreepathpath) and e.g. kairos has more than 5300 files in its package folder (mainly for django filer and the static files).

Parameters:
  • path_mask (str) – file mask including relative path to the package project root to be searched. passing an empty string (the default) returns all files in the package root directory.

  • skip_file_path (Callable[[str], bool]) – called for each found file/folder with the path_mask relative to the package root folder as argument, returning True to exclude the specified item from the returned result set. calls of a folder have a prefix of a slash character followed by a dot (“/.”) and help to minimize the number of calls against the web server api.

  • collector (Optional[Collector]) – file collector callable.

Return type:

Optional[set[str]]

Returns:

set of file paths of the package deployed on the web, relative to the project root or None if an error occurred. all files underneath a