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_userargument, andthe personal user credential token string in
web_token.the
project_nameargument 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 classCollector).skip_file_path: selector callable that accepts a file/folder path (relative to the project root) and returnsTrueto 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
|
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:
ErrorMsgMixinremote 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:
- 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:
- 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).
- _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:
- Returns:
callable receiving a string argument with the file path and returning an Iterable of tuples, to be used as the
item_collectorargument of the file/folderCollectorclass.
- _request(url_path, task, method=<function get>, success_codes=(200, 201), **request_kwargs)[source]
send a https request specified via the
methodargument and return the response.- Parameters:
- Return type:
Response- Returns:
request response. if on error occurred then the instance string attribute
error_messagecontains 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 toerror_message, separated by two new line characters.
- 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:
- 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.
- files_iterator(path_mask, level_index=0)[source]
find files matching the path mask string passed as the
path_maskargument.- 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 functionfnmatch.fnmatchcase()).level_index¶ (
int) – folder level depth inpassed file path maskto start searching (only specified in recursive call).
- Return type:
- 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.
- Return type:
- 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