Beispiel #1
0
            return abort(
                400, 'Não existe professor com esse ID no banco de dados.')

        if args:
            professor_selected.update(dict(**args))
            db.session.commit()

        return {}, 204

    @api.response(400, 'Não existe professor com esse ID no banco de dados.')
    @api.response(204, 'Success')
    def delete(self, unique_id):
        '''
        Deleta um professor com o determinado ID presente no banco de dados.
        '''

        professor_selected = Professor.query.filter_by(id=unique_id)

        if not professor_selected.first():
            return abort(
                400, 'Não existe professor com esse ID no banco de dados.')

        professor_selected.delete()

        db.session.commit()

        return {}, 204


api.add_resource(rota_acesso_todos_professores, '/')
api.add_resource(rota_acesso_unico_professores, '/<int:unique_id>/')
    @profile_orders_namespace.marshal_with(order)
    def get(self):
        """Returns all orders"""
        logger.info("Orders.get()")
        try:
            user_id = current_user().id
            orders =  Orders.get_orders_of_user(user_id=user_id)


            return [order.to_dict() for order in orders], 200
        except Exception as e:
            logger.exception("Orders.get(): %s", str(e))
            return "Couldn't load orders", 500

    @auth_required
    @profile_orders_namespace.expect(order)
    def put(self):
        """Updates current user order"""
        logger.info("Orders.put() user_id: %s", str(current_user().id))
        try:
            content = request.get_json()
            Orders.update_order(content)
            return 'User order has been updated', 200
        except Exception as e:
            logger.exception("Order.put(): %s", str(e))
            return "Couldn't update user's order", 500



profile_orders_namespace.add_resource(OrdersNamespace, "")
Beispiel #3
0
            lat = 0
        if lon is None:
            lon = 0
        if m is None:
            m = -1
        if k is None:
            k = -1
        # print(lat, lon, place_types, m, k)

        res = get_knearest_places(lat, lon, place_types, m, k)

        return res, 200


class PlaceRating(Resource):
    def get(self, place_id):
        """Returns average rating for given place id. 0 if there are no ratings."""
        response_object = {}
        place = get_place_by_id(place_id)

        if not place:
            places_namespace.abort(404, f"Place {place_id} does not exist")
        rating = get_rating_by_id(place_id)
        return {"rating": int(rating)}, 200


places_namespace.add_resource(PlacesList, "")
places_namespace.add_resource(Places, "/<int:place_id>")
places_namespace.add_resource(PlacesSearches, "/<string:place_types>")
places_namespace.add_resource(PlaceRating, "/rating/<int:place_id>")
Beispiel #4
0
        "votes_voided": fields.Integer(readOnly=True),
        "tie_avoided": fields.Boolean(readOnly=True),
        "day_found": fields.Integer(readOnly=True),
        "day_played": fields.Integer(readOnly=True),
        "note": fields.String(readOnly=True),
        "appearance": fields.Integer(attribute="appearance.id"),
    },
)


class IdolList(Resource):
    @idol_namespace.marshal_with(idol, as_list=True)
    def get(self):
        """Returns all users."""
        return get_all_idols(**request.args), 200


# class Idol(Resource):
#     @idol_namespace.marshal_with(idol)
#     @idol_namespace.response(200, "Success")
#     @idol_namespace.response(404, "Contestant <id> does not exist")
#     def get(self, contestant_id):
#         """Returns a single user."""
#         user = get_contestant_by_id(contestant_id)
#         if not user:
#             idol_namespace.abort(404, f"Contestant {contestant_id} does not exist")
#         return user, 200

idol_namespace.add_resource(IdolList, "")
# contestant_namespace.add_resource(Contestant, "/<int:contestant_id>")
Beispiel #5
0
            res = empty_result(data=f"Scheduled job to renew certificates")
            res['job_id'] = job_id

            resp = make_response(json.dumps(res), 200)
            if total_count:
                resp.headers['X-Total-Count'] = total_count
            resp.headers['Content-Type'] = "application/json"
            return resp
        else:
            return empty_result(
                status='error',
                data=f"Unknown action specified: {action}"), 400


# Devices
device_api.add_resource(DeviceByIdApi, '/<int:device_id>')
device_api.add_resource(DeviceByHostnameApi, '/<string:hostname>')
device_api.add_resource(DeviceConfigApi, '/<string:hostname>/generate_config')
device_api.add_resource(DevicePreviousConfigApi,
                        '/<string:hostname>/previous_config')
device_api.add_resource(DeviceApplyConfigApi,
                        '/<string:hostname>/apply_config')
device_api.add_resource(DeviceApi, '')
devices_api.add_resource(DevicesApi, '')
device_init_api.add_resource(DeviceInitApi, '/<int:device_id>')
device_initcheck_api.add_resource(DeviceInitCheckApi, '/<int:device_id>')
device_discover_api.add_resource(DeviceDiscoverApi, '')
device_syncto_api.add_resource(DeviceSyncApi, '')
device_update_facts_api.add_resource(DeviceUpdateFactsApi, '')
device_update_interfaces_api.add_resource(DeviceUpdateInterfacesApi, '')
device_cert_api.add_resource(DeviceCertApi, '')
Beispiel #6
0
            elif args['tags_ids'] is not None:
                tags_ids = args['tags_ids']
                offers = filter(
                    lambda offer: any(tag for tag in offer.tags
                                      if tag.tag_id in tags_ids), offers)
                return [offer.to_dict() for offer in offers], 200

            # return [offer.to_dict() for offer in offers], 200
        except Exception as e:
            logger.exception("Offers.get(): %s", str(e))
            return "Couldn't load offers", 500

    @auth_required
    @offers_current_namespace.expect(offer)
    def put(self):
        """Updates current user offer"""
        logger.info("Offers.put() user_id: %s", str(current_user().id))
        try:
            content = json.loads(request.form['data'])
            photo = request.files.get('photo', None)
            photo_url = cloudinary_uploader.upload(
                photo)['url'] if photo else None
            Offer.update_offer(content, photo_url)
            return 'User offer has been updated', 200
        except Exception as e:
            logger.exception("Offers.put(): %s", str(e))
            return "Couldn't update user's offer", 500


offers_current_namespace.add_resource(ProfileOffers, "")
Beispiel #7
0
# src/api/ping.py

from flask_restx import Namespace, Resource

ping_namespace = Namespace("ping")


class Ping(Resource):
    def get(self):
        return {"status": "success", "message": "pong!"}


ping_namespace.add_resource(Ping, "")
Beispiel #8
0
import json
import logging

from flask import current_app as app
from flask_restx import Namespace
from flask_restx import Resource


logger = logging.getLogger(__name__)
health_namespace = Namespace("health")


class Health(Resource):
    @staticmethod
    @health_namespace.response(200, "Health check passing")
    @health_namespace.response(404, "Health check failed")
    def get():
        health = "bad"
        try:
            with open(app.config["HEALTHCHECK_FILE_PATH"], "r") as fp:
                health = fp.read().strip()
                logger.info("Health check passing")
                return json.dumps({"health": health}), 200
        except IOError:
            logger.error("Health check fails", exc_info=True)
            return json.dumps({"health": health}), 404


health_namespace.add_resource(Health, "")
Beispiel #9
0
        response_object = {}

        announcement = get_announcement_by_id(announcement_id)
        if not announcement:
            announcements_namespace.abort(
                404, f"Announcement {announcement_id} does not exist")
        update_announcement(announcement, content)
        response_object["message"] = f"{announcement.id} was updated!"
        return response_object, 200

    @announcements_namespace.response(200, "<announcement_id> was removed!")
    @announcements_namespace.response(
        404, "Announcement <announcement_id> does not exist")
    def delete(self, announcement_id):
        """Updates a announcement."""
        response_object = {}
        announcement = get_announcement_by_id(announcement_id)
        if not announcement:
            announcements_namespace.abort(
                404, f"Announcement {announcement_id} does not exist")
        delete_announcement(announcement)
        response_object["message"] = f"{announcement.id} was removed!"
        return response_object, 200


announcements_namespace.add_resource(AnnouncementsList, "/")
announcements_namespace.add_resource(AnnouncementsListbySponsor,
                                     "/by_sponsor/<string:sponsor_name>")
announcements_namespace.add_resource(Announcements, "/<int:announcement_id>")
Beispiel #10
0
from flask_restx import Namespace

from app.api.adapter.namespaces.rm.routes import RequirementList, RequirementItem

rm_ns = Namespace(name='rm', description='Requirements Management', path='/rm')

rm_ns.add_resource(RequirementList, "/requirement")
rm_ns.add_resource(RequirementItem, "/requirement/<string:id>")
# rm_ns.add_resource(UploadCollection, "/collection")
# rm_ns.add_resource(QueryCapability, "/query_capability", defaults={'query_capability_id': ''})
Beispiel #11
0
class Status(Resource):
    @auth_namespace.marshal_with(user)
    @auth_namespace.response(200, "Success")
    @auth_namespace.response(401, "Invalid token")
    @auth_namespace.expect(parser)
    def get(self):
        auth_header = request.headers.get("Authorization")
        if auth_header:
            try:
                access_token = auth_header.split(" ")[1]
                resp = User.decode_token(access_token)
                user = get_user_by_id(resp)
                if not user:
                    auth_namespace.abort(401, "Invalid token")
                return user, 200
            except jwt.ExpiredSignatureError:
                auth_namespace.abort(
                    401, "Signature expired. Please log in again.")
                return "Signature expired. Please log in again."
            except jwt.InvalidTokenError:
                auth_namespace.abort(401,
                                     "Invalid token. Please log in again.")
        else:
            auth_namespace.abort(403, "Token required")


auth_namespace.add_resource(Register, "/register")
auth_namespace.add_resource(Login, "/login")
auth_namespace.add_resource(Refresh, "/refresh")
auth_namespace.add_resource(Status, "/status")
Beispiel #12
0
        return empty_result(status='success', data=data), 201

    @jwt_required
    def delete(self):
        """ Remove linknet """
        json_data = request.get_json()
        errors = []
        if 'id' not in json_data:
            errors.append("Required field id not found")
        elif not isinstance(json_data['id'], int):
            errors.append("Field id must be an integer")
        if errors:
            return empty_result(status='error', data=errors), 400

        with sqla_session() as session:
            cur_linknet = session.query(Linknet).filter(
                Linknet.id == json_data['id']).one_or_none()
            if not cur_linknet:
                return empty_result(
                    status='error',
                    data="No such linknet found in database"), 404
            session.delete(cur_linknet)
            session.commit()
            return empty_result(
                status="success",
                data={"deleted_linknet": cur_linknet.as_dict()}), 200


# # Links
api.add_resource(LinknetsApi, '')
Beispiel #13
0
                return abort(
                    400, 'Não existe professor com esse ID no banco de dados.')

        if args:
            turma_selected.update(dict(**args))
            db.session.commit()

        return {}, 204

    @api.response(400, 'Não existe turma com esse código no banco de dados.')
    @api.response(204, 'Success')
    def delete(self, codigo):
        '''
        Deleta uma turma com o determinado codigo presente no banco de dados. 
        '''
        turma_selected = Turma.query.filter_by(codigo=codigo)

        if not turma_selected.first():
            return abort(
                400, 'Não existe turma com esse codigo no banco de dados.')

        turma_selected.delete()

        db.session.commit()

        return {}, 204


api.add_resource(rota_acesso_todas_turmas, '/')
api.add_resource(rota_acesso_unico_turmas, '/<string:codigo>/')
Beispiel #14
0
                time_start = datetime.strptime(json_data['start_at'],
                                               date_format)
                time_now = datetime.now()

                if time_start < time_now:
                    return empty_result(status='error',
                                        data='start_at must be in the future')
                time_diff = time_start - time_now
                seconds = time_diff.seconds
            except Exception as e:
                logger.exception(f'Exception when scheduling job: {e}')
                return empty_result(status='error',
                                    data=f'Invalid date format, should be: {date_format}')

        scheduler = Scheduler()
        job_id = scheduler.add_onetime_job(
            'cnaas_nms.confpush.firmware:device_upgrade',
            when=seconds,
            scheduled_by=get_jwt_identity(),
            kwargs=kwargs)
        res = empty_result(data='Scheduled job to upgrade devices')
        res['job_id'] = job_id

        return res


# Firmware
api.add_resource(FirmwareApi, '')
api.add_resource(FirmwareImageApi, '/<string:filename>')
api.add_resource(FirmwareUpgradeApi, '/upgrade')
Beispiel #15
0
        user_record = get_user_by_id(user_id)
        if user_record.get_points_alert and points != event.points:
            try:
                # Req Change 3:
                msg = "You now have " + points + " points in the GoodDriver App."
                send_email(email, "Points updated in GoodDriver App", msg)
            except:
                pass

        response_object["message"] = f"{event.id} was updated!"
        return response_object, 200

    @events_namespace.response(200, "<event_id> was removed!")
    @events_namespace.response(404, "Event <event_id> does not exist")
    def delete(self, event_id):
        """Updates a event."""
        response_object = {}
        event = get_event_by_id(event_id)
        if not event:
            events_namespace.abort(404, f"Event {event_id} does not exist")
        delete_event(event)
        response_object["message"] = f"Event {event.id} was removed!"
        return response_object, 200


events_namespace.add_resource(EventsList, "/")
# events_namespace.add_resource(EventsListbyUser, "/by_user/<int:user_id>")
events_namespace.add_resource(
    EventsListbyUser, "/by_user/<int:user_id>/by_caller/<int:caller_id>")
events_namespace.add_resource(Events, "/<int:event_id>")
Beispiel #16
0
        response_object = {}

        quote = Quote.query.filter_by(content=content).first()
        if quote:
            response_object["message"] = "Sorry, this quote already exists."
            return response_object, 400

        add_quote(author_name, content)
        response_object["message"] = f"quote was added!"
        return response_object, 201


# we dont use marshal with - no information
class RandomQuotes(Resource):

    #@quotes_namespace.marshal_with(quote)
    def get(self):
        """Returns three random quotes with author info"""
        quotes = Quote.query.all()
        quotes_list = []
        for q in quotes:
            quotes_list.append(q.to_dict())

        # random choose three quotes
        randam_quotes = random.sample(quotes_list, k=3)
        return randam_quotes, 200


quotes_namespace.add_resource(Quotes, "")
quotes_namespace.add_resource(RandomQuotes, "/random")
Beispiel #17
0
        if len(shop.get(sku)) == 0:
            product_namespace.abort(404, f"Product (SKU{sku}) does not exist")
        updated_product = Product(sku, name, qty, price)
        shop.update(updated_product)
        response_object["message"] = f"Product (SKU{sku}) was updated!"
        return response_object, 200

    @product_namespace.response(200, "All products have been deleted!")
    def delete(self):
        """deletes all products from shop"""
        shop.delete()
        response_object = {}
        response_object["message"] = "All products deleted!"
        return response_object, 200


class ProductItem(Resource):
    @product_namespace.marshal_with(product)
    @product_namespace.response(200, "Success")
    @product_namespace.response(404, "Product <SKU> does not exist")
    def get(self, sku):
        """Returns a single product."""
        item = shop.get(sku)
        if not item:
            product_namespace.abort(404, f"Product {sku} does not exist")
        return item[0], 200


product_namespace.add_resource(ProductList, "")
product_namespace.add_resource(ProductItem, "/<int:sku>")
Beispiel #18
0
            "hotel_day_count as ( "
            "select distinct hotel_id, count(date) over(PARTITION BY hotel_id) as day_count "
            "from hotel_dates "
            "), "
            "available_hotels as ( "
            "select hotel_id "
            "from hotel_day_count "
            f"where day_count = :day_count "
            ") "
            "select distinct hotel_id "
            "from available_hotels left join hotels on available_hotels.hotel_id = hotels.id; "
        )
        stmt = text(stmt)
        avail_hotels = db.engine.execute(
            stmt,
            checkin=checkin.isoformat(),
            lastnight=lastnight.isoformat(),
            room_types=room_types,
            day_count=day_count,
        ).fetchall()
        avail_hotels = [v[0] for v in avail_hotels]

        # Get hotels with availabilities
        hotel_filters.append(Hotels.id.in_(avail_hotels))
        hotels = db.session.query(Hotels).filter(*hotel_filters).all()

        return hotels


availabilities_ns.add_resource(Availabilities, "", endpoint="availabilities")
Beispiel #19
0
    def get(self, group_name):
        """ Get a single group by name """
        tmpgroups = groups_populate(group_name)
        result = {'groups': tmpgroups}
        return empty_result(status='success', data=result)


class GroupsApiByNameOsversion(Resource):
    @jwt_required
    def get(self, group_name):
        """Get os version of all devices in a group"""
        try:
            group_os_versions = groups_osversion_populate(group_name)
        except ValueError as e:
            return empty_result(
                status='error',
                data="Exception while getting group {}: {}".format(
                    group_name, str(e))), 404
        except Exception as e:
            return empty_result(
                status='error',
                data="Exception while getting group {}: {}".format(
                    group_name, str(e))), 500
        result = {'groups': group_os_versions}
        return empty_result(status='success', data=result)


api.add_resource(GroupsApi, '')
api.add_resource(GroupsApiByName, '/<string:group_name>')
api.add_resource(GroupsApiByNameOsversion, '/<string:group_name>/os_version')
Beispiel #20
0
        return {}, 204

    @api.response(400, 'Não existe turma com esse codigo no banco de dados. \n'
                  'Não existe frequencia com esse ID no banco de dados.')
    @api.response(204, 'Success')
    def delete(self, codigo, frequencia_id):
        '''
        Deleta o registro de uma frequencia com determinado ID
        '''
        if not Turma.query.filter_by(codigo=codigo).first():
            return abort(
                400, 'Não existe turma com esse codigo no banco de dados.')

        frequencia_selected = Frequencia.query.filter_by(id=frequencia_id)

        if not frequencia_selected.first():
            return abort(
                400, 'Não existe frequencia com esse ID no banco de dados.')

        frequencia_selected.delete()

        db.session.commit()

        return {}, 204


api.add_resource(rota_acesso_todas_frequencias,
                 '/<string:codigo>/frequencias/')
api.add_resource(rota_acesso_unico_frequencias,
                 '/<string:codigo>/frequencias/<int:frequencia_id>/')
@api.doc(
    responses={
        401:
        'Token inválida. \n'
        'Token já expirou. \n'
        'O header de autorização não está presente.'
    })
class rota_acesso_erros(Resource):
    @api.response(400, 'Não existe turma com esse código no banco de dados. \n'
                  'Não existe frequência com esse ID no banco de dados.')
    @api.response(200, 'Success', erros_field)
    def get(self, codigo, frequencia_id):
        '''
        Acesso ao registro de correções feitas através da rota PUT para a presença de alunos
        '''
        if not Turma.query.filter_by(codigo=codigo).first():
            return abort(
                400, 'Não existe turma com esse codigo no banco de dados.')

        if not Frequencia.query.filter_by(id=frequencia_id).first():
            return abort(
                400, 'Não existe frequencia com esse ID no banco de dados.')

        erros = AnotacaoErros.query.filter_by(frequencia_id=frequencia_id)

        return ErrosSchema(many=True).dump(erros)


api.add_resource(rota_acesso_erros,
                 '/<string:codigo>/frequencias/<int:frequencia_id>/erros/')
Beispiel #22
0
        """Returns user profile info"""
        try:
            args = parser.parse_args()
            user_id = args['user-id']
            if not user_id:
                user_id = current_user().id
            logger.info("UserProfile.get() user_id: %s", str(user_id))
            return User.get_user_profile_info(user_id), 200
        except Exception as e:
            logger.exception("UserProfile.get(): %s", str(e))
            return "Couldn't load user profile info", 500

    @auth_required
    def put(self):
        """Updates current user profile info"""
        logger.info("UserProfile.put() user_id: %s", str(current_user().id))
        try:
            user_id = current_user().id
            content = json.loads(request.form['data'])
            photo = request.files.get('photo', None)
            photo_url = cloudinary_uploader.upload(
                photo)['url'] if photo else None
            User.update_user_profile_info(user_id, content, photo_url)
            return 'User profile info has been updated', 200
        except Exception as e:
            logger.exception("UserProfile.put(): %s", str(e))
            return "Couldn't update user profile info", 500


user_profile_namespace.add_resource(UserProfile, "")
Beispiel #23
0
        with open('registry.json', 'r') as fd:
            json_data = json.load(fd)

        if json_in['name'] not in json_data:
            json_data['name'] = {}

        json_data['name']['type'] = json_in['type']
        json_data['name']['ip-address'] = json_in['ip-address']
        json_data['name']['room'] = json_in['room']

        with open('registry.json', 'w') as fd:
            fd.write(json.dumps(json_data))


register.add_resource(RegisterApi, '')

app = Flask(__name__)
app.config['SECRET_KEY'] = os.urandom(128)

api = Api(app)
api.add_namespace(register)


@app.route('/dashboard')
def index():
    with open('registry.json', 'r') as fd:
        json_data = json.load(fd)

    return render_template("registry.html", data=json_data)
Beispiel #24
0
    },
)


class accountsList(Resource):
    @accounts_namespace.marshal_with(view_account,
                                     as_list=True,
                                     envelope="data")
    def get(self):
        """Returns all accounts"""
        return get_all_accounts(), 200  # updated

    @accounts_namespace.expect(account, validate=True)
    def post(self):
        """Create new account"""
        post_data = request.get_json()
        email = post_data.get("email")
        password = post_data.get("password")
        response_object = {}

        account = get_account_by_email(email)
        if account:
            response_object["message"] = "Sorry. That email already exists."
            return response_object, 400
        add_account(email, password)  # new
        response_object["message"] = f"{email} registered!"
        return response_object, 201


accounts_namespace.add_resource(accountsList, "")
Beispiel #25
0
def setup_routes(ns: Namespace):
    ns.add_resource(IsConnected, "/isConnected")

    # Bee data
    ns.add_resource(Beedex, "/beedex/<int:id>")
    ns.add_resource(Beedex, "/beedex")
    ns.add_resource(BeeRecord, "/beerecord/<int:id>")
    ns.add_resource(BeeRecordsList, "/beerecords/<int:page>")
    ns.add_resource(BeeVisRecords, "/beevisrecords")
    ns.add_resource(BeeUserRecords, "/beerecorduser")
    ns.add_resource(RecordData, "/record")
    ns.add_resource(NoElevationData, "/noelevationrecords")

    # Flower data -- don't look at me like that! I didn't write the API interface spec!
    ns.add_resource(Flowerdex, "/addflower")  # POST new flower.
    ns.add_resource(Flowerdex, "/flowerdex")  # GET or POST flower.
    ns.add_resource(Flowerdex,
                    "/flowerdex/<int:id>")  # GET or DELETE flower entry
    ns.add_resource(Flowerdex, "/deleteflower/<int:id>")  # DELETE flower.
    ns.add_resource(FlowerList,
                    "/flowerlist")  # Legacy support for flowerlist endpoint
    ns.add_resource(FlowerShapes, "/flowershapes")
    ns.add_resource(
        FlowerShapes,
        "/flowercolors")  # Not a typo, these have the same handler...
    ns.add_resource(UnmatchedFlowers, "/unmatched_flowers")

    # Media upload
    ns.add_resource(UploadImage, "/uploadImage64")
    ns.add_resource(UploadVideo, "/uploadVideo")

    # Login/refresh/logout
    ns.add_resource(Enroll, "/enroll")
    ns.add_resource(Refresh, "/refresh")
    ns.add_resource(Unenroll, "/unenroll")

    # News
    ns.add_resource(UpdateBioCSNews, "/update_biocsnews")
    ns.add_resource(GetBioCSNews, "/biocsnews")
    ns.add_resource(UpdateNews, "/update_news")
    ns.add_resource(GetNews, "/news")

    # Admin
    ns.add_resource(VerifyAdmin, "/verifyAdmin")
Beispiel #26
0
        response_object = {}
        # User validation before deleting
        was_successful, session_token = extract_token(request)
        response_object = {}
        if not was_successful:
            response_object["message"] = session_token
            return response_object, 400
        # Check token validity
        user = get_user_by_session_token(session_token)
        if user is None:
            response_object["message"] = "Invalid token."
            return response_object, 400
        # Create / validate Review object
        user_id = user.id
        review = get_review_by_id(review_id)
        if review is None:
            reviews_namespace.abort(404, f"Review {review_id} does not exist")
        elif user_id != review.user_id:
            reviews_namespace.abort(400, "Cannot delete other user's review")

        if not review:
            reviews_namespace.abort(404, f"Review {review_id} does not exist.")

        delete_review(review)
        response_object["message"] = f"Review {review.id} was deleted."
        return response_object, 200


reviews_namespace.add_resource(ReviewsList, "")
reviews_namespace.add_resource(Reviews, "/<int:review_id>")
Beispiel #27
0
        try:
            pmh = PluginManagerHandler()
            plugindata = pmh.get_plugindata()
            plugin_module_names = pmh.get_plugins()
        except Exception as e:
            return empty_result('error',
                                "Error retrieving plugins {}".format(str(e)))
        else:
            return empty_result('success', {
                'loaded_plugins': plugin_module_names,
                'plugindata': plugindata
            })

    @jwt_required
    @api.expect(plugin_model)
    def put(self):
        """ Modify plugins """
        json_data = request.get_json()
        if 'action' in json_data:
            if str(json_data['action']).upper() == 'SELFTEST':
                pmh = PluginManagerHandler()
                res = pmh.pm.hook.selftest()
                return empty_result('success', {'result': res})
            else:
                return empty_result('error', "Unknown action specified"), 400
        else:
            return empty_result('error', "No action specified"), 400


api.add_resource(PluginsApi, '')
Beispiel #28
0
        try:
            content = json.loads(request.form['data'])
            user_id = current_user().id
            photo = request.files.get('photo', None)
            photo_url = cloudinary_uploader.upload(
                photo)['url'] if photo else None

            for parameter in [
                    'name', 'portions_number', 'longitude', 'latitude',
                    'pickup_times', 'offer_expiry'
            ]:
                if parameter not in content:
                    return f"{parameter} missing in request", 400

            offer_id = Offer.add_offer(
                user_id, content['name'], True, content['portions_number'], 0,
                content['longitude'], content['latitude'], datetime.now(),
                content['pickup_times'], content['offer_expiry'],
                content.get('description', None), photo_url)

            for tag_id in content.get('tags', []):
                OffersTags.add_offer_tag(offer_id, tag_id)
            return "Offer has been added", 201

        except Exception as e:
            logger.exception("Offers.post(): %s", str(e))
            return "Couldn't add offers", 500


offers_namespace.add_resource(Offers, "")
Beispiel #29
0
        if not user:
            users_namespace.abort(404, f"User {user_id} does not exist")

        if get_user_by_email(email):
            response_object["message"] = "Sorry. That email already exists."
            return response_object, 400

        update_user(user, username, email)

        response_object["message"] = f"{user.id} was updated!"
        return response_object, 200

    @users_namespace.response(200, "<user_id> was removed!")
    @users_namespace.response(404, "User <user_id> does not exist")
    def delete(self, user_id):
        """ "Deletes a user."""
        response_object = {}
        user = get_user_by_id(user_id)

        if not user:
            users_namespace.abort(404, f"User {user_id} does not exist")

        delete_user(user)

        response_object["message"] = f"{user.email} was removed!"
        return response_object, 200


users_namespace.add_resource(UsersList, "")
users_namespace.add_resource(Users, "/<int:user_id>")
Beispiel #30
0
        update_order_item(order_item, order_id, catalog_id, catalog_item_id,
                          quantity, actual_cost, points_cost)
        response_object["message"] = f"{order_item.id} was updated!"
        return response_object, 200

    @order_items_namespace.response(200, "<order_item_id> was removed!")
    @order_items_namespace.response(404,
                                    "Order item <order_item_id> does not exist"
                                    )
    def delete(self, order_item_id):
        """Updates an order item."""
        response_object = {}
        order_item = get_order_item_by_id(order_item_id)
        if not order_item:
            order_items_namespace.abort(
                404, f"Order item {order_item_id} does not exist")
        delete_order_item(order_item)
        response_object["message"] = f"Order item {order_item.id} was removed!"
        return response_object, 200


orders_namespace.add_resource(OrdersList, "")
orders_namespace.add_resource(
    OrdersListbyUser, "/by_user/<int:user_id>/by_caller/<int:caller_id>")
# orders_namespace.add_resource(OrdersListbyUser, "/by_user")
orders_namespace.add_resource(Orders, "/<int:order_id>")

order_items_namespace.add_resource(OrderItemsList, "")
order_items_namespace.add_resource(OrderItemsListbyOrder,
                                   "/by_order/<int:order_id>")
order_items_namespace.add_resource(OrderItems, "/<int:order_item_id>")