Last active
November 24, 2021 22:46
-
-
Save igormcsouza/3b16dafd17a24119ba70e03ed3b4db01 to your computer and use it in GitHub Desktop.
The simplest crud application one can make with flask and an in memory storage. Is not perfect, but shows the idea on how to create it faster.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from typing import Any, Dict, List | |
from flask import Flask, jsonify, request | |
app = Flask(__name__) | |
# In Memory data storage, or a list. | |
students: List[Dict[str, Any]] = [] | |
@app.route("/students", methods=["GET", "POST"]) | |
def index(): | |
""" | |
Main student route. | |
GET -> retrieve all students. | |
POST -> create a new student, no validation is required here. | |
""" | |
if request.method == "POST": | |
students.append(request.json) # type: ignore | |
return jsonify(), 201 | |
return jsonify({"students": students}) | |
@app.route("/students/<int:id>", methods=["GET", "PUT", "DELETE"]) | |
def get_one_record(id: int): | |
""" | |
Deals with a single student. | |
GET -> receives an id (position on the array) and returns it. | |
PUT -> update the dictionary where the user is stored. | |
DELETE -> remove that particular student from the list. | |
""" | |
try: | |
student = students[id] | |
except IndexError: | |
return jsonify({"details": "Student not found"}), 404 | |
if request.method == "GET": | |
return jsonify({"student": student}) | |
if request.method == "PUT": | |
student.update(request.json) # type: ignore | |
return jsonify(), 204 | |
if request.method == "DELETE": | |
students.remove(student) | |
return jsonify(), 204 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Can I run it locally on my machine?
Sure, follow the steps below to make it stonks! By the way, the commands are for Linux, so, if you're a windows user you must adapt the widget thingy.