-
| Hello! I pivoted to using Pyscript instead of templates because of limitations with function calls in templates. I'm using a webhook trigger and expecting a form POST'd with one or more file attachments sometimes. I can see the FileField in the  @webhook_trigger(<REDACTED>, local_only=False)
async def notify_messages(payload):
    multi_uploads = False
    log.warning(payload)
    msg_body = {
        "title": f"Message from {payload['from']}",
        "message": json.dumps(f"""
Subject: {payload['subject']}
Body:
{payload['stripped-text']}
"""),
    'tags': ['balloon','mailbox'],
    'actions': [
        {
            'action': 'http',
            'label': 'Reply',
            'url': f'mailto:{payload['sender']}'
        }
    ]}
    if 'attachment-count' in payload.keys():
        file_object = payload['attachment-1']
        log.warning(type(file_object))
        msg_body['attach'], msg_body['filename'] = await get_attachment(file_object)
        if int(payload['attachment-count']) > 1:
            multi_uploads = True
    await send_ntfy(msg_body)
    if multi_uploads:
        uploads = int(payload['attachment-count'])
        for i in range(2,uploads+1):
            upload = payload[f'attachment-{i}']
            next_upload_msg = {
                "title": f"Attachment {i}/{uploads} from {payload['from']}",
                "message": f"Attaching {upload.filename} ({upload.content_type})",
                "tags": ['balloon','floppy_disk']
            }
            next_upload_msg['attach'], next_upload_msg['filename'] = await get_attachment(upload)
            await send_ntfy(next_upload_msg)
    
async def send_ntfy(msg):
    msg['topic'] = <REDACTED>
    async with aiohttp.ClientSession() as session:
        await session.post('https://ntfy.sh', json=msg)
async def get_attachment(attachment):
    attachment_string = ""
    log.warning(type(attachment))
    log.warning(dir(attachment))
    async with await aiofiles.open(attachment.file) as f:
        contents = await f.read()
        encoded_file = task.executor(b64encode, contents)
        attachment_string = f"data:{attachment.content_type};base64,{encoded_file}"
    return (attachment_string, attachment.filename )I've tried with just  | 
Beta Was this translation helpful? Give feedback.
Replies: 2 comments
-
| Solved! The error was that the 'read' mechanism is built in to FileField types.  | 
Beta Was this translation helpful? Give feedback.
-
| Thanks for posting the solution once you figured it out - very helpful for other users. | 
Beta Was this translation helpful? Give feedback.
Solved! The error was that the 'read' mechanism is built in to FileField types.
attachment.file.read()returns the full contents.