Exemple #1
0
async def get_image(
        property_code: str,
        request: Request,
        background_tasks: BackgroundTasks,
        db: Session = Depends(get_db),
) -> FileResponse:
    property = dao.get_property_by_code(db, code=property_code)
    if property is None:
        raise HTTPException(status_code=404,
                            detail="Requested image does not exist")
    if not property.active:
        raise HTTPException(status_code=404,
                            detail="Requested image does not exist")

    try:
        image_resp = image_queries[property.image]
    except KeyError:
        image_resp = image_queries["other"]

    user_agent = request.headers.get("user-agent")
    referer = request.headers.get("referer")
    ip_address = request.client[0]
    if not request.cookies.get("cid"):
        cid = str(uuid.uuid4())
    else:
        cid = request.cookies.get("cid")

    response = FileResponse(static_file(image_resp["filename"]),
                            media_type=image_resp["media_type"])
    response.headers[
        "Cache-Control"] = "no-cache, no-store, must-revalidate, private"
    response.headers["Expires"] = current_http_datetime()
    response.set_cookie("cid", cid, path="/", expires=60 * 60 * 24 * 365)

    background_tasks.add_task(
        send_analytics_payload,
        ga_code=property.ga_code.code,
        property_code=property.code,
        client_id=cid,
        user_agent=user_agent,
        title=property.image,
        ip_address=ip_address,
        referer=referer,
    )

    return response