Skip to content

Instantly share code, notes, and snippets.

@igormcsouza
Last active November 24, 2021 22:46
Show Gist options
  • Save igormcsouza/3b16dafd17a24119ba70e03ed3b4db01 to your computer and use it in GitHub Desktop.
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.
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
@igormcsouza
Copy link
Author

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.

pip install Flask gunicorn
wget -O crud.py https://gist.githubusercontent.com/igormcsouza/3b16dafd17a24119ba70e03ed3b4db01/raw/1938686f0c7a383a6ce6c23cce0c0e3ba7f5a50c/crud.py
gunicorn crud:app --bind 0.0.0.0:8000 --reload

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment