def create_new_link(request: HttpRequest):
    """
    Create a new link
    :param request:
    :return:
    """
    method_verify(request, "POST")
    url_id = get_kvs(conn).insert_one({
        "url": request.POST["url"],
        "data": json.loads(request.POST["data"]),
        "valid": True
    }).inserted_id
    return {"id": _convert_oid_to_key(url_id)}
def basic_information(request: HttpRequest):
    """
    Return basic information by searched link
    :param request:
    :return:
    """
    method_verify(request, "GET")
    query_result = get_kvs(conn).find_one(
        {"_id": _convert_key_to_oid(request.GET["key"])})
    assert query_result is not None, "Key not exist."
    _id = query_result.pop("_id")
    query_result["key"] = _convert_oid_to_key(_id)
    query_result["status"] = "success"
    return query_result
def delete_link(request: HttpRequest):
    """
    Dangerous! Be careful while using.
    This interface is for delete some link physically
    Try to use disable interface instead
    :param request:
    :return:
    """
    method_verify(request, "DELETE")
    delete_result = get_kvs(conn).delete_one({
        "_id":
        _convert_key_to_oid(request.POST["key"])
    }).deleted_count > 0
    if delete_result:
        return {"status": "success"}
    else:
        raise Exception("Executed successfully but didn't delete anything.")
def enable_link(request: HttpRequest):
    """
    Set a link as enable
    :param request:
    :return:
    """
    method_verify(request, "POST")
    modify_result = get_kvs(conn).update_one(
        {
            "_id": _convert_key_to_oid(request.POST["key"])
        }, {
            "$set": {
                "valid": True
            }
        }).modified_count > 0
    if modify_result:
        return {"status": "success"}
    else:
        raise Exception("Executed successfully but didn't modify anything.")
def get_redirect_page(request: HttpRequest) -> HttpResponse:
    """
    Redirect to URL by the key given, and insert log asynchronously
    :param request: The django request
    :return:
    """
    method_verify(request, "GET")
    _id = _convert_key_to_oid(request.GET["k"])
    res = get_kvs(conn).find_one({"_id": _id})
    assert res is not None, "Can't find URL in database"
    assert res["valid"], "URL is not valid"
    data = _extract_info_from_request(request)
    data["url_id"] = _id
    data["visit_time"] = datetime.now()
    if DATA_REDUNDANCY:
        data["data"] = res["data"]
        data["url"] = res["url"]
    queue_provide(data)
    url = res["url"]
    return redirect(url, permanent=False)