Assuming you already have flask installed,
pip install flask
you should be able to import flask
import flask
More importantly you want to get specific libraries which include:
These are the most basic needed just for a normal static page that doesnt do too much
from flask import Flask
Setting up the flask app is done through setting the app do to the flask variable
app = Flask(__name__)
We will now setup a base route for the application for it to be routed through just the root directory
@app.route("/")
def homepage():
return "Hello World"
However, if we wanted something more than just a string being passed back, we will have to have some sort of html file loaded up in a "templates" folder. This folder is in the same directory as the python file running flask is in. Flask will draw from this directory for the various templates that you make.
The way you would call up an html file would be through the render template function, and this requires another import, or you could otherwise just import both libraries at the same time
from flask import Flask, render_template
from flask import render_template
Now you can create another app route for this html file. You can name all these functions whatever you want, and the route is the route itself which the user will take to access this file.
for this you will use
render_template()
In this case, index.html is stored within the templates folder in your working directory
@app.route("/htmlpage")
def htmlpageDemo():
return render_template("index.html")
Furthermore if you'd like to instead return a json type file back, you can use return python dictionaries
somepythonVar = 35
@app.route("/jsonAPI")
def me_api():
return {
"username": "User",
"age": somepythonVar
}
Now we have to actually run the app, and its done through the app.run()
function
if __name__ == "__main__":
app.run(host="127.0.0.1",port=8080, debug=True)
Technically, this is all you need to setup a basic static page. This page can be accessed through localhost:8080
and the working directories like localhost:8080/htmlpage
will call the function htmlpageDemo()
within the code, and will return the specificed html. Return json back to the user is common for apis, and now you can make your own with relative ease.
This is the funcitonality of a web application and can be used for a multitude of uses including websites and apis