├── .gitignore ├── app.py ├── data.db ├── data.py └── model ├── __init__.py ├── episode.py ├── show.py └── user.py /.gitignore: -------------------------------------------------------------------------------- 1 | apienv 2 | .idea -------------------------------------------------------------------------------- /app.py: -------------------------------------------------------------------------------- 1 | from datetime import datetime, timedelta 2 | 3 | from flask import Flask, jsonify, request 4 | from flask_jwt import JWT, jwt_required 5 | from werkzeug.security import safe_str_cmp 6 | 7 | from data import alchemy 8 | from model import show, episode, user 9 | 10 | app = Flask(__name__) 11 | app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///data.db' 12 | app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False 13 | app.config['PROPAGATE_EXCEPTIONS'] = True 14 | app.secret_key = 'supersecreto' 15 | 16 | 17 | # Funções necessárias para o JWT 18 | def authenticate(username,password): 19 | auth_user = user.UserModel.find_by_name(username) 20 | dict_error = {'erro':'Usuário ou senha inválidos'} 21 | if auth_user and safe_str_cmp(auth_user.password.encode('utf-8'),password.encode('utf-8')): 22 | return auth_user 23 | return auth_user, 401 24 | 25 | def identity(payload): 26 | user_id = payload['user_name'] 27 | return user.UserModel.find_by_name(user_id) 28 | 29 | jwt = JWT(app,authenticate,identity) 30 | 31 | @jwt.jwt_payload_handler 32 | def make_payload(jwt_identity): 33 | expiration = datetime.now() +timedelta(hours=10) 34 | nbf = datetime.now() + timedelta(seconds=1) 35 | iat = datetime.now() 36 | return { 37 | 'user_id' : jwt_identity.id, 38 | 'user_name' : jwt_identity.name, 39 | 'iat':iat, 40 | 'exp':expiration, 41 | 'nbf':nbf 42 | } 43 | 44 | @app.before_first_request 45 | def create_tables(): 46 | alchemy.create_all() 47 | 48 | 49 | @app.route('/', methods=['GET']) 50 | @jwt_required() 51 | def home(): 52 | return "API Funcionando", 200 53 | 54 | @app.route("/signup",methods=['POST']) 55 | def signup(): 56 | request_data = request.get_json() 57 | # Caso o email já exista, devolve conflito (status 409) 58 | if (user.UserModel.find_by_name(request_data['username'])): 59 | return {'message': 'email já encontrado'}, 409 60 | new_user = user.UserModel(name=request_data['username'],password=request_data['password']) 61 | new_user.save_to_db() 62 | return new_user.json() 63 | 64 | # post /show data: {name :} 65 | @app.route('/show', methods=['POST']) 66 | @jwt_required() 67 | def create_show(): 68 | request_data = request.get_json() 69 | new_show = show.ShowModel(request_data['name']) 70 | new_show.save_to_db() 71 | result = show.ShowModel.find_by_id(new_show.id) 72 | return jsonify(result.json()) 73 | 74 | 75 | # get /show/ data: {name :} 76 | @app.route('/show/') 77 | @jwt_required() 78 | def get_show(name): 79 | result = show.ShowModel.find_by_name(name); 80 | if result: 81 | return result.json(); 82 | return {'message': 'Série não encontrada'}, 404 83 | 84 | 85 | # post /show/ data: {name :} 86 | @app.route('/show//item', methods=['POST']) 87 | @jwt_required() 88 | def create_episode_in_show(name): 89 | request_data = request.get_json() 90 | parent = show.ShowModel.find_by_name(name) 91 | if parent: 92 | new_episode = episode.EpisodeModel(name=request_data['name'], season=request_data['season'], show_id=parent.id) 93 | new_episode.save_to_db() 94 | return new_episode.json() 95 | else: 96 | return {'message': 'Não existe a série'}, 404 97 | 98 | 99 | 100 | if __name__ == '__main__': 101 | from data import alchemy 102 | 103 | alchemy.init_app(app) 104 | app.run(port=5000, debug=True) 105 | -------------------------------------------------------------------------------- /data.db: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/brigolini/show-api-flask/2707b4608c5c1454ddfacd396efcb744ee8a0c79/data.db -------------------------------------------------------------------------------- /data.py: -------------------------------------------------------------------------------- 1 | from flask_sqlalchemy import SQLAlchemy 2 | 3 | alchemy = SQLAlchemy() -------------------------------------------------------------------------------- /model/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/brigolini/show-api-flask/2707b4608c5c1454ddfacd396efcb744ee8a0c79/model/__init__.py -------------------------------------------------------------------------------- /model/episode.py: -------------------------------------------------------------------------------- 1 | from data import alchemy 2 | 3 | class EpisodeModel(alchemy.Model): 4 | __tablename__ = 'episode' 5 | 6 | id = alchemy.Column(alchemy.Integer, primary_key=True) 7 | name = alchemy.Column(alchemy.String(80)) 8 | season = alchemy.Column(alchemy.Float(precision=2)) 9 | 10 | show_id = alchemy.Column(alchemy.Integer, alchemy.ForeignKey('shows.id')) 11 | #episode = alchemy.relationship('show.ShowModel') 12 | 13 | def __init__(self, name, season, show_id): 14 | self.name = name 15 | self.season = season 16 | self.show_id = show_id 17 | 18 | def json(self): 19 | return {'name': self.name, 'season': self.season} 20 | 21 | @classmethod 22 | def find_by_name(cls, name): 23 | return cls.query.filter_by(name=name).first() 24 | 25 | def save_to_db(self): 26 | alchemy.session.add(self) 27 | alchemy.session.commit() 28 | 29 | def delete_from_db(self): 30 | alchemy.session.delete(self) 31 | alchemy.session.commit() -------------------------------------------------------------------------------- /model/show.py: -------------------------------------------------------------------------------- 1 | from data import alchemy 2 | from . import episode 3 | 4 | 5 | class ShowModel(alchemy.Model): 6 | __tablename__ = 'shows' 7 | 8 | id = alchemy.Column(alchemy.Integer, primary_key=True) 9 | name = alchemy.Column(alchemy.String(80)) 10 | 11 | episodes = alchemy.relationship(episode.EpisodeModel, lazy='dynamic') 12 | 13 | def __init__(self, name): 14 | self.name = name 15 | 16 | def json(self): 17 | return {'name': self.name, 'episodes': [episode.json() for episode in self.episodes.all()]} 18 | 19 | def save_to_db(self): 20 | alchemy.session.add(self) 21 | alchemy.session.commit() 22 | 23 | @classmethod 24 | def find_by_name(cls, name): 25 | return cls.query.filter_by(name=name).first() 26 | 27 | @classmethod 28 | def find_by_id(cls, _id): 29 | return cls.query.filter_by(id=_id).first() -------------------------------------------------------------------------------- /model/user.py: -------------------------------------------------------------------------------- 1 | from data import alchemy 2 | 3 | 4 | class UserModel(alchemy.Model): 5 | __tablename__ = 'user' 6 | 7 | id = alchemy.Column(alchemy.Integer, primary_key=True) 8 | name = alchemy.Column(alchemy.String(80)) 9 | password = alchemy.Column(alchemy.String(80)) 10 | 11 | def __init__(self, name, password): 12 | self.name = name 13 | self.password = password 14 | 15 | def json(self): 16 | return {'name': self.name, 'password': self.password} 17 | 18 | @classmethod 19 | def find_by_name(cls, name): 20 | return cls.query.filter_by(name=name).first() 21 | 22 | def save_to_db(self): 23 | alchemy.session.add(self) 24 | alchemy.session.commit() 25 | 26 | def delete_from_db(self): 27 | alchemy.session.delete(self) 28 | alchemy.session.commit() 29 | --------------------------------------------------------------------------------