Create your first app using Flask.

What is Flask?

Flask is a micro web framework written in the Python language developed by Armin Ronacher.It is designed to keep the core of the application simple and scalable.

How to install Flask? you can install the Flask by writing this simple command-

pip install flask

Now, Let's create a folder.

mkdir myproject
cd myproject

Now let's begin with our first flask backend application. Inside myproject folder, type the following code in the editor as new.py.

 from flask import  Flask
 app =Flask(__name__)

 @app.route('/name')
 def myname():
     return '<h3>My name is Anshika</h3>'

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

First import Flask and call the Flask constructor which takes the name of the current module (name) as the argument. The route() function of the Flask class is a decorator, which tells the application which URL should call the associated function. The parameter represents URL binding with the function.

After that, we create our first method which returns an HTML tag. In the main function, let's run our

Now run it as python new.py

$ python new.py

  • Serving Flask app "hello"
  • Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)

Rendering template

Create a file, myname.html in the same folder, and write the following code.

<!doctype html>
<html>
   <body>

      <h1>Hello Anshika!</h1>

   </body>
</html>

Now, replace the following code in new.py

   from flask import  Flask, render_template
   app =Flask(__name__)

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

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

Instead of returning hardcode HTML from the function, a HTML file can be rendered by the render_template() function. The above code will produce the following result:-

name.png

If there's any doubt, please let me know. You can contact me on:-

LinkedIn or Github Stay tuned for the next post until then, show some love in the comment section.😊😊