-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.py
100 lines (79 loc) · 2.42 KB
/
app.py
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
92
93
94
95
96
97
98
99
100
import os
from flask import Flask, request, jsonify, render_template
from flask_sqlalchemy import SQLAlchemy
app = Flask(__name__)
app.config.from_object("config.ProductionConfig")
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
db = SQLAlchemy(app)
class Book(db.Model):
__tablename__ = 'books'
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String())
author = db.Column(db.String())
published = db.Column(db.String())
def __init__(self, name, author, published):
self.name = name
self.author = author
self.published = published
def __repr__(self):
return '<id {}>'.format(self.id)
def serialize(self):
return {
'id': self.id,
'name': self.name,
'author': self.author,
'published':self.published
}
@app.route("/")
def hello():
return "Hello World!"
@app.route("/add")
def add_book():
name=request.args.get('name')
author=request.args.get('author')
published=request.args.get('published')
try:
book=Book(
name=name,
author=author,
published=published
)
db.session.add(book)
db.session.commit()
return "Book added. book id={}".format(book.id)
except Exception as e:
return(str(e))
@app.route("/getall")
def get_all():
try:
books=Book.query.all()
return jsonify([e.serialize() for e in books])
except Exception as e:
return(str(e))
@app.route("/get/<id_>")
def get_by_id(id_):
try:
book=Book.query.filter_by(id=id_).first()
return jsonify(book.serialize())
except Exception as e:
return(str(e))
@app.route("/add/form",methods=['GET', 'POST'])
def add_book_form():
if request.method == 'POST':
name=request.form.get('name')
author=request.form.get('author')
published=request.form.get('published')
try:
book=Book(
name=name,
author=author,
published=published
)
db.session.add(book)
db.session.commit()
return "Book added. book id={}".format(book.id)
except Exception as e:
return(str(e))
return render_template("getdata.html")
if __name__ == '__main__':
app.run()