Flask Getting Started
The tasks project
- Flask is a micro web framework.
- You can use it to create web sites, but also to create web services, which are programs that communicate over the http protocol.
- We'll use it here to create a simple web service and api.
- In our api, we'll send and receive JSON strings to represent tasks
Installation
- Create a directory for you application, and cd into it (tasks in my example)
- Create a python virtual environment inside your new directory
- Activate your new virtual environment
1$> mkdir tasks
2$> cd tasks
3$> python3 -m venv flaskenv
4$> source flaskenv/bin/activate
5(flaskenv) $>
- Now install flask:
1pip install flask
Flask Applicaion
- Create your application file (tasks.py in my example)
- Inside it, create your application object (with the module name as init in it):
1from flask import Flask
2
3app = Flask(__name__)
- Now, register URIs, using the route method:
1all_tasks = [
2 None,
3 {'id':1, 'title':'shop', 'details':'Milk'},
4 {'id':2, 'title':'post-office', 'details':'Send Letter'},
5 {'id':3, 'title':'phone', 'details':'Call Joan'},
6 {'id':4, 'title':'kitchen', 'details':'Wash the dishes'},
7]
8@app.route("/tasks")
9def get_all_tasks():
10 return json.dumps(all_tasks)
I have created a list of dictionaries to represent my tasks.
- When I run my application, refering to /tasks should return all of the tasks.
1$ curl http://localhost:5000/tasks
2[null, {"id": 1, "title": "shop", "details": "Milk"}, {"id": 2, "title": "post-office", "details": "Send Letter"}, {"id": 3, "title": "phone", "details": "Call Joan"}, {"id": 4, "title": "kitchen", "details": "Wash the dishes"}]
3$
Running the application
- If the virtual environment is activated (in IDE or in bash), then you can just run the program itself:
1(flaskenv) $> python tasks.py
2 * Serving Flask app 'tasks'
3 * Debug mode: off
4WARNING: This is a development server. Do not use it in a production deployment. Use a production WSGI server instead.
5 * Running on http://127.0.0.1:5000
6Press CTRL+C to quit
7127.0.0.1 - - [17/Mar/2024 07:06:19] "GET /tasks HTTP/1.1" 200 -