Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import pdb
- from flask import Flask, jsonify, request, abort
- from flask_jwt_extended import JWTManager, jwt_required,\
- create_access_token, get_jwt_identity
- books = [
- {
- 'id': 1,
- 'title': u'Learn Python hard way',
- 'author': u'Nikhil'
- },
- {
- 'id': 2,
- 'title': u'Learning Python',
- 'Author': u'ABCD'
- }
- ]
- app = Flask(__name__)
- app.secret_key = 'super-secret' # Change this!
- # Setup the Flask-JWT-Extended extension
- jwt = JWTManager(app)
- # Provide a method to create access tokens. The create_access_token()
- # function is used to actually generate the token
- @app.route('/login', methods=['POST'])
- def login():
- username = request.json.get('username', None)
- password = request.json.get('password', None)
- if username != 'test' or password != 'test':
- return jsonify({"msg": "Bad username or password"}), 401
- ret = {'access_token': create_access_token(identity=username)}
- return jsonify(ret), 200
- @app.route('/books', methods=['GET', 'POST'])
- @jwt_required
- def get_books():
- if request.method == 'POST':
- return create_book()
- else:
- return jsonify({'books': books})
- def create_book():
- if not (request.json or 'title' in request.json):
- abort(400)
- book = {
- 'id': books[-1]['id'] + 1,
- 'title': request.json['title'],
- 'author': request.json.get('author', "")
- }
- books.append(book)
- return jsonify({'book': book}), 201
- @app.route('/books/<int:book_id>', methods=['DELETE'])
- @jwt_required
- def delete_book(book_id):
- pdb.set_trace()
- book = [book for book in books if book['id'] == book_id]
- if len(book) == 0:
- abort(404)
- books.remove(book[0])
- return jsonify({'result': True})
- if __name__ == '__main__':
- app.run()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement