"""Dog type contract.""" id: str = field(metadata={'marshmallow_field': UUID()}) name: str abbreviation: Optional[str] Schema: ClassVar[Type[mm.Schema]] @hug.cli() @hug.get('/dogs') def dogs() -> Dog.Schema(many=True): """A fake index of dog resources that is randomly generated.""" return [ Dog(id=uuid.uuid1(), name=name, abbreviation=abbrev) for name, abbrev in ( random.choice(list(DOG_TYPES_TO_ABBREVIATIONS.items())) for idx in range(10)) ] @hug.cli() @hug.get('/dogs/{id}') def dog(id: UUID()) -> Dog.Schema(): """A fake dog resource that echos and randomly generates a dog.""" name = random.choice(list(DOG_TYPES_TO_ABBREVIATIONS)) abbrev = DOG_TYPES_TO_ABBREVIATIONS[name] return Dog(id=id, name=name, abbreviation=abbrev) if __name__ == '__main__': hug.API(__name__).cli()
"""An example of using a middleware to require HTTPS connections. requires https://github.com/falconry/falcon-require-https to be installed via pip install falcon-require-https """ import hug from falcon_require_https import RequireHTTPS hug.API(__name__).http.add_middleware(RequireHTTPS()) @hug.get() def my_endpoint(): return "Success!"
# Disable all logging features import logging logging.disable() from meinheld import patch patch.patch_all() import hug hug.API(__name__).http.output_format = hug.output_format.text @hug.get("/") def index(): return "" @hug.get("/user/{id}") def user_info(id): return str(id) @hug.post("/user", methods=["POST"]) def user(): return ""
import hug @hug.get() def weather(): """Returns Its a sunny day to a user""" return { "message": "It\'s a sunny day" } hug.API(__name__).http.serve(port=3000)
def test_context(self): """Test to ensure the hug singleton provides a global modifiable context""" assert not hasattr(hug.API(__name__), '_context') assert hug.API(__name__).context == {} assert hasattr(hug.API(__name__), '_context')
ApiContext.init_globals(os.environ['WMT_CONFIG']) @hug.startup() def init_settings(api): # see https://github.com/hugapi/hug/issues/623 if hasattr(api.http, 'falcon'): api.http.falcon.req_options.auto_parse_qs_csv = False @hug.context_factory() def create_context(*args, **kwargs): return ApiContext() hug.API(__name__).http.add_middleware( hug.middleware.CORSMiddleware(hug.API(__name__))) hug.API(__name__).extend(base, '') if ApiContext.db_config.MAPTYPE == 'routes': from wmt_api.api.listings import routes as listings from wmt_api.api.details import routes as details from wmt_api.api.tiles import routes as tiles elif ApiContext.db_config.MAPTYPE == 'slopes': from wmt_api.api.listings import slopes as listings from wmt_api.api.details import slopes as details from wmt_api.api.tiles import slopes as tiles else: raise RuntimeError( f"No API specified for map type '{ApiContext.db_config.MAPTYPE}'") hug.API(__name__).extend(listings, '/list')
if not debug: msm.removeRests() file_path = os.path.join(temp_dir, 'meico.msm') msm.writeMsm(file_path) elif output == 'midi': midi = msm.exportMidi(float(tempo), not no_program_changes) file_path = os.path.join(temp_dir, 'meico.mid') midi.writeMidi(file_path) elif output == 'wav' or output == 'mp3': midi = msm.exportMidi(float(tempo), not no_program_changes) audio = midi.exportAudio( ) if soundbank is None else midi.exportAudio( File(os.path.join(SB_BASEDIR, SB_FILES[soundbank]))) if output == 'wav': file_path = os.path.join(temp_dir, 'meico.wav') audio.writeAudio(file_path) elif output == 'mp3': file_path = os.path.join(temp_dir, 'meico.mp3') audio.writeMp3(file_path) return file_path except jpype.JavaException as e: print(e.stacktrace()) response.status = HTTP_BAD_REQUEST return {'errors': 'Error during processing of MEI file.'} # Start development server # !!!DO NOT USE IN PRODUCTION!!! if __name__ == '__main__': hug.API(__name__).http.serve(port=8001)
import json import logging import os import sys import jwt import hug from access_control.access_control import admin_authentication, token_key_authentication, verify_user from db.directives import PeeweeContext, PeeweeSession from db.model import FrontendConfig from config import config FORMAT = '%(asctime)s - %(levelname)s\t%(name)s: %(message)s' logging.basicConfig(format=FORMAT, stream=sys.stdout, level=logging.INFO) log = logging.getLogger('appointments') hug_api = hug.API('appointments') hug_api.http.add_middleware(hug.middleware.LogMiddleware()) @hug.post("/login") # noqa def token_gen_call(db: PeeweeSession, body: hug.types.json): """Authenticate and return a token""" secret_key = config.Settings.jwt_key user = verify_user(body['username'], body['password'], context=create_context()) if user: return { "token":
import hug from . import api hug.API(__name__).extend(api) # Public API from .api import get_labels, get_level, get_levels
import hug from cruft import api, logo def _check_command_output(up_to_date: bool) -> None: if not up_to_date: sys.exit( "FAILURE: Project's cruft is out of date! Run `cruft update` to clean this mess up." ) else: print( "SUCCESS: Good work! Project's cruft is up to date and as clean as possible :)." ) def _update_output(updated: bool) -> None: if not updated: print("Nothing to do, project's cruft is already up to date!") else: print( "Good work! Project's cruft has been updated and is as clean as possible!" ) cli = hug.cli(api=hug.API(__name__, doc=logo.ascii_art)) cli(api.create) cli.output(_update_output)(api.update) cli.output(_check_command_output)(api.check)
import hug API = hug.API('git') @hug.object(name='git', version='1.0.0', api=API) @hug.object.urls('/', requires=()) class GIT(object): """An example of command like calls via an Object""" @hug.object.cli def push(self, k, branch='master'): return 'Pushing {}'.format(branch) @hug.object.cli def pull(self, k, branch='master'): return 'Pulling {}'.format(branch) if __name__ == '__main__': API.cli()
return {"status": "OK"} @hug.get('/status') def status(): """Devuelve estado""" return {"status": "OK"} @hug.get('/all') def all(): """Devuelve todos los hitos""" return {"hitos": estos_hitos.todos_hitos()} @hug.get('/one/{id}') def one(id: int): """Devuelve un hito""" return {"hito": estos_hitos.uno(id)} if 'PORT' in os.environ: port = int(os.environ['PORT']) else: port = 8000 api = hug.API(__name__) if __name__ == '__main__': hug.API(__name__).http.serve(port)
@hug.get("/", output=hug.output_format.html) def get_root(response): return dashboard.on_get(persistence_mgr) def plugins_callback(event_id, future): """Attach the value returned by a plugin to the associated event.""" return_val = future.result(0) if return_val is not None: persistence_mgr.attach_info(event_id, return_val) mongodb_uri = config.config.get("server", "MongoDBUri") persistence_mgr = persistence.PersistenceManager(mongodb_uri) executor = ThreadPoolExecutor() plugin_mgr = PluginManager() plugin_mgr.setPluginPlaces(["./counterserver/plugins"]) plugin_mgr.setCategoriesFilter({ IEventReceiverPlugin.__name__: IEventReceiverPlugin, }) plugin_mgr.collectPlugins() for p in plugin_mgr.getAllPlugins(): logging.info("Plugin '" + p.name + "' loaded") if __name__ == '__main__': hug.API(__name__).http.serve()
import hug from falcon import HTTP_400 from gpiozero import OutputDevice # Global constants try: PROBE_PATH = glob('/sys/bus/w1/devices/28*/temperature')[0] except IndexError: exit('Error: Unable to open temperature probe') STATE_PATH = Path('state') DEFAULT_GOAL_TEMP = 90 MAXIMUM_TEMP = 104 # Add CORS middleware api = hug.API(__name__) api.http.add_middleware(hug.middleware.CORSMiddleware(api)) # Set up authentication load_dotenv() USERNAME = getenv('USERNAME') PASSWORD = getenv('PASSWORD') authentication = hug.authentication.basic(hug.authentication.verify(USERNAME, PASSWORD)) def is_float(string): try: float(string) return True except ValueError: return False
def test_singleton(self): """Test to ensure there can only be one hug API per module""" assert hug.API(__name__) == api
global coref global userin global server_reg_key global db_session nlp = nlp_ref # Load en_core_web_sm, English, 50 MB, default model learner = learner_ref omniscient = omniscient_ref dc = dc_ref coref = coref_ref userin = userin_ref server_reg_key = reg_key db_session = db_session_ref app = hug.API(__name__) app.http.output_format = hug.output_format.text app.http.add_middleware(CORSMiddleware(app)) self.waitress_thread = Thread(target=waitress.serve, args=(__hug_wsgi__, ), kwargs={"port": port_number}) if dont_block: self.waitress_thread.daemon = True self.waitress_thread.start() if not dont_block: self.waitress_thread.join() if __name__ == '__main__': app = hug.API(__name__) app.http.output_format = hug.output_format.text app.http.add_middleware(CORSMiddleware(app)) waitress.serve(__hug_wsgi__, port=8000)
def serve(): hug.API(__name__).http.serve(listen_port, display_intro=False)