示例#1
0
def add_resthandlers(url, handlers):
    # get_collection, add_resource, replace_resource, get_resource, edit_resource, delete_resource = handlers
    hug.get(endpoint, api=api)(echo)
    hug.get(endpoint, api=api)(echo)
    hug.post(endpoint, api=api)(echo)
    hug.put(endpoint, api=api)(echo)
    hug.patch(endpoint, api=api)(echo)
示例#2
0
 def setup_endpoints(self):
     """Assign methods to endpoints"""
     hug.post('/login', api=self.api)(self.login)
     hug.post('/passwordResetCode', api=self.api)(self.password_reset_code)
     hug.post(
         '/passwordReset/{password_reset_code}',
         api=self.api)(self.update_password_with_code)
     token_key_authentication = \
         hug.authentication.token(  # pylint: disable=no-value-for-parameter
             self.token_verify)
     hug.put(
         '/password/{user_id}',
         api=self.api,
         requires=token_key_authentication)(self.update_password)
     hug.get(
         '/users/{user_id}',
         api=self.api,
         requires=token_key_authentication)(self.get_user)
     hug.get(
         '/userProfiles/{user_id}',
         api=self.api,
         requires=token_key_authentication)(self.get_user_profile)
     hug.patch(
         '/userProfiles/{user_id}',
         api=self.api,
         requires=token_key_authentication)(self.patch_user_profile)
     hug.get(
         '/people/{person_id}',
         api=self.api,
         requires=token_key_authentication)(self.get_person)
     hug.get(
         '/people',
         api=self.api,
         requires=token_key_authentication)(self.people)
     hug.get(
         '/boards/{board_id}',
         api=self.api,
         requires=token_key_authentication)(self.board)
     hug.get(
         '/boards',
         api=self.api,
         requires=token_key_authentication)(self.get_boards)
     hug.get(
         ('/reportedfeelings/boards/{board_id}'
          '/people/{person_id}/dates/{date}'),
         api=self.api,
         requires=token_key_authentication)(self.get_reported_feeling)
     hug.post(
         ('/reportedfeelings/boards/{board_id}'
          '/people/{person_id}/dates/{date}'),
         api=self.api,
         requires=token_key_authentication)(self.create_reported_feeling)
示例#3
0
def enable_echo(api, endpoint='/echo'):
    hug.get(endpoint, api=api)(echo)
    hug.get(endpoint, api=api)(echo)
    hug.post(endpoint, api=api)(echo)
    hug.put(endpoint, api=api)(echo)
    hug.patch(endpoint, api=api)(echo)
示例#4
0
        output=hug.output_format.file)(lambda: "arctfurious/html/prize1.html")
hug.get("/prize2", api=api,
        output=hug.output_format.file)(lambda: "arctfurious/html/prize2.html")
hug.get("/prize3", api=api,
        output=hug.output_format.file)(lambda: "arctfurious/html/prize3.html")
hug.get("/prize4", api=api,
        output=hug.output_format.file)(lambda: "arctfurious/html/prize4.html")
hug.get("/prize5", api=api,
        output=hug.output_format.file)(lambda: "arctfurious/html/prize5.html")

# Endpoints for the API functions
hug.get(
    "/", api=api,
    output=hug.output_format.file)(lambda: "arctfurious/html/scoreboard.html")
hug.get("/scoreboard", api=api)(scoreboard.scoreboard)
hug.post("/code", api=api)(ctf.code)
hug.post("/register", api=api)(register.register)


# Temporary debug endpoint
def deleteCookies(response=None):
    response.unset_cookie(globals.COOKIENAME)
    return True


hug.get("/dc", api=api)(deleteCookies)

# Redirect all other requests to the scoreboard screen
# TODO: This hack just uses the scoreboard page for 404 errors, figure out how to do this properly
hug.not_found(
    api=api,
示例#5
0
def generate_accessors(schm, version=1, name=None):
    """Will generate GET, POST and PUT/PATCH for the model contained by the schema

    Args:
        schem: a marshmallow-sqlalchemy's Schema instance
        path (str): the path where you will find the ressource if path is None, will use the __tablename__ of the model
        name: A custom name that will be used the path
        version (int): the version of the ressource
    """
    model = schm.Meta.model
    model_name = model.__tablename__ if not name else name

    mapper = sainspect(model)
    pks = mapper.primary_key
    pks_name = tuple(pk.name for pk in pks)

    # /model_name
    path_get_all = "/{}".format(model_name)
    # /model_name/pk1/pk2/.../pkn
    path_get_one = path_get_all + "/{" + "}/{".join(pks_name) + "}"
    path_post = path_get_all
    path_put = path_get_one
    path_delete = path_get_one
    path_delete_all = path_get_all

    def cant_find_ress(kwargs):
        pks_d = {pk: kwargs.get(pk) for pk in pks_name}
        logger.error("Can't find ressource : %r", pks_d)
        return "Can't find any ressource with " + ", ".join("{}={}".format(pk, val) for pk, val in pks_d.items())

    # 1. Create a general get, without any doc
    def get_all(response, **kwargs):
        # Return all instances of the ressource
        logger.debug("Call to get severeals ressources : %r", kwargs)
        insts = schm.filter_instances(kwargs)
        d = schm.dump(insts, many=True).data
        logger.debug("Returning the following ressources : %r", d)
        return d

    def get_one(response, **kwargs):
        # return only one instance of the ressource, according to the pks
        # treat kwarks according pks
        # Get the instance of the model
        logger.debug("Request only one ressource : %r", kwargs)
        try:
            inst = schm.get_instance(kwargs)
        except SQLAlchemyError as err:
            logger.error("Error while getting the requested ressource : %r", err)
            schm.Meta.sqla_session.rollback()
            inst = None

        if not inst:
            response.status = HTTP_400
            logger.debug("Nothing found returning status 400")
            return cant_find_ress(kwargs)

        d = schm.dump(inst).data  # get a JSON using marshmallow
        logger.debug("Returning the founded ressource : %r", d)
        return d

    # 2. Add documentation following a template
    get_one.__doc__ = """Allow to get a {} ressource.""".format(model_name, pks_name)
    get_all.__doc__ = """Allow to get all {} ressources.
    If filters are specified, you can get only a part of the query.
    e.g: .../campaign?id_malette==1 will return every instances of campaign where id_malette==1""".format(model_name)

    # 3. Say to hug that it exists
    hug.get(path_get_one)(get_one)
    hug.get(path_get_all)(get_all)

    # And do the same for POSTs requests
    def post(response, **kwargs):

        logger.debug("Received POST request : %r", kwargs)
        inst, error = schm.load(kwargs)  # create ress in mem
        logger.debug("Created in memory instance of the ressource : %r", inst)

        if error:
            logger.error("Returning 400 status. Something went wrong when creating in memory instance of the ressource based on SQLAlchemy Schema : %r", error)
            response.status = HTTP_400
            return error

        try:
            logger.debug("Trying to commit the new ressource : %r", inst)
            schm.Meta.sqla_session.add(inst)  # add inst to server
            schm.Meta.sqla_session.commit()  # commit to server
            logger.debug("Succesfully commited new ressource : %r", inst)
        except IntegrityError as err:
            schm.Meta.sqla_session.rollback()  # uncommit ! It doesn't works ! :-(
            response.status = HTTP_400
            logger.error("Got IntegrityError from SQLAlchemy : %r", err)
            logger.debug("Returning 400 error.")
            return "IntegrityError ! {}".format(err.args)
        except SQLAlchemyError as err:
            schm.Meta.sqla_session.rollback()  # uncommit ! It doesn't works ! :-(
            response.status = HTTP_400
            logger.error("SQLAclhemy failled when commiting new ressource with following error : %r", err)
            return "Sqlalchemy didn't like it {}".format(err.__class__)

        response.status = HTTP_201
        d = schm.dump(inst).data
        logger.debug("Returning inserted ressource datas : %r", d)
        return schm.dump(inst).data

    post.__doc__ = "Allow to create a new {} ressource".format(model_name)

    hug.post(path_post)(post)

    # And do the same for PUT/PATCHs requests
    def put(response, **kwargs):
        logger.debug("PUT call : %r", kwargs)

        # Find ress
        try:
            logger.debug("Trying to find the ressource that needs to be updated")
            inst = schm.get_instance(kwargs)
        except SQLAlchemyError as err:
            logger.error("SQLAlchemy error while trying to find the ressource for put : %r", err)
            schm.Meta.sqla_session.rollback()  # uncommit ! It doesn't works ! :-(
            inst = None

        if inst is None:
            logger.error("No ressource found for PUT returning 400 status.")
            response.status = HTTP_400
            return cant_find_ress(kwargs)

        # update ressource data
        old_data = schm.dump(inst).data
        old_data.update(kwargs)

        logger.debug("Updating data in memory using SQLAlchemy schema")
        data, error = schm.load(old_data, instance=inst)  # set data in mem

        if error:
            logger.error("Error occured when update ressource with request data in memory based on SQLAlchemy schema : %r", error)
            response.status = HTTP_400
            return error

        try:
            schm.Meta.sqla_session.commit()  # commit to serv
            logger.debug("Ressource succesfully commited to database")
        except SQLAlchemyError as err:
            logger.error("Error when commiting updated resource : %r", err)
            schm.Meta.sqla_session.rollback()  # uncommit ! It doesn't works ! :-(
            response.status = HTTP_400
            return "Sqlalchemy didn't like it {}".format(err.args)

        d = schm.dump(inst).data
        logger.debug("Returning updated ressource : %r", d)
        return d

    put.__doc__ = "Allow to modify a new {} ressource".format(model_name)

    hug.put(path_put)(put)
    hug.patch(path_put)(put)

    # DELETE ressource
    def delete_one(response, **kwargs):
        logger.debug("DELETE call : %r", kwargs)

        # Find ress and delete
        try:
            logger.debug("Trying to find the ressource that needs to be updated")
            inst = schm.get_instance(kwargs)
            schm.Meta.sqla_session.delete(inst)
            schm.Meta.sqla_session.commit()  # commit to serv
        except SQLAlchemyError as err:
            logger.error("SQLAlchemy error while trying to find the ressource for delete : %r", err)
            schm.Meta.sqla_session.rollback()  # uncommit ! It doesn't works ! :-(
            inst = None
            return "SQLAlchemy error while trying to find the ressource for delete : %r" % err

        if inst is None:
            logger.error("No ressource found for PUT returning 400 status.")
            response.status = HTTP_400
            return cant_find_ress(kwargs)

        return {}

    hug.delete(path_delete)(delete_one)

    def delete_all(response, **kwargs):
        # Return all instances of the ressource
        logger.debug("Call to delete severeals ressources : %r", kwargs)
        insts = schm.filter_instances(kwargs)
        try:
            for inst in insts:
                schm.Meta.sqla_session.delete(inst)
            schm.Meta.sqla_session.commit()  # commit to serv
        except SQLAlchemyError as err:
            logger.error("SQLAlchemy error while trying to find the ressource for delete : %r", err)
            schm.Meta.sqla_session.rollback()  # uncommit ! It doesn't works ! :-(
            return "SQLAlchemy error while trying to find the ressource for delete : %r" % err

        return None

    hug.delete(path_delete_all)(delete_all)
#!/usr/bin/env python3
# coding: utf-8
"""

"""

import hug

from ...utils.augmented import AugmentedDict
from ..html import render

get = hug.get(on_invalid=hug.redirect.not_found)
post = hug.post(output=hug.output_format.json)
html = hug.get(output=hug.output_format.html)

CONT = AugmentedDict()


@hug.startup()
def init(*args, **kwargs):
    # init things here. Usually useful to put stuff in the global container CONT
    # eg. CONT.key = value
    pass


@html.urls('/')
def home_page():
    """Home page"""
    return render('default')