0
0
FlaskHow-ToBeginner · 3 min read

How to Create a Flask App: Simple Steps for Beginners

To create a Flask app, first install Flask with pip install flask. Then, create a Python file with from flask import Flask, define an app using app = Flask(__name__), and add routes with @app.route(). Finally, run the app using app.run().
📐

Syntax

The basic syntax to create a Flask app includes importing Flask, creating an app instance, defining routes, and running the app.

  • from flask import Flask: Imports the Flask class.
  • app = Flask(__name__): Creates the app object.
  • @app.route('/'): Defines a URL route.
  • def function(): Defines the function to run when the route is accessed.
  • app.run(): Starts the Flask development server.
python
from flask import Flask

app = Flask(__name__)

@app.route('/')
def home():
    return 'Hello, Flask!'

if __name__ == '__main__':
    app.run()
💻

Example

This example shows a simple Flask app that displays 'Hello, Flask!' when you visit the home page.

python
from flask import Flask

app = Flask(__name__)

@app.route('/')
def home():
    return 'Hello, Flask!'

if __name__ == '__main__':
    app.run()
Output
* Running on http://127.0.0.1:5000/ (Press CTRL+C to quit) When you open http://127.0.0.1:5000/ in a browser, it shows: Hello, Flask!
⚠️

Common Pitfalls

Common mistakes when creating a Flask app include:

  • Not installing Flask before running the app.
  • Forgetting to check if __name__ == '__main__' before calling app.run(), which can cause issues when importing.
  • Using incorrect route decorators or missing the @app.route decorator.
  • Not running the app in the correct environment or port conflicts.
python
from flask import Flask

app = Flask(__name__)

# Wrong: missing route decorator
# def home():
#     return 'Hello, Flask!'

# Right way:
@app.route('/')
def home():
    return 'Hello, Flask!'

if __name__ == '__main__':
    app.run()
📊

Quick Reference

StepDescription
Install FlaskRun pip install flask in your terminal.
Import FlaskUse from flask import Flask in your Python file.
Create AppDefine app = Flask(__name__).
Define RoutesUse @app.route('/') to set URL paths.
Run AppCall app.run() inside if __name__ == '__main__'.

Key Takeaways

Install Flask using pip before creating your app.
Create the app with Flask(__name__) and define routes with @app.route decorators.
Always use if __name__ == '__main__' before running app.run() to avoid import issues.
Test your app by visiting the URL shown in the terminal after running the app.
Avoid missing route decorators or syntax errors to ensure your app works correctly.