-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
92 lines (65 loc) · 2.24 KB
/
Copy pathapp.py
File metadata and controls
92 lines (65 loc) · 2.24 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
from flask import Flask, request, jsonify
from flask_sqlalchemy import SQLAlchemy
from flask_marshmallow import Marshmallow
import os
# after code written, in a repl -> from app import db -> db.create_all() initializes the db
app = Flask(__name__)
# @app.route('/')
# def hello():
# return 'Hello World'
basedir = os.path.abspath(os.path.dirname(__file__))
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///' + os.path.join(basedir, 'app.sqlite')
db = SQLAlchemy(app)
ma = Marshmallow(app)
class Guide(db.Model):
id = db.Column(db.Integer, primary_key=True) # primary key makes it automatically incrememnting
title = db.Column(db.String(100), unique=False)
content = db.Column(db.String(144), unique=False)
def __init__(self, title, content):
self.title = title
self.content = content
class GuideSchema(ma.Schema):
class Meta:
fields = ('title', 'content', 'id')
guide_schema = GuideSchema()
guides_schema = GuideSchema(many=True)
# endpoint to create new guide
@app.route('/guide', methods=['POST'])
def add_guide():
title = request.json['title']
content = request.json['content']
new_guide = Guide(title, content)
db.session.add(new_guide)
db.session.commit()
guide = Guide.query.get(new_guide.id)
return guide_schema.jsonify(guide)
# endpoint to query all guides
@app.route('/guides', methods=["GET"])
def get_guides():
all_guides = Guide.query.all()
result = guides_schema.dump(all_guides)
return jsonify(result)
# endpoint to query a guide
@app.route('/guide/<id>', methods=["GET"])
def get_guide(id):
guide = Guide.query.get(id)
return guide_schema.jsonify(guide)
# Endpoint for updating a guide
@app.route('/guide/<id>', methods=["PUT"])
def guid_update(id):
guide = Guide.query.get(id)
title = request.json['title']
content = request.json['content']
guide.title = title
guide.content = content
db.session.commit()
return guide_schema.jsonify(guide)
# Endpoint for deleting a guide
@app.route('/guide/<id>', methods=["DELETE"])
def guide_delete(id):
guide = Guide.query.get(id)
db.session.delete(guide)
db.session.commit()
return f'You deleted guide with id {id}'
if __name__ == '__main__':
app.run(debug = True)