Sorry if I'm not getting something right, I am new to web application development, I've been working on a project with Django and I wish I could do the following:
When the user clicks on a button an Ajax request is generated (I am using plain Javascript).
const csrftoken = document.querySelector('[name=csrfmiddlewaretoken]').value;
// Create new request add token
const generateRequest = new XMLHttpRequest();
generateRequest.open('POST', '/generate');
generateRequest.setRequestHeader('X-CSRFToken', csrftoken);
generateRequest.onload = () => {
// Get url with the midi file, see below
};
// Add the motif to send with the request
const data = new FormData();
data.append('motif', JSON.stringify(notes));
// Send request
This request sends some notes to the server (Django) that generates a melody.
# Generate the melody based on the seed
@require_http_methods(["POST"])
def generate(request):
# See if method was post
if request.method == "POST":
# Get the seed and other stuff...
# Create a melody generator
mg = MelodyGenerator()
melody = mg.generate_melody(encoded_seed, ...)
mg.save_melody(melody)
# Return the melody
return JsonResponse({"melody": melody}, status=200)
The server saves the melody in a midi file that I want to be a temp file
class MelodyGenerator:
# ... do some stuff
def save_melody(...):
path_dir = os.path.join(settings.MEDIA_ROOT, "temp_midis")
file_path = os.path.join(path_dir, file_name)
midi = stream.write(format, file_path)
So the user can listen the midi (html template):
<midi-player
src = "url/path/to/temporaryfile"
sound-font visualizer = "#myVisualizer">
</midi-player>
<midi-visualizer type = "staff" id = "myVisualizer"> </midi-visualizer>
I want this file to be temporary so that it does not take up space, that is, that the user can listen to the melody, have the option to download it, etc, but that when they leave the page, the file is deleted and thus does not take up more space .
How can I know the url of this file, which I want to be temporary?