Flask is a micro web framework in Python that also happens to be a boon for all crazy website developers. With Flask, you don’t need to load all libraries or worry about the server-side – it all gets done so easily.
Let’s get our hands dirty by making a very basic Flask website. But before we start, we should familiarize ourselves with how different virtual environments work in different frameworks.
A virtual environment in Python is simply a separate space or stack where you only load libraries that are required in your specific project, not any unnecessary ones.
Now, let’s get started with our very easy and basic website using Flask. I use the Pycharm editor because it’s intelligent enough to identify missing dependencies in a project.
You can download Pycharm here.
pip install flask
main.pyfile, go to the file menu in the menu bar of Pycharm, and make a new project.
Learn how to create/ set an environment in Pycharm first.
Now, make a
main.py file in your new project and write the following code:
from flask import Flask app = Flask(__name__) # default-page @app.route(“/”) def home(): return “hello world” if __name__ == “__main__”: app.run()
Or simply right click and run main.
A Localhost address, like:
http://127.0.0.1:5000/ would appear in the terminal. Click on it and your default browser gets opened.
You have now made your first simple and basic website. But, it is just the basic one that you have completed.
Let’s add some HTML pages on our website.
You must have seen that the web addresses are in the form,
/ you add is to render to specific web pages, and we are going to move from one page to another using
/, i.e., render_template.
Step 4: Make a templates folder in your project, then make an
about.html file in it.
Step 5: Write the following code in
<!DOCTYPE html> <html lang=”en”> <head> <meta charset=”UTF-8"> <title>ABOUT</title> </head> <body> <h1> <centre> Hey,this is my first site.</centre> </h1> </body> </html>
from flask import Flask,render_template app = Flask(__name__) # default-page @app.route(“/”) def home(): return “hello world” # about-page @app.route(“/about”) def about(): return render_template(“About.html”) if __name__ == “__main__”: app.run()
Now, when you run the main file, in the localhost address add
You should then be able to see your About page.
There are many more things that you can add onto your website.
You can find the code here: Github.
You can read more about Flask here.
View all Courses