Advertisement
Guest User

Untitled

a guest
Oct 14th, 2018
105
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 4.12 KB | None | 0 0
  1. import json
  2. import pandas as pd
  3. from flask import Flask, request
  4. from flask_restplus import Resource, Api, fields, inputs, reqparse
  5. from functools import wraps
  6.  
  7. auth = {"basic": {"type": "basic"}}
  8.  
  9. app = Flask(__name__)
  10. api = Api(
  11. app,
  12. default="Books",
  13. title="Books Dataset",
  14. description="desc",
  15. authorizations=auth,
  16. security="basic"
  17. )
  18. csv = "Books.csv"
  19. df = None
  20.  
  21. book_schema = api.model(
  22. "Book",
  23. {
  24. "Flickr_URL": fields.String,
  25. "Publisher": fields.String,
  26. "Author": fields.String,
  27. "Title": fields.String,
  28. "Date_of_Publication": fields.Integer,
  29. "Identifier": fields.Integer,
  30. "Place_of_Publication": fields.String,
  31. },
  32. )
  33.  
  34. parser = reqparse.RequestParser()
  35. parser.add_argument("order", choices=[col for col in book_schema.keys()])
  36. parser.add_argument("ascending", type=inputs.boolean)
  37.  
  38.  
  39. def require_auth(f):
  40. @wraps(f)
  41. def decorated(*args, **kwargs):
  42. auth = request.authorization
  43. if not auth:
  44. api.abort(401)
  45. if not (auth.username == "admin" and auth.password == "admin"):
  46. api.abort(401)
  47. return f(*args, **kwargs)
  48.  
  49. return decorated
  50.  
  51.  
  52. # API
  53. @api.route("/books")
  54. class BooksList(Resource):
  55. @api.response(200, "Success")
  56. @api.doc(description="Get a list of all books")
  57. @require_auth
  58. def get(self):
  59. args = parser.parse_args()
  60. (order, asc) = (args.get("order"), args.get("ascending", True))
  61.  
  62. if order:
  63. df.sort_value(by=order, inplace=True, ascending=asc)
  64.  
  65. jsonFormat = json.loads(df.to_json(orient="index"))
  66.  
  67. books = []
  68. for b in jsonFormat:
  69. book = jsonFormat[b]
  70. book["Identifier"] = int(b)
  71. books.append(book)
  72.  
  73. return books
  74.  
  75.  
  76. @api.route("/books/<int:b_id>")
  77. class Books(Resource):
  78. @api.response(200, "Book found")
  79. @api.response(404, "Book not found")
  80. @api.doc(description="Get a single book given an ID")
  81. @require_auth
  82. def get(self, b_id):
  83. if b_id not in df.index:
  84. api.abort(404, f"Book {b_id} does not exist")
  85. book = dict(df.loc[b_id])
  86. return book
  87.  
  88. @api.response(200, "Book deleted")
  89. @api.response(404, "Book not found")
  90. @api.doc(description="Delete a single book given an ID")
  91. @require_auth
  92. def delete(self, b_id):
  93. if b_id not in df.index:
  94. api.abort(404, f"Book {b_id} does not exist")
  95. df.drop(b_id, inplace=True)
  96. return {"message": f"Book {b_id} has been removed"}
  97.  
  98. @api.response(200, "Book modified")
  99. @api.response(400, "Data format validation error")
  100. @api.response(404, "Book not found")
  101. @api.expect(book_schema)
  102. @require_auth
  103. def put(self, b_id):
  104. if b_id not in df.index:
  105. api.abort(404, f"Book {b_id} does not exist")
  106.  
  107. book = request.json
  108. print(book)
  109. if "Identifier" in book and b_id != book["Identifier"]:
  110. return {"message": "Identifier cannot be changed"}, 400
  111.  
  112. for key in book:
  113. if key not in book_schema.keys():
  114. return {"message": f"Property {key} is invalid"}, 400
  115. df.loc[b_id, key] = book[key]
  116. df.append(book, ignore_index=True)
  117. return {"message": f"Book {b_id} has been modified"}, 200
  118.  
  119.  
  120. # Handling Dataset for Books
  121. def importDataset():
  122. cols_to_drop = [
  123. "Edition Statement",
  124. "Corporate Author",
  125. "Corporate Contributors",
  126. "Former owner",
  127. "Engraver",
  128. "Contributors",
  129. "Issuance type",
  130. "Shelfmarks",
  131. ]
  132. global df
  133. df = pd.read_csv(csv)
  134. df.drop(cols_to_drop, inplace=True, axis=1)
  135.  
  136. new_date = df["Date of Publication"].str.extract(r"^(\d{4})", expand=False)
  137. new_date = pd.to_numeric(new_date)
  138. new_date = new_date.fillna(0)
  139. df["Date of Publication"] = new_date
  140.  
  141. df.columns = [c.replace(" ", "_") for c in df.columns]
  142.  
  143. df.set_index("Identifier", inplace=True)
  144.  
  145.  
  146. if __name__ == "__main__":
  147. importDataset()
  148. app.run(debug=True)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement