FLASK BASIC TUTORIAL
Flask is a lightweight WSGI (web server gateway interface), enabling developers to create web applications. This is a detailed, getting started tutorial on how to develop a CRUD application using flask.
1. Installation
Install the latest version of python in your system. Flask support python 3.5 and above, python 2.7 and PyPy.
Open your command prompt and create a virtual environment, if required. You can easily google, how to create virtual environment (optional).
I am here using anaconda command prompt.
Command - pip install flask
In my system, it was already installed, therefore, it is showing "requirement satisfied" messages. It may take some time to install if you are installing for the first time.
2. Minimal Application in Flask
1. Firstly we will import the flask
2. Then, we are requesting the flask to create a web application in app=Flask(__name__)
3. Then we will do flask routing
@app.route("/") - This will route to homepage
@app.route("/courses") - This will route to /courses page
@app.route("/<name>") - This will route to /name page
Like this, we can create multiple pages in our website
4. Then, using if __name__=="__main__":, we are asking the application to run the program.
The debug turns on the debug-mode so that we can get error (do not use in production)
port=8000, for changing the port
from flask import Flask
app = Flask(__name__)
@app.route("/")
def goedu():
return "<h1>Goeduhub Technologies</h1><br><h2>Tutorial by Aprajita</h2>"
@app.route("/courses")
def course():
return "<h1>FLASK BASIC TUTORIAL</h1>"
@app.route("/<name>")
def user(name):
return f"<h1>Hello {name}! Welcome to Goeduhub Technologies!</h1>"
# Asking the application to run the program
if __name__=="__main__":
app.run(debug=True, port=8000)
#*Note* - It will give a link. We need to press the link to go to the homepage.
|
OUTPUT
You will get a link. Click on it and this page will appear
Now, we go to /courses page
Now, we go to /<name> page. This is a user-defined page.
3. Static and Templates directories
STATIC
- The static and templates directories should be present with .py/.ipynb file, not anywhere else.
- Inside static we can have audio/video/image files.
- Copy a file inside static. Then run the home "direcory/static/file_name". We can access the files from there.
Inside static we will add one image file and try to access it by just going to "/static/<image_name>"
Like this we can access files from static directories.
TEMPLATES
- We can render html pages using return function. It will render the home.html page from templates folder.
- Store the html page as 'home.html' in the templates folder.
- Here, I have used bootstrap to make the page beautiful. I won't dive into what bootstrap is, as it is outside the scope of this tutorial.
@app.route("/about")
def about():
return render_template('about.html')
|
Here we called the 'about.html' page saved in templates folder.