API Reference

LoginHooks

class piccolo_api.shared.auth.hooks.LoginHooks(pre_login: List[PreLoginHook] | None = None, login_success: List[LoginSuccessHook] | None = None, login_failure: List[LoginFailureHook] | None = None)[source]

Allows you to run custom logic during login. A hook can be a function or coroutine.

Here’s an example using session_login:

def check_ban_list(username: str, **kwargs):
    '''
    An example `pre_login` hook.
    '''
    if username in ('nuisance', 'pest'):
        return 'This account has been temporarily suspended'.


async def log_success(username: str, user_id: int, **kwargs):
    '''
    An example `login_success` hook.
    '''
    await my_logging_service.record(
        f'{username} just logged in'
    )


async def log_failure(username: str, **kwargs):
    '''
    An example `login_failure` hook.
    '''
    await my_logging_service.record(f'{username} could not login')
    return (
        'To reset your password go <a href="/password-reset/">here</a>.'
    )


login_endpoint = session_login(
    hooks=LoginHooks(
        pre_login=[check_ban_list],
        login_success=[log_success],
        login_failure=[log_failure],
    )
)

If any of the hooks return a string, the login process is aborted, and the login template is shown again, containing the string as a warning message. The string can contain HTML such as links, and it will be rendered correctly.

All of the example hooks above accept **kwargs - this is recommended just in case more data is passed to the hooks in future Piccolo API versions.

Parameters:
  • pre_login – A list of function and / or coroutines, which accept the username as a string.

  • login_success – A list of function and / or coroutines, which accept the username as a string, and the user ID as an integer. If a string is returned, the login process stops before a session is created.

  • login_failure – A list of function and / or coroutines, which accept the username as a string.

OrderBy

class piccolo_api.crud.endpoints.OrderBy(column: Column, ascending: bool = True)[source]

CAPTCHA

class piccolo_api.shared.auth.captcha.Captcha(form_html: str, token_field: str, validator: Callable[[str], str | None] | Callable[[str], Awaitable[str | None]])[source]

Used to create CAPTCHAs for adding bot protection to endpoints. This is a generic class for implementing your own CAPTCHA. Out of the box support is provided for hcaptcha and recaptcha_v2, so you should only need to use this class directly if doing something custom.

Parameters:
  • form_html – Any HTML which needs inserting into the form to make the CAPTCHA work.

  • validator – A callback (either an async or normal function), which is passed the CAPTCHA token, and is used to verify with the CAPTCHA provider’s API that the token is valid. To indicate that validation has failed, return a string containing an error message which will be shown to the user.

piccolo_api.shared.auth.captcha.hcaptcha(site_key: str, secret_key: str) Captcha[source]

Can be used along with Piccolo endpoints to incorporate hCaptcha.

Parameters:
  • site_key – Provided by hCaptcha.

  • secret_key – Provided by hCaptcha.

piccolo_api.shared.auth.captcha.recaptcha_v2(site_key: str, secret_key: str) Captcha[source]

Can be used along with Piccolo endpoints to incorporate reCAPTCHA.

Parameters:
  • site_key – Provided by reCAPTCHA.

  • secret_key – Provided by reCAPTCHA.

Styles

class piccolo_api.shared.auth.styles.Styles(background_color: str = '#EEF2F5', foreground_color: str = 'white', text_color: str = 'black', error_text_color: str = 'red', button_color: str = '#419EF8', button_text_color: str = 'white', link_color: str = '#419EF8', border_color: str = 'rgba(0, 0, 0, 0.2)')[source]

Used to set CSS styles in endpoints such as session_login, session_logout, and register.

Each of the values must be valid CSS.

Media

class piccolo_api.media.local.LocalMediaStorage(column: t.Union[Text, Varchar, Array], media_path: str, executor: t.Optional[Executor] = None, allowed_extensions: t.Optional[t.Sequence[str]] = ALLOWED_EXTENSIONS, allowed_characters: t.Optional[t.Sequence[str]] = ALLOWED_CHARACTERS, file_permissions: t.Optional[int] = 0o600)[source]

Stores media files on a local path. This is good for simple applications, where you’re happy with the media files being stored on a single server.

Parameters:
  • column – The Piccolo Column which the storage is for.

  • media_path – This is the local folder where the media files will be stored. It should be an absolute path. For example, '/srv/piccolo-media/poster/'.

  • executor – An executor, which file save operations are run in, to avoid blocking the event loop. If not specified, we use a sensibly configured ThreadPoolExecutor.

  • allowed_extensions – Which file extensions are allowed. If None, then all extensions are allowed (not recommended unless the users are trusted).

  • allowed_characters – Which characters are allowed in the file name. By default, it’s very strict. If set to None then all characters are allowed.

  • file_permissions – If set to a value other than None, then all uploaded files are given these file permissions.

class piccolo_api.media.s3.S3MediaStorage(column: t.Union[Text, Varchar, Array], bucket_name: str, folder_name: t.Optional[str] = None, connection_kwargs: t.Optional[t.Dict[str, t.Any]] = None, sign_urls: bool = True, signed_url_expiry: int = 3600, upload_metadata: t.Optional[t.Dict[str, t.Any]] = None, executor: t.Optional[Executor] = None, allowed_extensions: t.Optional[t.Sequence[str]] = ALLOWED_EXTENSIONS, allowed_characters: t.Optional[t.Sequence[str]] = ALLOWED_CHARACTERS)[source]

Stores media files in S3 compatible storage. This is a good option when you have lots of files to store, and don’t want them stored locally on a server. Many cloud providers provide S3 compatible storage, besides from Amazon Web Services.

Parameters:
  • column – The Piccolo Column which the storage is for.

  • bucket_name – Which S3 bucket the files are stored in.

  • folder_name – The files will be stored in this folder within the bucket. S3 buckets don’t really have folders, but if folder is 'movie_screenshots', then we store the file at 'movie_screenshots/my-file-abc-123.jpeg', to simulate it being in a folder.

  • connection_kwargs

    These kwargs are passed directly to the boto3 client. For example:

    S3MediaStorage(
        ...,
        connection_kwargs={
            'aws_access_key_id': 'abc123',
            'aws_secret_access_key': 'xyz789',
            'endpoint_url': 's3.cloudprovider.com',
            'region_name': 'uk'
        }
    )
    

  • sign_urls – Whether to sign the URLs - by default this is True, as it’s highly recommended that your store your files in a private bucket.

  • signed_url_expiry – Files are accessed via signed URLs, which are only valid for this number of seconds.

  • upload_metadata

    You can provide additional metadata to the uploaded files. To see all available options see S3Transfer.ALLOWED_UPLOAD_ARGS. Below we show examples of common use cases.

    To set the ACL:

    S3MediaStorage(
        ...,
        upload_metadata={'ACL': 'my_acl'}
    )
    

    To set the content disposition (how the file behaves when opened - is it downloaded, or shown in the browser):

    S3MediaStorage(
        ...,
        # Shows the file within the browser:
        upload_metadata={'ContentDisposition': 'inline'}
    )
    

    To attach user defined metadata to the file:

    S3MediaStorage(
        ...,
        upload_metadata={'Metadata': {'myfield': 'abc123'}}
    )
    

    To specify how long browsers should cache the file for:

    S3MediaStorage(
        ...,
        # Cache the file for 24 hours:
        upload_metadata={'CacheControl': 'max-age=86400'}
    )
    

    Note: We automatically add the ContentType field based on the file type.

  • executor – An executor, which file save operations are run in, to avoid blocking the event loop. If not specified, we use a sensibly configured ThreadPoolExecutor.

  • allowed_extensions – Which file extensions are allowed. If None, then all extensions are allowed (not recommended unless the users are trusted).

  • allowed_characters – Which characters are allowed in the file name. By default, it’s very strict. If set to None then all characters are allowed.