예제 #1
0
파일: happbase.py 프로젝트: gauravr/userdb
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
파일: app.py 프로젝트: ppinette/hug_website
"""hug's website: hug.rest"""
from functools import partial

import hug

from hug_website import controllers

dual_output = hug.output_format.suffix({'/js': hug.output_format.json},
                                       hug.output_format.html)
app = hug.get(output=dual_output,
              on_invalid=hug.redirect.not_found).suffixes('/js')
html = partial(hug.transform.suffix, {'/js': None})


@hug.static('/static', cache=True)
def static_files():
    return ('hug_website/static', )


@hug.not_found(transform=html(controllers.frame), output=dual_output)
def drop_bear():
    return root('not_found')


@app.transform(html(controllers.frame),
               urls=('/', '/website/{page_name}/{section}',
                     '/website/{page_name}'))
def root(page_name: hug.types.one_of(
    ('home', 'contribute', 'quickstart', 'discuss', 'not_found',
     'learn')) = 'home',
         section: hug.types.one_of(controllers.DOCUMENTATION_TEMPLATES.keys()
예제 #3
0
파일: demo.py 프로젝트: biyaa/pyweb
"""
    web.demo
    ~~~~~~~~
    Created on 2017-02-20 16:54
    @author : huangguoxiong
    copyright: (c) 2017 by huangguoxiong.
    license: Apache license, see LICENSE for more details.
"""

import numpy as np
import time
import random as rd
import hug
import os
cmd_cur_id = rd.randint(9,999999)
api = hug.get(on_invalid=hug.redirect.not_found)
html = hug.get(output=hug.output_format.html)


def set_p(pid):
    with open('p.io','w') as p:
        p.write(str(pid))
        p.write('\n')

def get_r(cid):
    result_a = None
    with open('r.io','r') as r:
        lines = r.readlines()
        print(lines)
        cmd_id = lines[0][:-1]
        print(cmd_id)
예제 #4
0
import hug

from datetime import datetime

# Create decorators for mimetypes (JSON is default)
plaintext = hug.get(output=hug.output_format.text)
json = hug.get(output=hug.output_format.json)


# Create a directive to add necessary headers
@hug.response_middleware()
def set_required_headers(request, response, resource):
    date_obj = datetime.now()
    rfc_1123 = "%a, %d %b %Y %H:%M:%S GMT"
    rfc_1123_date = date_obj.strftime(rfc_1123)

    headers = {"Server": "hug", "Date": rfc_1123_date}

    response.set_headers(headers)


@plaintext
@hug.get("/plaintext")
def plaintext():
    """Plaintext handler."""
    return "Hello, World!"


app = hug.API(__name__).http.server()
예제 #5
0
파일: external.py 프로젝트: a523/learn-hug
import hug
import internal

# 方法一:
# router = hug.route.API(__name__)
# router.get('/home')(internal.root)

# 方法二:
api = hug.API(__name__)
hug.get('/home', api=api)(internal.root)
예제 #6
0
파일: happbase.py 프로젝트: gauravr/userdb
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)
예제 #7
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)
예제 #8
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)
예제 #9
0
#! /usr/bin/env python
"""Executable hello world example powered by hug.

See https://github.com/timothycrosley/hug for more extensive details about
how to use hug.

Note kwargs are not support for cli usage, per
https://github.com/timothycrosley/hug/issues/321
"""

import hug

sagen = hug.get(
    output=hug.output_format.text,
    examples='names=Hanz&names=Franz',
)


@sagen
@hug.cli()
def hallo(names: hug.types.multiple):
    """Print a German greeting to the cli"""

    return '\n'.join(
        'Hallo {}!'.format(name.capitalize())
        for name in names
    )


@sagen
@hug.cli()
예제 #10
0
import hug

from datetime import datetime


# Create decorators for mimetypes (JSON is default)
plaintext = hug.get(output=hug.output_format.text)
json      = hug.get(output=hug.output_format.json)


# Create a directive to add necessary headers
@hug.response_middleware()
def set_required_headers(request, response, resource):
    date_obj      = datetime.now()
    rfc_1123      = "%a, %d %b %Y %H:%M:%S GMT"
    rfc_1123_date = date_obj.strftime(rfc_1123)

    headers       = { "Server": "hug", "Date": rfc_1123_date }

    response.set_headers(headers)


@plaintext
@hug.get("/plaintext")
def plaintext():
    """Plaintext handler."""
    return "Hello, World!"

app = hug.API(__name__).http.server()
예제 #11
0
 def decorator(f):
     return hug.get(output=output)(hug.cli(output=output)(func))
예제 #12
0
import base64

import hug
import markdown

from adventure.app import Adventure
from adventure.output import MarkdownPassthru

from .models import init_db
from .session_store import AdventureSessionStore
from .settings import settings
from .template_loader import get_template


html = hug.get(output=hug.output_format.html)
api = hug.API(__name__)
api.http.add_middleware(
    hug.middleware.SessionMiddleware(
        AdventureSessionStore(), cookie_secure=False, cookie_http_only=False
    )
)
init_db(settings.DATABASE_URL)


@hug.get("/HEALTH-CHECK")
def health_check():
    """simple health status check page"""
    return {"status": "okay"}


@html.urls("/")
예제 #13
0
파일: main.py 프로젝트: roddux/ArCTFurious
# main.py
# The main router for the web app
import hug
import arctfurious.scoreboard as scoreboard
import arctfurious.ctf as ctf
import arctfurious.register as register
import arctfurious.globals as globals

api = hug.API(__name__)

# Static files
hug.get(
    "/register.html", api=api,
    output=hug.output_format.file)(lambda: "arctfurious/html/register.html")
hug.get("/register.js", api=api,
        output=hug.output_format.file)(lambda: "arctfurious/html/register.js")
hug.get(
    "/scoreboard.html", api=api,
    output=hug.output_format.file)(lambda: "arctfurious/html/scoreboard.html")
hug.get(
    "/scoreboard.js", api=api,
    output=hug.output_format.file)(lambda: "arctfurious/html/scoreboard.js")
hug.get("/code.html", api=api,
        output=hug.output_format.file)(lambda: "arctfurious/html/code.html")
hug.get("/code.js", api=api,
        output=hug.output_format.file)(lambda: "arctfurious/html/code.js")
hug.get("/styles.css", api=api,
        output=hug.output_format.file)(lambda: "arctfurious/html/styles.css")
hug.get("/promeo.woff2", api=api,
        output=hug.output_format.file)(lambda: "arctfurious/html/promeo.woff2")
예제 #14
0
import argparse
import os

import eri.logging as logging
import hug
import jinja2


# ----------------------------- #
#   Module Constants            #
# ----------------------------- #

logger = logging.getLogger(__name__)
logging.configure()

html = hug.get(output=hug.output_format.html)

HERE = os.path.dirname(os.path.realpath(__file__))
TEMP_DIR = os.path.join(HERE, 'templates')
JINJA_ENV = jinja2.Environment(loader=jinja2.FileSystemLoader(TEMP_DIR))


# ----------------------------- #
#   routes                      #
# ----------------------------- #

@hug.cli()
@hug.get(examples='name=Zach&age=31')
@hug.local()
def happy_birthday(name: hug.types.text, age: hug.types.number, hug_timer=3):
    """says happy bday to a user"""
예제 #15
0
"""hug's website: hug.rest"""
from functools import partial

import hug

from hug_website import controllers

dual_output = hug.output_format.suffix({'/js': hug.output_format.json}, hug.output_format.html)
app = hug.get(output=dual_output, on_invalid=hug.redirect.not_found).suffixes('/js')
html = partial(hug.transform.suffix, {'/js': None})


@hug.static('/static', cache=True)
def static_files():
    return ('hug_website/static', )


@hug.not_found(transform=html(controllers.frame), output=dual_output)
def drop_bear():
    return root('not_found')


@app.transform(html(controllers.frame), urls=('/', '/website/{page_name}/{section}', '/website/{page_name}'))
def root(page_name: hug.types.one_of(('home', 'contribute', 'quickstart', 'discuss', 'not_found', 'learn'))='home',
         section: hug.types.one_of(controllers.DOCUMENTATION_TEMPLATES.keys())=controllers.DOCUMENTATION[0][0]):
    if page_name == 'learn' and section:
        content = globals()[page_name](section)
    else:
        content = globals()[page_name]()
    return {'label': 'hug', 'version': hug.__version__,
            'content': content, 'page': page_name}
예제 #16
0
import numpy as np
import pandas as pd
import xarray as xr

import logging
import lfmc.config.debug as dev
logging.basicConfig(filename='/var/log/lfmcserver.log',
                    level=logging.DEBUG,
                    format='%(asctime)s %(levelname)s %(name)s %(message)s')
logger = logging.getLogger(__name__)

api_ = hug.API(__name__)
api_.http.add_middleware(hug.middleware.CORSMiddleware(api_, max_age=10))

api = hug.get(on_invalid=hug.redirect.not_found)

suffix_output = hug.output_format.suffix({
    '.json': hug.output_format.pretty_json,
    '.mp4': hug.output_format.mp4_video,
    '.mov': hug.output_format.mov_video,
    '.nc': hug.output_format.file
})

content_output = hug.output_format.on_content_type(
    {'application/x-netcdf4': hug.output_format.file})


@hug.cli()
@hug.post(('/fuel', '/fuel.json', '/fuel.mp4', '/fuel.mov', '/fuel.nc'),
          versions=1,
예제 #17
0
import hug
import piexif
from cloudinary import uploader
from uuid import uuid4 as generate_id
from config import MESSES_DATASET
from resources import datasets
import controllers
import reverse_geocoder
from functools import partial
from mapbox import Uploader
from multipart import MultipartParser

app = hug.get(output=hug.output_format.suffix(
    {'/js': hug.output_format.json}, hug.output_format.html)).suffixes('/js')
html = partial(hug.transform.suffix, {'/js': None})


@hug.default_input_format('multipart/form-data')
def multipart(body, **header_params):
    """Converts multipart form data into native Python objects"""

    if header_params and 'boundary' in header_params:
        if type(header_params['boundary']) is str:
            header_params['boundary'] = header_params['boundary'].encode()
    parser = MultipartParser(stream=body,
                             boundary=header_params['boundary'],
                             disk_limit=17179869184)
    form = dict(zip([p.name for p in parser.parts()],\
        [(p.filename,p.file) if p.filename else p.file.read().decode() for p in parser.parts()]))
    return form