Ejemplo n.º 1
0
from flask import request
from database.models.user import User
from database.models.heart_rate import HeartRate
from flask_restplus import Resource
from datetime import datetime
from api.utility import list_to_array
from api.routes.access_restrictions import requires_access_level
from flask_jwt_extended import jwt_required, get_jwt_identity
from api.utility import custom_response
from api import api
from api.custom_request import fitness_data

ns = api.namespace('heart-rates',
                   description='Operations related to heart rates')


@ns.route('/all')
@api.doc(security='apiKey')
class HeartRatesAllApi(Resource):
    @jwt_required
    @requires_access_level(0)
    def get(self):
        """
        Return all the heart rates
        """
        heart_rates = HeartRate.query.all()
        heart_rates = list_to_array(heart_rates)
        return custom_response(200, "All Heart Rates", heart_rates)


@ns.route('')
Ejemplo n.º 2
0
                                  required=False,
                                  default=1,
                                  help='Page number')
pagination_arguments.add_argument('bool',
                                  type=bool,
                                  required=False,
                                  default=1,
                                  help='Page number')
pagination_arguments.add_argument('per_page',
                                  type=int,
                                  required=False,
                                  choices=[2, 10, 20, 30, 40, 50],
                                  default=10,
                                  help='Results per page {error_msg}')

ns = api.namespace('todos', description='Operations related to todo posts')


@ns.route('/')
class TodoResource(Resource):
    @api.expect(todo_post)
    def post(self):
        todo = TodoModel(**request.json)
        todo.save_to_db()
        return {'message': 'Success'}

    @api.expect(pagination_arguments)
    def get(self):
        args = pagination_arguments.parse_args(request)
        page = args.get('page', 1)
        per_page = args.get('per_page', 10)
Ejemplo n.º 3
0
from flask import request
from database.models.user import User
from database.models.calorie import Calorie
from flask_restplus import Resource
from datetime import datetime
from api.utility import list_to_array
from api.routes.access_restrictions import requires_access_level
from flask_jwt_extended import jwt_required, get_jwt_identity
from api.utility import custom_response
from api import api
from api.custom_request import fitness_data

ns = api.namespace('calories', description='Operation related to category')


@ns.route('/all')
@api.doc(security='apiKey')
class CaloriesAllApi(Resource):

    @jwt_required
    @requires_access_level(0)
    def get(self):
        """
        Return all the calories
        """
        calories = Calorie.query.all()
        calories = list_to_array(calories)
        return custom_response(
            200,
            "All calories",
            calories
Ejemplo n.º 4
0
from flask import request
from database.models.user import User
from database.models.activity import Activity
from flask_restplus import Resource
from datetime import datetime
from api.utility import list_to_array
from api.routes.access_restrictions import requires_access_level
from flask_jwt_extended import jwt_required, get_jwt_identity
from api.utility import custom_response
from api import api
from api.custom_request import activity_data

ns = api.namespace('activities',
                   description='Operations related to activities')


@ns.route('/all')
@api.doc(security='apiKey')
class ActivitiesAllApi(Resource):
    @jwt_required
    @requires_access_level(0)
    def get(self):
        """
        Return all the activities
        """
        activities = Activity.query.all()
        activities = list_to_array(activities)
        return custom_response(200, "All activities", activities)


@ns.route('')
Ejemplo n.º 5
0
from flask import Flask
from flask_restplus import Resource, fields
from api import api

ns = api.namespace('todos', description='TODO operations')

todo = api.model('Todo', {
    'id': fields.Integer(readOnly=True, description='The task unique identifier'),
    'task': fields.String(required=True, description='The task details')
})


class TodoDAO(object):
    def __init__(self):
        self.counter = 0
        self.todos = []

    def get(self, id):
        for todo in self.todos:
            if todo['id'] == id:
                return todo
        api.abort(404, "Todo {} doesn't exist".format(id))

    def create(self, data):
        todo = data
        todo['id'] = self.counter = self.counter + 1
        self.todos.append(todo)
        return todo

    def update(self, id, data):
        todo = self.get(id)
Ejemplo n.º 6
0
from database.models.user import User
import calendar
import time
import os
import sys
from api.utility import custom_response
import base64
from api import api
from settings import FLASK_SERVER_NAME

dir_name = os.path.dirname(sys.modules['__main__'].__file__)
image_save_path = dir_name + "/food_images/"

server_url = FLASK_SERVER_NAME

ns = api.namespace('images', description='Operations related to images')


@ns.route('')
@api.doc(security='apiKey')
class ImagesApi(Resource):
    @jwt_required
    @requires_access_level(2)
    def post(self):
        """
        Add a new image for the caller user
        """

        current_user = User.find_by_username(get_jwt_identity()['username'])

        current_dir = "{}{}/".format(image_save_path, current_user.id)
Ejemplo n.º 7
0
import datetime
from http import HTTPStatus

from flask_restplus import Resource

from api import api
from api.api_models import loan_model
from api.parsers import book_loan_parser
from database import db
from database.db_models import Book as BookDBModel, Borrower as BorrowerDBModel
from mail import send_reminder_mail

ns = api.namespace('loan', description='Operations with respect to loaning a book')


@ns.route('/')
@api.doc(description='List of books loaned. \n\n ')
class LoanedBooks(Resource):
    @api.marshal_with(loan_model, as_list=True)
    @api.response(HTTPStatus.OK, 'Fetching lent books request successful')
    @api.response(HTTPStatus.BAD_REQUEST, 'Fetching lent books request unsuccessful')
    @api.doc(description='Get List of books loaned . \n\n ')
    def get(self):
        """ Get all lent books """
        try:
            loaned_books = []
            resp = BookDBModel.query.filter(BookDBModel.lent_to.isnot(None)).all()
            if not resp:
                return []
            for x in resp:
                book = x.to_dict()
Ejemplo n.º 8
0
from flask import Response, request, abort
from flask_restplus import Resource
from settings import SAVE_IMG
from api.utility import custom_response
import time
import calendar
import os
import sys
from ml_resources.e_recognition import make_scraper, predict_emotion
from api import api

dir_name = os.path.dirname(sys.modules['__main__'].__file__)
image_save_path = dir_name + "/ml_resources/images/"

ns = api.namespace('emotion-recognition',
                   description='Operations related to emotion recognition')


@ns.route('')
class PredictionApi(Resource):
    def post(self):
        """
        Return the emotion predicted for the specified image
        """
        if not request.files:
            abort(400)

        image = request.files.get("image", "")

        timestamp = calendar.timegm(time.gmtime())
        image_name = str(timestamp) + ".jpg"
Ejemplo n.º 9
0
from flask.ext.restful.reqparse import RequestParser
from api import api, EventsDC, EventDC, ErrorDC, event_parser, log, PaginateEventsDC
from flask.ext.restplus import Resource
from flask import request
from model.event import Event
from model.venue import Venue
from model.visibility import Visibility
from model.assistance import Assistance, Requirement
from services.jwtService import *
from model.user import User

ns = api.namespace('events', description='Servicios para eventos')

@ns.route('/<string:tag>')
@api.doc(responses={404: 'Event not found', 401: 'Authorization Required'}, params={'tag': 'Tag\'s Event'})
class EventService(Resource):
    @api.marshal_with(EventDC)
    @login_optional()
    def get(self, tag):
        log.info("Otorga el Evento con: {'tag':'%s'}" % tag)
        event = Event.query.get_by_tag(tag)
        event.hasAssistance = False
        event.isOwner= False
        user = currentUser()
        event.soldOut = not event.hasAvailability()
        if event.hasAccess(user) :
            if isLogged():
                assistance = Assistance.query.get_by_eventTag_and_user(event.tag, user)
                event.hasAssistance = assistance is not None
                event.requirementMissing = event.lackRequirements()
                event.isOwner = event.owner.username == user.username
Ejemplo n.º 10
0
from flask import request
from database.models.user import User
from database.models.personal_info import PersonalInfo
from flask_restplus import Resource
from api.utility import list_to_array
from api.routes.access_restrictions import requires_access_level
from flask_jwt_extended import jwt_required, get_jwt_identity
from api.utility import custom_response
from api import api
from api.custom_request import personal_info_data

ns = api.namespace('personal-info',
                   description='Operation related to user\'s personal info')


@ns.route('/all')
@api.doc(security='apiKey')
class PersonalInfoAllApi(Resource):
    @jwt_required
    @requires_access_level(0)
    def get(self):
        """
        Return all the users' personal info
        """
        personal_info = PersonalInfo.query.all()
        personal_info = list_to_array(personal_info)
        return custom_response(200, "All personal info", personal_info)


@ns.route('')
@api.doc(security='apiKey')
Ejemplo n.º 11
0
from flask import request
from database.models.user import User
from database.models.step import Step
from flask_restplus import Resource
from datetime import datetime
from api.utility import list_to_array
from api.routes.access_restrictions import requires_access_level
from flask_jwt_extended import jwt_required, get_jwt_identity
from api.utility import custom_response
from api import api
from api.custom_request import fitness_data

ns = api.namespace('steps', description='Operations related to steps')


@ns.route('/all')
@api.doc(security='apiKey')
class StepsAllApi(Resource):
    @jwt_required
    @requires_access_level(0)
    def get(self):
        """
        Return all the steps
        """
        steps = Step.query.all()
        steps = list_to_array(steps)
        return custom_response(200, "All steps", steps)


@ns.route('')
@api.doc(security='apiKey')
Ejemplo n.º 12
0
from flask import request
from database.models.user import User
from database.models.meter import Meter
from flask_restplus import Resource
from datetime import datetime
from api.utility import list_to_array
from api.routes.access_restrictions import requires_access_level
from flask_jwt_extended import jwt_required, get_jwt_identity
from api.utility import custom_response
from api import api
from api.custom_request import fitness_data

ns = api.namespace('meters', description='Operations related to meters')


@ns.route('/all')
@api.doc(security='apiKey')
class MetersAllApi(Resource):
    @jwt_required
    @requires_access_level(0)
    def get(self):
        """
        Return all the meters
        """
        meters = Meter.query.all()
        meters = list_to_array(meters)
        return custom_response(200, "All meters", meters)


@ns.route('')
@api.doc(security='apiKey')
Ejemplo n.º 13
0
from flask.ext.restplus import Resource
import requests
import requests_cache
from datetime import datetime
from api import api, wather_parser, log
from services.jwtService import login_optional
from model.event import Event

ws = api.namespace("weather", description="Servicios para el clima")

# expires_after is seconds (7200 is 2 hours)
requests_cache.install_cache(cache_name="demo_cache", backend="memory", expire_after=7200)


@ws.route("")
@api.doc()
class WeatherService(Resource):
    @login_optional()
    @api.doc(parser=wather_parser)
    def get(self):
        args = wather_parser.parse_args()
        event = Event.query.get_by_tag(args.event)

        eventDate = datetime.strptime(event.date, "%Y-%m-%d")
        today = datetime.today().replace(hour=0, minute=0, second=0, microsecond=0)
        days = (eventDate - today).days

        if days < 16 and days >= 0:
            place = "{0}, {1}, {2}".format(event.venue.street, event.venue.city, event.venue.country)
            r = requests.get(
                "http://api.openweathermap.org/data/2.5/forecast?q=${0}&mode=json&units=metric&cnt=${1}&appid=5bb6740af88caf0f0825477ff473c661&lang=en".format(
Ejemplo n.º 14
0
from flask.ext.restplus import Resource
from api import api, VenueDC, log
from model.venue import Venue
from services.jwtService import *

ns = api.namespace('venues', description='Servicios para venues')


@ns.route('')
class VenuesService(Resource):
    @api.marshal_list_with(VenueDC)
    def get(self):
        return Venue.query.all()
Ejemplo n.º 15
0
from flask_restplus import Resource
from flask import request
from api import api
from api.robot.services import Robot
from robot.robot_mail import login_gmail

ns = api.namespace('robot',
                   description='Robo que loga nas contas gmail via browser')


@ns.route('/login')
class StartRobot(Resource):
    def patch(self):
        login_gmail()
        response = request.json
        ci = Robot()
        ret = ci.conectouEnviou(response)

        return ret
Ejemplo n.º 16
0
from flask_restplus import Namespace, Resource, fields
from .model import UserModel
from api import api
from bson.objectid import ObjectId

user_ns = api.namespace('user', description='Operations related to user')

'''Response Marshals'''
user_output = api.model('user_output', {
    'user_id': fields.String(description='User Id'),
    'username': fields.String(description='Username of a user'),
    'first_name': fields.String(description='First name of a user'),
    'last_name': fields.String(description='Last Name of a user'),
    'email': fields.String(description='Email Address'),
    'date_of_birth': fields.DateTime(description='Date of birth of a user'),
    'active': fields.Boolean(description='Is the user active'),
    'creation_date': fields.DateTime(description='Date when the user was created'),
    'email_verified': fields.Boolean(description='Is the email verified'),
    'address_line_one': fields.String(description='First line of the address'),
    'address_line_two': fields.String(description='Second line of the address'),
    'city': fields.String(description='City'),
    'state': fields.String(description='State'),
    'zip': fields.Integer(description='Zip code'),
    'license': fields.String(description='license number')
    })

user_input = api.model('user_input', {
    'username': fields.String(description='Username of a user'),
    'password': fields.String(description='Password of a user'),
    'first_name': fields.String(description='First name of a user'),
    'last_name': fields.String(description='Last Name of a user'),
Ejemplo n.º 17
0
from http import HTTPStatus

from flask_restplus import Resource

from api import api
from api.api_models import list_model
from api.api_models import success_model
from api.parsers import list_get_parser, list_add_parser
from database import db
from database.db_models import Book as BookModel, ListBook, List as ListModel

ns = api.namespace('lists',
                   description='Operations with respect to books list')


@ns.route('/')
@api.doc(description='Get all lists of books with \n\n ')
class Lists(Resource):
    @api.expect(list_get_parser, validate=False)
    @api.marshal_with(list_model, as_list=True)
    @api.response(HTTPStatus.OK, 'Fetching lists successful')
    @api.response(HTTPStatus.BAD_REQUEST, 'Fetching lists unsuccessful')
    @api.doc(description='Get List of books . \n\n ')
    def get(self):
        """ Get all lists """
        try:
            lists = []
            args = list_get_parser.parse_args()
            resp_query = ListModel.query
            if args['description']:
                resp_query = resp_query.filter_by(
Ejemplo n.º 18
0
from flask_accept import accept
from flask_restplus import Resource

from api import api

ns = api.namespace('hashtags', description='hashtags resource of tweets')


@ns.route("/")
class hashtags(Resource):
    @accept('application/json')
    def get(self):
        """search hashtags from tweets"""
        return []
Ejemplo n.º 19
0
from flask.ext.restplus import Resource
import requests
import requests_cache
from datetime import datetime
from api import api, wather_parser, log
from services.jwtService import login_optional
from model.event import Event

ws = api.namespace('weather', description='Servicios para el clima')

# expires_after is seconds (7200 is 2 hours)
requests_cache.install_cache(cache_name='demo_cache',
                             backend='memory',
                             expire_after=7200)


@ws.route('')
@api.doc()
class WeatherService(Resource):
    @login_optional()
    @api.doc(parser=wather_parser)
    def get(self):
        args = wather_parser.parse_args()
        event = Event.query.get_by_tag(args.event)

        eventDate = datetime.strptime(event.date, "%Y-%m-%d")
        today = datetime.today().replace(hour=0,
                                         minute=0,
                                         second=0,
                                         microsecond=0)
        days = (eventDate - today).days
Ejemplo n.º 20
0
import os
from flask_restplus import Resource, fields
from flask import jsonify, request

from tools.xml_tools import update_xml_attribute
from tools.config_reader import ConfigReader
from tools.kanbans_tools import KanbanFinder, KanbanCreator, KanbanDeleter
from api import api, logger

ns = api.namespace(
    "resources/kanbans",
    description=
    "Operations related to kanban boards located in management module",
)
kanban_model = api.model(
    "Kanban Model",
    {
        "name":
        fields.String(required=True, description="Kanban name"),
        "description":
        fields.String(required=True, description="Kanban description"),
    },
)

# Config file reader (from env variable)
config = ConfigReader()


@ns.route("/")
class KanbansAll(Resource):
    """ Endpoints for kanbans """
from flask.ext.restplus import Resource
from api import api, AssistancesDC, log, assistance_parser, mailService, PaginateAssistancesDC
from flask import request
from model.assistance import Assistance, Requirement
from model.user import User
from model.event import Event
from services.jwtService import *

ass = api.namespace('assistances', description='Servicios para asistencias')

@ass.route('')
class AssistanceService(Resource):
    @api.marshal_list_with(AssistancesDC)
    @login_required()
    def get(self):
        return Assistance.query.get_by_user(currentUser())

    @api.doc(parser=assistance_parser)
    @api.marshal_with(AssistancesDC, code=201)
    @login_required()
    def post(self):
        args = assistance_parser.parse_args()
        event = Event.query.get_by_tag(args.event)
        if not event.hasAvailability():
            api.abort(400, "The event haven't availability")

        newAssistance = Assistance(
            eventTag = args.event,
            event = event.getAppearanceAssistance(),
            user = currentUser().username,
            requirements = map(lambda req: Requirement(name=req["name"],quantity=req["quantity"]), args.requirements)
from flask.ext.restplus import Resource
from api import api, AssistancesDC, log, assistance_parser, mailService, PaginateAssistancesDC
from flask import request
from model.assistance import Assistance, Requirement
from model.user import User
from model.event import Event
from services.jwtService import *

ass = api.namespace('assistances', description='Servicios para asistencias')


@ass.route('')
class AssistanceService(Resource):
    @api.marshal_list_with(AssistancesDC)
    @login_required()
    def get(self):
        return Assistance.query.get_by_user(currentUser())

    @api.doc(parser=assistance_parser)
    @api.marshal_with(AssistancesDC, code=201)
    @login_required()
    def post(self):
        args = assistance_parser.parse_args()
        event = Event.query.get_by_tag(args.event)
        if not event.hasAvailability():
            api.abort(400, "The event haven't availability")

        newAssistance = Assistance(
            eventTag=args.event,
            event=event.getAppearanceAssistance(),
            user=currentUser().username,
Ejemplo n.º 23
0
from flask.ext.restplus import Resource
from api import api, VenueDC, log
from model.venue import Venue
from services.jwtService import *

ns = api.namespace('venues', description='Servicios para venues')

@ns.route('')
class VenuesService(Resource):
    @api.marshal_list_with(VenueDC)
    def get(self):
        return Venue.query.all()
Ejemplo n.º 24
0
Archivo: users.py Proyecto: hnjm/LEFT
from flask_accept import accept
from flask_restplus import Resource

from api import api

ns = api.namespace('users', description='users resource of tweets')


@ns.route("/")
class Users(Resource):
    @accept('application/json')
    def get(self):
        """search users from tweets"""
        return []
Ejemplo n.º 25
0
from flask import request
from flask_restplus import Resource
from database.models.user import User
from flask_jwt_extended import (create_access_token, create_refresh_token,
                                jwt_required, jwt_refresh_token_required,
                                get_jwt_identity, get_raw_jwt)
from database.models.revoked_token import RevokedToken
from api.utility import custom_response
from api import api
from api.custom_request import login_data

ns = api.namespace('', description='Operations related to authentication')


@ns.route('/sign-in')
@api.expect(login_data)
class LoginApi(Resource):
    def post(self):
        """
        Create new user session
        """
        body = request.get_json()
        user = User.find_by_username(body['username'])
        if not user:
            return custom_response(
                401, 'User {} doesn\'t exist'.format(body['username']))

        if User.verify_hash(body['password'], user.password):
            tmp_user = user.to_dict()
            tmp_user.update({
                'access_token':
Ejemplo n.º 26
0
"""
Nominations API Implementation
"""
from flask import request
from flask_restplus import Resource
from api import api
from database import db
from database.nomination import Nomination
from api.serializers import nomination

ns = api.namespace('nominations', description='Nomination operations')


def create_nom(data):
    """
    Add a nomination to the database.

    :param dict data: The JSON representing the nomination
    """
    name = data.get('name')
    pic_path = data.get('pic_path')
    seconded = data.get('seconded')
    votes = data.get('votes')
    nom = Nomination(name, pic_path, seconded, votes)
    db.session.add(nom)
    db.session.commit()


def update_nom(nom_name, data):
    """
    Update a nom in the database.
Ejemplo n.º 27
0
from api import api

# define constaints

DESCRIPTION = """
This collection of API endpoints serves Taxomomic Information Registry (TIR)
record documents in the form of a paginated list or a single record lookup by identifier.
Additionally, it provides the ability to write custom queries following the Elasticsearch
query DSL specifications. (https://www.elastic.co/guide/en/elasticsearch/reference/current/query-dsl.html)
"""

ELASTIC_INDEX = 'bis_pipeline__pipeline_result__sgcn'
DEFAULT_ERROR_MESSAGE = 'Error! Something went wrong while processing this TIR request.'

NS = api.namespace('TIR',
                   description='Taxonomic Information Registry',
                   path="/api/v1")

UNIT_SCHEMA = {
    "$schema": "http://json-schema.org/draft-04/schema#",
    "taxonomic_category": {
        "type": "string"
    },
    "state": {
        "type": "string"
    },
    "record_processed": {
        "type": "string"
    },
    "source_file_date": {
        "type": "string"
Ejemplo n.º 28
0
from http import HTTPStatus

from flask_restplus import Resource

from api import api
from api.api_models import borrower_model
from api.parsers import borrower_update_parser, borrower_parser
from database import db
from database.db_models import Book as BookDBModel, Borrower as BorrowerDBModel

ns = api.namespace('borrowers',
                   description='Operations with respect to borrowers')


@ns.route('/')
@api.doc(description='List of borrowers. \n\n ')
class Borrowers(Resource):
    @api.marshal_with(borrower_model, as_list=True)
    @api.response(HTTPStatus.OK, 'Fetching all borrowers successful')
    @api.response(HTTPStatus.BAD_REQUEST,
                  'Fetching borrowers request unsuccessful')
    @api.doc(description='Get List of borrowers . \n\n ')
    def get(self):
        """ Get all borrowers """
        try:
            result = {}
            borrowers = []

            resp = BorrowerDBModel.query.all()
            if not resp:
                return []
Ejemplo n.º 29
0
from flask.ext.restplus import Resource
from api import api, signup, user_parser, log, UsersDC, app, mailService
from services.jwtService import jwt, generate_token, login_required, currentUser
from model.user import User

us = api.namespace('user', description='Servicios para usuario')


@us.route('')
class UserService(Resource):
    @api.marshal_with(signup)
    @login_required()
    def get(self):
        return currentUser()

    @api.doc(parser=user_parser)
    @login_required()
    def put(self):
        args = user_parser.parse_args()
        user = currentUser()
        user.email = args.email
        user.firstName = args.firstName
        user.lastName = args.lastName
        user.phone = args.phone
        user.save()
        return 201

    @api.doc(parser=user_parser)
    def post(self):
        args = user_parser.parse_args()
        user = User(username=args.username,