Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import json
- import pandas as pd
- from flask import Flask, request
- from flask_restplus import Resource, Api, fields, inputs, reqparse
- from functools import wraps
- auth = {"basic": {"type": "basic"}}
- app = Flask(__name__)
- api = Api(
- app,
- default="Books",
- title="Books Dataset",
- description="desc",
- authorizations=auth,
- security="basic"
- )
- csv = "Books.csv"
- df = None
- book_schema = api.model(
- "Book",
- {
- "Flickr_URL": fields.String,
- "Publisher": fields.String,
- "Author": fields.String,
- "Title": fields.String,
- "Date_of_Publication": fields.Integer,
- "Identifier": fields.Integer,
- "Place_of_Publication": fields.String,
- },
- )
- parser = reqparse.RequestParser()
- parser.add_argument("order", choices=[col for col in book_schema.keys()])
- parser.add_argument("ascending", type=inputs.boolean)
- def require_auth(f):
- @wraps(f)
- def decorated(*args, **kwargs):
- auth = request.authorization
- if not auth:
- api.abort(401)
- if not (auth.username == "admin" and auth.password == "admin"):
- api.abort(401)
- return f(*args, **kwargs)
- return decorated
- # API
- @api.route("/books")
- class BooksList(Resource):
- @api.response(200, "Success")
- @api.doc(description="Get a list of all books")
- @require_auth
- def get(self):
- args = parser.parse_args()
- (order, asc) = (args.get("order"), args.get("ascending", True))
- if order:
- df.sort_value(by=order, inplace=True, ascending=asc)
- jsonFormat = json.loads(df.to_json(orient="index"))
- books = []
- for b in jsonFormat:
- book = jsonFormat[b]
- book["Identifier"] = int(b)
- books.append(book)
- return books
- @api.route("/books/<int:b_id>")
- class Books(Resource):
- @api.response(200, "Book found")
- @api.response(404, "Book not found")
- @api.doc(description="Get a single book given an ID")
- @require_auth
- def get(self, b_id):
- if b_id not in df.index:
- api.abort(404, f"Book {b_id} does not exist")
- book = dict(df.loc[b_id])
- return book
- @api.response(200, "Book deleted")
- @api.response(404, "Book not found")
- @api.doc(description="Delete a single book given an ID")
- @require_auth
- def delete(self, b_id):
- if b_id not in df.index:
- api.abort(404, f"Book {b_id} does not exist")
- df.drop(b_id, inplace=True)
- return {"message": f"Book {b_id} has been removed"}
- @api.response(200, "Book modified")
- @api.response(400, "Data format validation error")
- @api.response(404, "Book not found")
- @api.expect(book_schema)
- @require_auth
- def put(self, b_id):
- if b_id not in df.index:
- api.abort(404, f"Book {b_id} does not exist")
- book = request.json
- print(book)
- if "Identifier" in book and b_id != book["Identifier"]:
- return {"message": "Identifier cannot be changed"}, 400
- for key in book:
- if key not in book_schema.keys():
- return {"message": f"Property {key} is invalid"}, 400
- df.loc[b_id, key] = book[key]
- df.append(book, ignore_index=True)
- return {"message": f"Book {b_id} has been modified"}, 200
- # Handling Dataset for Books
- def importDataset():
- cols_to_drop = [
- "Edition Statement",
- "Corporate Author",
- "Corporate Contributors",
- "Former owner",
- "Engraver",
- "Contributors",
- "Issuance type",
- "Shelfmarks",
- ]
- global df
- df = pd.read_csv(csv)
- df.drop(cols_to_drop, inplace=True, axis=1)
- new_date = df["Date of Publication"].str.extract(r"^(\d{4})", expand=False)
- new_date = pd.to_numeric(new_date)
- new_date = new_date.fillna(0)
- df["Date of Publication"] = new_date
- df.columns = [c.replace(" ", "_") for c in df.columns]
- df.set_index("Identifier", inplace=True)
- if __name__ == "__main__":
- importDataset()
- app.run(debug=True)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement