Advertisement
Guest User

Untitled

a guest
Aug 3rd, 2017
489
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.76 KB | None | 0 0
  1. import pdb
  2. from flask import Flask, jsonify, request, abort
  3. from flask_jwt_extended import JWTManager, jwt_required,\
  4. create_access_token, get_jwt_identity
  5.  
  6.  
  7. books = [
  8. {
  9. 'id': 1,
  10. 'title': u'Learn Python hard way',
  11. 'author': u'Nikhil'
  12. },
  13. {
  14. 'id': 2,
  15. 'title': u'Learning Python',
  16. 'Author': u'ABCD'
  17. }
  18. ]
  19.  
  20.  
  21. app = Flask(__name__)
  22. app.secret_key = 'super-secret' # Change this!
  23.  
  24. # Setup the Flask-JWT-Extended extension
  25. jwt = JWTManager(app)
  26.  
  27.  
  28. # Provide a method to create access tokens. The create_access_token()
  29. # function is used to actually generate the token
  30. @app.route('/login', methods=['POST'])
  31. def login():
  32. username = request.json.get('username', None)
  33. password = request.json.get('password', None)
  34. if username != 'test' or password != 'test':
  35. return jsonify({"msg": "Bad username or password"}), 401
  36.  
  37. ret = {'access_token': create_access_token(identity=username)}
  38. return jsonify(ret), 200
  39.  
  40.  
  41. @app.route('/books', methods=['GET', 'POST'])
  42. @jwt_required
  43. def get_books():
  44. if request.method == 'POST':
  45. return create_book()
  46. else:
  47. return jsonify({'books': books})
  48.  
  49.  
  50. def create_book():
  51. if not (request.json or 'title' in request.json):
  52. abort(400)
  53. book = {
  54. 'id': books[-1]['id'] + 1,
  55. 'title': request.json['title'],
  56. 'author': request.json.get('author', "")
  57.  
  58. }
  59. books.append(book)
  60. return jsonify({'book': book}), 201
  61.  
  62.  
  63. @app.route('/books/<int:book_id>', methods=['DELETE'])
  64. @jwt_required
  65. def delete_book(book_id):
  66. pdb.set_trace()
  67. book = [book for book in books if book['id'] == book_id]
  68. if len(book) == 0:
  69. abort(404)
  70. books.remove(book[0])
  71. return jsonify({'result': True})
  72.  
  73.  
  74. if __name__ == '__main__':
  75. app.run()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement