Computer scienceBackendFlaskApplication Architecture

Flask and Frontend

4 minutes read

Flask allows developers to work with both backend and frontend development. When you work with Flask, you can take a peek at both parts. But, you won't find a single somewhat serious web project that relies on frontend that Flask can provide. So, let's try to answer this question: "What is Flask's role in web development?"

Flask's place in web-development

Let's talk about the true nature of the framework that is Flask. If you google it, you'll see that Flask falls into a pool of backend frameworks. There are several reasons for that:

  • First, Flask's code and features are meant to run on the server. However, frontend content is supposed to run on the browser of the person using the website.

  • It can parse requests, handle responses and data management via database integration, and store sessions.

  • With Flask, it is easy to build an API using RESTful or class-based views, implement routing, and versioning.

But simultaneously, as you covered in the templates topic earlier, you can build some HTML markdown, CSS, and even simple Javascript on top of routes. For example, create a simple app and return the render_template function call like this:

from flask import Flask, render_template
app = Flask(__name__)
 
@app.route('/')
def hello_name():
    return render_template('index.html')
 
if __name__ == '__main__':
   app.run(debug=True)

and in templates/index.html, you have:

<!doctype html>
<html>
    <body>  
        <h1>Hello world!</h1>   
    </body>
<script>
    alert("hello");
    ...
</script>
</html>

You can also pass variables of different types, use loops and conditions in them, and inherit and link to one another. For clarifications and examples, see our topic.

So, why do you need other languages and front-end frameworks, or even specialized developers, if Flask can do these basic tasks with 'render_template' and some HTML files using Jinja?

When frontend grows

Well, that's the point - these tasks are basic. This is okay if you have a project that is a Single Page Application (SPA) - a website with only one page. For example, a portfolio with links to your projects or a business card. An SPA gets all the data it needs from the backend, and there shouldn't be too much data so that it loads quickly.

With a simple Single Page Application (SPA), you won't have problems if you use templates. One page is enough. You just pass variables to the templates, and that's it. Your movie collection or to-do list is ready to use.

But Flask's full-stack-ness comes to an end when requirements for the front end become a little bit more complicated.

Imagine that your page uses a lot of data. Arrays of thousands of articles, pictures, and maybe their metadata. Megabytes of data that your page doesn't need until someone does something. Your application will need more than 1 page to display itself, there will be many more forms with data to fill in and different pages for users to view.

But, modern web pages can handle that. They can deal with complex tasks: like drawing a graph, or showing a dashboard that updates every second. You can't do these tasks only with Flask's templates. Well, you could, but it would waste a lot of time and resources. This is especially true when there are already tools that can do this. You wouldn't want to create something that already exists, right?

What do you need to communicate with frontend?

Architecture

First of all, you need to coordinate with the frontend which style of architecture you use. There are many types: GraphQL, JsonRPC, but the most popular is REST API. Let's build examples considering the last one.

CORS

For safety, web pages can only ask for resources from the same place, or URL (for example, http://localhost). This is called the same-origin policy. It's part of the CORS mechanism - Cross-Origin Resource Sharing. This sets rules on how our resources should handle data and links from other places. Changes in http/https, ports like :80 or :8000, and of course, changes in the URL or IP address, are all seen as changes in origin. This means your application won't be able to download a resource. This could be a picture in an <img> tag, CSS styles, or any request from the Flask backend application.

To allow some of the origins to be requested, you need the Access-Control-Allow-Origin header to include some trusted URLs that we plan to request.

from flask import Flask, jsonify


app = Flask(__name__)


@app.route("/", methods=["GET"])
def get_msg():
    """GET in server"""
    response = jsonify(message="Hello Hyperskill!")

    # Enable Access-Control-Allow-Origin
    response.headers.add("Access-Control-Allow-Origin", "url-of-your-host")
    return response

HTTPS

When you transfer sensitive data: authorization data, confidential, banking information, and so on, you need a secure connection. You get this by encryption of data using Transport Level Security(TLS)/Secure Sockets Layer(SSL) on top of HTTP protocol.

To use this, you can't just change "http://" to "https://" at the start of the request. You must also add a certificate and set up your hosting/server. This is usually done in the web interface or in the configuration files. It's also common to automatically change from "http://" to "https://" when someone visits any page on your website.

Conclusion

In this topic, you learned what Flask can and cannot do with frontend. You also learned when it's time to go beyond templates and Jinja.

You learned about the things to consider when working with the independent frontend side of our application: HTTPS, CORS, overall security, architecture, and naming conventions.

4 learners liked this piece of theory. 0 didn't like it. What about you?
Report a typo