0
0
Flaskframework~30 mins

Serving JavaScript files in Flask - Mini Project: Build & Apply

Choose your learning style9 modes available
Serving JavaScript Files in Flask
📖 Scenario: You are building a simple Flask web app that needs to serve a JavaScript file to add interactivity on the client side.Think of it like setting up a small shop where you want to display a sign (JavaScript) outside the window (web page) so visitors can see it and interact.
🎯 Goal: Create a Flask app that serves a JavaScript file correctly so the browser can load and run it.
📋 What You'll Learn
Create a Flask app instance named app
Create a route / that returns an HTML page referencing a JavaScript file
Place the JavaScript file in the correct static folder
Serve the JavaScript file using Flask's static file serving
💡 Why This Matters
🌍 Real World
Web developers often need to serve JavaScript files to add interactivity to their web pages. Flask's static folder makes this easy and organized.
💼 Career
Knowing how to serve static files like JavaScript and CSS is essential for backend developers working with Flask or similar web frameworks.
Progress0 / 4 steps
1
Create the Flask app and HTML route
Create a Flask app instance called app and add a route for / that returns a simple HTML string with a <script> tag referencing /static/script.js.
Flask
Need a hint?

Use Flask(__name__) to create the app. Use @app.route('/') to define the home page. Return an HTML string with a <script> tag linking to /static/script.js.

2
Create the JavaScript file in the static folder
Create a folder named static in your project root. Inside it, create a file named script.js with a single line: console.log('JavaScript loaded');
Flask
Need a hint?

The static folder is where Flask looks for static files like JavaScript. Create script.js inside it with the exact console.log line.

3
Run the Flask app with debug mode
Add the code to run the Flask app with debug=True when the script is executed directly.
Flask
Need a hint?

Use the standard Python check if __name__ == '__main__': and call app.run(debug=True) inside it.

4
Verify JavaScript is served correctly
Add a comment in the Python file explaining that Flask automatically serves files from the static folder at the /static/ URL path.
Flask
Need a hint?

Just add a comment line explaining how Flask serves static files from the static folder.