flask-api-example/app.py

227 lines
5.5 KiB
Python
Raw Permalink Normal View History

2018-01-31 23:17:52 +01:00
# -*- coding: utf-8 -*-
2018-02-01 22:40:22 +01:00
2018-02-05 23:59:51 +01:00
# =========================
2018-01-31 23:17:52 +01:00
# Librarys
2018-02-01 22:40:22 +01:00
# =========================
2018-01-31 00:42:22 +01:00
import os
2018-02-11 18:02:41 +01:00
from os.path import join, dirname
from dotenv import load_dotenv
2018-02-05 23:59:51 +01:00
from flask import Flask, request
2018-01-20 00:37:59 +01:00
from flask_restplus import Resource, Api
2018-02-05 23:59:51 +01:00
from models import db, User, Notice, Comment
2018-02-05 23:00:30 +01:00
from flask_marshmallow import Marshmallow
2018-01-31 00:42:22 +01:00
2018-02-05 23:59:51 +01:00
# =========================
2018-02-01 22:40:22 +01:00
# Extensions initialization
# =========================
2018-02-11 18:02:41 +01:00
dotenv_path = join(dirname(__file__), 'env')
load_dotenv(dotenv_path)
2018-01-20 00:37:59 +01:00
app = Flask(__name__)
2018-02-12 22:39:12 +01:00
2018-01-31 23:17:52 +01:00
2018-02-05 23:59:51 +01:00
# =========================
2018-02-01 22:40:22 +01:00
# Configurations
# =========================
app.config['SECRET_KEY'] = os.environ.get('SECRET_KEY')
2018-02-01 20:32:28 +01:00
app.config['SQLALCHEMY_DATABASE_URI'] = os.environ.get('DATABASE_URI')
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
2018-02-12 22:39:12 +01:00
ma = Marshmallow(app)
api = Api(app)
2018-02-01 20:32:28 +01:00
db.init_app(app)
2018-01-20 00:37:59 +01:00
PRE_URL = '/api/v1/'
2018-02-05 23:59:51 +01:00
# =========================
2018-02-05 23:00:30 +01:00
# Schemas
# =========================
2018-02-05 23:59:51 +01:00
2018-02-05 23:00:30 +01:00
# User
class UserSchema(ma.Schema):
class Meta:
# Fields to expose
fields = ('username', 'mail')
user_schema = UserSchema()
users_schema = UserSchema(many=True)
2018-02-05 23:59:51 +01:00
# Notice
class NoticeSchema(ma.Schema):
class Meta:
# Fields to expose
2018-02-06 23:01:20 +01:00
fields = ('title', 'url', 'user_id', '_links')
2018-02-05 23:59:51 +01:00
_links = ma.Hyperlinks({
'comments': ma.URLFor('comments', id='<id>'),
'user': ma.URLFor('user_single', id='<user_id>')
})
notice_schema = NoticeSchema()
news_schema = NoticeSchema(many=True)
# Comment
class CommentSchema(ma.Schema):
class Meta:
# Fields to expose
fields = ('text', '_links')
_links = ma.Hyperlinks({
'notice': ma.URLFor('news_single', id='<id>'),
'user': ma.URLFor('user_single', id='<user_id>')
})
comment_schema = CommentSchema()
comments_schema = CommentSchema(many=True)
# =========================
2018-02-05 23:00:30 +01:00
# Routes
# =========================
2018-02-05 23:59:51 +01:00
2018-02-05 23:00:30 +01:00
# Signup
2018-01-20 00:37:59 +01:00
@api.route(PRE_URL + 'signup')
class Signup(Resource):
def post(self):
2018-02-06 21:29:09 +01:00
return {'message': 'ok'}
2018-01-20 00:37:59 +01:00
2018-02-05 23:59:51 +01:00
2018-02-05 23:00:30 +01:00
# Login
2018-01-20 00:37:59 +01:00
@api.route(PRE_URL + 'login')
class Login(Resource):
def post(self):
2018-02-06 21:29:09 +01:00
return {'message': 'ok'}
2018-01-20 00:37:59 +01:00
2018-02-05 23:59:51 +01:00
2018-02-05 23:00:30 +01:00
# Logout
2018-02-05 23:59:51 +01:00
@api.route(PRE_URL + 'logout')
2018-01-20 00:37:59 +01:00
class Logout(Resource):
def get(self):
2018-02-06 21:29:09 +01:00
return {'message': 'ok'}
2018-01-20 00:37:59 +01:00
2018-02-05 23:59:51 +01:00
2018-02-05 23:00:30 +01:00
# User
@api.route(PRE_URL + 'user')
class UserList(Resource):
2018-01-20 00:37:59 +01:00
2018-02-05 23:00:30 +01:00
def get(self):
all_users = User.query.all()
return users_schema.jsonify(all_users)
@api.route(PRE_URL + 'user/<int:id>')
class UserSingle(Resource):
def get(self, id):
2018-02-06 21:29:09 +01:00
my_user = User.query.get(id)
if my_user:
return user_schema.jsonify(my_user)
else:
return {'message': 'No existe el usuario'}, 400
2018-02-05 23:00:30 +01:00
2018-02-05 23:59:51 +01:00
# Notice
@api.route(PRE_URL + 'notice')
class NoticeList(Resource):
2018-01-20 00:37:59 +01:00
def get(self):
2018-02-05 23:59:51 +01:00
my_news = Notice.query.all()
return news_schema.jsonify(my_news)
2018-01-20 00:37:59 +01:00
def post(self):
2018-02-06 21:29:09 +01:00
json_data = request.get_json()
if not json_data:
return {'message': 'Datos inválidos'}, 400
# Validations
try:
title = json_data['title']
url = json_data['url']
user_id = json_data['user_id']
except Exception as e:
return {'message': 'No existen los campos necesarios'}, 400
# Save data
my_notice = Notice(title=title, url=url, user_id=user_id)
db.session.add(my_notice)
try:
db.session.commit()
except Exception as e:
db.session.rollback()
return {'message': 'No se ha podido guardar la información'}, 500
return {'message': 'ok'}, 200
2018-01-20 00:37:59 +01:00
2018-02-05 23:59:51 +01:00
@api.route(PRE_URL + 'notice/<int:id>')
class NewsSingle(Resource):
2018-01-20 00:37:59 +01:00
def get(self, id):
2018-02-05 23:59:51 +01:00
my_notice = Notice.query.get(id)
return notice_schema.jsonify(my_notice)
2018-02-06 21:29:09 +01:00
def patch(self, id):
2018-02-05 23:59:51 +01:00
my_notice = Notice.query.get(id)
2018-02-06 21:29:09 +01:00
if not my_notice:
return {'message': 'No existe la noticia'}, 400
json_data = request.get_json()
if not json_data:
return {'message': 'Datos inválidos'}, 400
# Validations
try:
title = json_data['title']
url = json_data['url']
user_id = json_data['user_id']
except Exception as e:
return {'message': 'No existen los campos necesarios'}, 400
# Update data
my_notice.title = title
my_notice.url = url
my_notice.user_id = user_id
db.session.add(my_notice)
try:
db.session.commit()
except Exception as e:
db.session.rollback()
return {'message': 'No se ha podido guardar la información'}, 500
return {'message': 'ok'}, 200
2018-02-05 23:59:51 +01:00
def delete(self, id):
my_notice = Notice.query.get(id)
2018-02-06 21:29:09 +01:00
if my_notice:
db.session.delete(my_notice)
db.session.commit()
try:
db.session.commit()
except Exception as e:
db.session.rollback()
2018-02-06 21:31:34 +01:00
return {
'message': 'No se ha podido guardar la información'}, 500
2018-02-06 21:29:09 +01:00
else:
return {'message': 'No existe la noticia'}, 400
return {'message': 'ok'}, 200
2018-01-20 00:37:59 +01:00
2018-02-05 23:00:30 +01:00
# Comment
2018-02-05 23:59:51 +01:00
@api.route(PRE_URL + 'notice/<int:id>/comments')
2018-01-20 00:37:59 +01:00
class Comments(Resource):
def get(self, id):
2018-02-05 23:59:51 +01:00
my_comments = Comment.query.filter_by(notice_id=id).all()
return comments_schema.jsonify(my_comments)
2018-01-20 00:37:59 +01:00
def post(self, id):
return {'hello': 'world'}
2018-02-05 23:59:51 +01:00
# =========================
2018-02-05 23:00:30 +01:00
# Run
# =========================
2018-01-20 00:37:59 +01:00
if __name__ == '__main__':
2018-02-05 23:00:30 +01:00
app.run(debug=True if os.environ.get('DEBUG') == 'True' else False)