Flask Web Framework – Serving Static Files and Request Objects

Published by BrighterBees on

In the last article, we have read about URL building and HTTP methods. In this article, we will discuss serving static files and request objects.

Static Files

A web application often requires a static file such as a Javascript file or a CSS file supporting the display of a web page. Usually, the webserver is configured to serve them for you, but during the development, these files are served from a static folder in your project or next to your module and it will be available at /static on the application.

A special endpoint ‘static’ is used to generate a URL for static files.

In the following example, a Javascript function defined as script.js is called OnClick event of HTML button in index.html which is rendered on the ‘/’ URL of the Flask application.

Application Structure
        - app.py
        - templates
             - index.html
        - static 
             - script.js
from flask import Flask, render_template
app = Flask(__name__)

@app.route('/')
def index():
    return render_template('index.html')

if __name__ ==  '__main__':
    app.run(debug =  True)

The HTML script of index.html is given below.

<!DOCTYPE html>
<html>
	<head>
		<title>Static Files</title>

		<script type="text/javascript" src="{{ url_for('static' , filename = 'script.js') }}"></script>

	</head>
	<body>
		<input type="button"  onclick="sayHello()" value="Click me" />
	</body>
</html>

script.js contains sayHello() function.

function sayHello() {
	alert('Hello Coder');
}

You can also link CSS file using the above method. If you have tried it then comment below.

Request Object

The data from a client’s web page is sent to the server as a global request object. In order to process the request data, it should be imported from Flask module.

Important attributes of request object are listed below –

  • Form – It is a dictionary object containing key and value pairs of form parameters and their values.
  • args – parsed contents of query string which is part of URL after the question mark (?).
  • Cookies – dictionary object holding cookies names and values
  • files – data pertaining to uploaded file
  • method – current request method

So we have learned about serving static files like JavaScript, CSS and request objects. Try it and if you have any problem then just comment below.

connect with the author on LinkedIn.

visit our website brighterbees for such interesting study stuff and more about flask.

you can also access our blog series on cloud computing.


0 Comments

Leave a Reply

Your email address will not be published. Required fields are marked *

STAY CONNECT WITH US