I am working with Flask and trying to serve a file for the user to download.
My code looks something like this:
@app.route('/downloads/<string:yt_id>')
def download_file(yt_id):
def hooks(data):
if data['status'] == 'finished':
filename = data['filename']
ydl_opts = {
'format': 'bestaudio/best',
'postprocessors': [{
'key': 'FFmpegExtractAudio',
'preferredcodec': 'mp3',
'preferredquality': '192',
}],
'progress_hooks': [hooks],
}
with youtube_dl.YoutubeDL(ydl_opts) as ydl:
ydl.download(['http://www.youtube.com/watch?v='+yt_id])
return send_from_directory(".",
filename,
as_attachment=True)
I guess the only relevant part of the above code is this:
return send_from_directory(".",
filename,
as_attachment=True)
And this is the error message that I'm getting:
NameError: global name 'send_from_directory' is not defined
I have looked at several examples of how people are using send_from_directory
and I don't see much difference with what I am doing. So any help would be greatly appreciated.
The Python "NameError: name is not defined" occurs when we try to access a variable or function that is not defined or before it is defined. To solve the error, make sure you haven't misspelled the variable's name and access it after it has been declared.
If you run it from a Python shell, then __file__ is not defined unless you import the code as a module.
NameError: global name '---' is not definedOther names are defined within the program (such as variables). If Python encounters a name that it doesn't recognize, you'll probably get this error. Some common causes of this error include: Forgetting to give a variable a value before using it in another statement.
What Is a NameError in Python? In Python, the NameError occurs when you try to use a variable, function, or module that doesn't exist or wasn't used in a valid way. Some of the common mistakes that cause this error are: Using a variable or function name that is yet to be defined.
You have to import it from flask ... It should be...
from flask import send_from_directory
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With