[Python] Asynchronously uploading a file to an HFS server without saving it to the device

Discussão em 'Python' iniciado por Stack, Março 14, 2025.

  1. Stack

    Stack Membro Participativo

    I'm trying to upload a file to the HFS server without saving it to the device. It works synchronously, with saving json to the device, but there are problems with asynchronous sending. I get the following error Duplicate Content-Length:\n\n bytearray(b'Content-Length: 623

    async def upload_data_HFS(import_url, username, password, data):
    """Отправка JSON-данных в виде файла на HFS-сервер"""

    timestamp = datetime.now().strftime("%d-%m-%Y-%H-%M")
    file_name = f"{timestamp}-visit.json"

    json_data = json.dumps(data, indent=4, ensure_ascii=False)

    try:
    async with aiohttp.ClientSession() as session:
    form_data = aiohttp.FormData()
    form_data.add_field(
    "file",
    io.StringIO(json_data),
    filename=file_name,
    content_type="application/json"
    )

    async with session.post(import_url, data=form_data, auth=BasicAuth(username, password)) as response:
    response_text = await response.text()
    status = response.status

    if status == 200:
    return {"status": status, "message": "Upload successful"}
    else:
    logging.error(f"Ошибка {status}: {response_text}")
    return {"status": status, "error": response_text}

    except Exception as e:
    logging.error(f"Ошибка при загрузке файла: {e}")
    return {"status": "Error", "error": str(e)}


    I tried saving the file to the device and then uploading it to the server, and it worked, but synchronously sending the file and downloading it to the device slows down the execution of the rest of the code

    Continue reading...

Compartilhe esta Página