# Import the Flask class from the flask library from flask import Flask # Create a Flask instance which will represent the webapp app = Flask(__name__) # Create some HTML content to be served by flask web_page_content = """ <h3 style="background-color: #e8e8e8; border-radius:5px; text-align:center;"> 'Hello, World' </h3> """ # Create the function that will serve the HTML content @app.route('/') def hello_world(): return web_page_content # Run the Flask app instance app.run()
Run the file and visit http://127.0.0.1:5000/ in your browser to see the web app.
The above example is a simple one which contains the HTML code inside the Python code. Notice the <h3> tags? That is HTML code.
Normally, for larger apps, you want to put the HTML code in a separate .html file and serve that file via Flask instead of serving the HTML string directly.
Here is how your project directory structure would look like if you choose to save the HTML inside HTML files (and you should):
app.py
/templates
index.html
The Python code would go inside app.py and it would look like below:
from flask import Flask, render_template
app = Flask(__name__)
@app.route('/')
def hello_world():
return render_template('index.html')
app.run()
And index.html would look like this:
<h3 style="background-color: #e8e8e8; border-radius:5px; text-align:center;">
'Hello, World'
</h3>
Learn Flask development and learn to build cool apps with our premium Python course on Udemy.
Subscribe to be the first to know when a new Python course is released.