コード例 #1
0
ファイル: api.py プロジェクト: BillArnold/barnoldjg
    def make_api(self):
        self.before_hooks.extend(self.hooks.optional_request_hooks())
        self.after_hooks.extend(self.hooks.optional_response_hooks())

        api = API(before=self.before_hooks, after=self.after_hooks)

        # Set the default route to the NYI object
        api.add_sink(self.default_route or NYI(before=self.before_hooks,
                                               after=self.after_hooks))

        # Add Error Handlers - ordered generic to more specific
        built_in_handlers = [(Exception, handle_unexpected_errors),
                             (ResponseException, ResponseException.handle),
                             (InvalidTokenError, InvalidTokenError.handle)]

        for ex, handler in built_in_handlers + self._error_handlers:
            api.add_error_handler(ex,
                                  wrap_handler_with_hooks(handler,
                                                          self.after_hooks))

        # Add all the routes collected thus far
        for _, disp in self._dispatchers.items():
            for endpoint, handler in disp.get_routes():
                LOG.debug("Loading endpoint %s", endpoint)
                api.add_route(endpoint, handler)
                api.add_route('%s.json' % endpoint, handler)

        return api
コード例 #2
0
ファイル: echo.py プロジェクト: coreofscience/http-echo
def app(environment=None):
    """
    Create our echo falcon app.
    """
    if environment is None:
        environment = os.environ
    logging.basicConfig()
    logging.getLogger("falcon").setLevel(logging.DEBUG)
    api = API()
    api.add_route("/ping", PingResource())
    api.add_sink(sink(environment))
    return api
コード例 #3
0
def serve(port: int = 3000, root_dir: Opt[str] = None) -> None:
    '''
    Start a server providing access to the records in a directory.
    '''
    root_dir = Path(root_dir or get_conf().root_dir)

    def write_response(req: Request, res: Response) -> None:
        res.content_type = 'application/cbor'
        res.set_header('Access-Control-Allow-Origin', '*')

        if req.path.endswith('/_entry-names'):
            path = root_dir / req.path[1:-len('/_entry-names')]
            if path.is_file(): raise HTTPStatus(HTTP_404)
            res.data = cbor2.dumps(dict(
                type='plain-object',
                content=sorted([
                    re.sub(r'\.h5$', '', p.name) + ('/' if p.is_dir() else '')
                    for p in path.glob('[!_]*')
                ])
            ))

        elif req.path.endswith('/_meta'):
            key = req.path[1:-len('/_meta')]
            res.data = cbor2.dumps(_read_meta(root_dir, key))

        else:
            t_last = float(req.get_param('t_last') or 0) / 1000
            entry = _read(root_dir, req.path[1:], t_last)
            if entry['type'] == 'file':
                res.data = (root_dir / entry['content']).read_bytes()
            else:
                res.data = cbor2.dumps(entry)

        res.status = HTTP_200

    app = API(middleware=[_HandleCORS()])
    app.add_sink(write_response)

    class Server(GunicornApp): # type: ignore
        def load(self) -> API:
            return app
        def load_config(self) -> None:
            self.cfg.set('bind', f'localhost:{port}')
            self.cfg.set('workers', 2 * cpu_count())
    Server().run()
コード例 #4
0
def register(app: falcon.API, sub_path=''):
    app.add_sink(sink, sub_path + '/proxy')
コード例 #5
0
    res.status = HTTP_200


class HandleCORS(object):
    def process_request(self, req: Request, res: Response) -> None:
        res.set_header('Access-Control-Allow-Origin', '*')
        res.set_header('Access-Control-Allow-Methods', '*')
        res.set_header('Access-Control-Allow-Headers', '*')
        res.set_header('Access-Control-Max-Age', 600)
        if req.method == 'OPTIONS':
            raise HTTPStatus(HTTP_200)


wsgi_app = API(middleware=[HandleCORS()])
wsgi_app.add_sink(write_response)

#-- I/O -----------------------------------------------------------------------

_web_dtypes = dict(bool='uint8',
                   uint8='uint8',
                   uint16='uint16',
                   uint32='uint32',
                   uint64='uint32',
                   int8='int8',
                   int16='int16',
                   int32='int32',
                   int64='int32',
                   float16='float32',
                   float32='float32',
                   float64='float64',
コード例 #6
0
def register_routes(app: falcon.API, db_engine: Engine):
    app.add_sink(handle_404, '')
    app.set_error_serializer(json_error_serializer)

    routes: Dict[str, Type[resource.LimitedCollectionResource]] = {
        '/bait':
        resource.BaitCollectionResource,
        '/bait/angler_id/{bait_angler_bait_id}':
        resource.BaitCollectionResource,
        '/bait/item_id/{bait_xivapi_item_id}':
        resource.BaitCollectionResource,
        '/bait/name/{language}/{name}':
        resource.BaitCollectionResource,
        '/fish':
        resource.FishCollectionResource,
        '/fish/angler_id/{fish_angler_fish_id}':
        resource.FishCollectionResource,
        '/fish/item_id/{fish_xivapi_item_id}':
        resource.FishCollectionResource,
        '/fish/name/{language}/{name}':
        resource.FishCollectionResource,
        '/spot':
        resource.SpotCollectionResource,
        '/spot/angler_id/{spot_angler_spot_id}':
        resource.SpotCollectionResource,
        '/spot/{spot_gathering_type}/{spot_gathering_type_unique_id}':
        resource.SpotCollectionResource,
        '/spot/name/{language}/{name}':
        resource.SpotCollectionResource,
        '/comment':
        resource.CommentCollectionResource,
        '/comment/bait':
        resource.BaitCommentCollectionResource,
        '/comment/bait/angler_id/{bait_angler_bait_id}':
        resource.BaitCommentCollectionResource,
        '/comment/bait/item_id/{bait_xivapi_item_id}':
        resource.BaitCommentCollectionResource,
        '/comment/fish':
        resource.FishCommentCollectionResource,
        '/comment/fish/angler_id/{fish_angler_fish_id}':
        resource.FishCommentCollectionResource,
        '/comment/fish/item_id/{fish_xivapi_item_id}':
        resource.FishCommentCollectionResource,
        '/comment/spot':
        resource.SpotCommentCollectionResource,
        '/comment/spot/angler_id/{spot_angler_spot_id}':
        resource.SpotCommentCollectionResource,
        '/comment/spot/{spot_gathering_type}/{spot_gathering_type_unique_id}':
        resource.SpotCommentCollectionResource,
        '/bait_alt_currency':
        resource.BaitAltCurrencyPriceCollectionResource,
        '/bait_alt_currency/angler_id/{bait_angler_bait_id}':
        resource.BaitAltCurrencyPriceCollectionResource,
        '/bait_alt_currency/item_id/{bait_xivapi_item_id}':
        resource.BaitAltCurrencyPriceCollectionResource,
        '/fish_bait_preference':
        resource.FishBaitPreferenceCollectionResource,
        '/fish_bait_preference/bait/angler_id/{bait_angler_bait_id}':
        resource.FishBaitPreferenceCollectionResource,
        '/fish_bait_preference/bait/item_id/{bait_xivapi_item_id}':
        resource.FishBaitPreferenceCollectionResource,
        '/fish_bait_preference/fish/angler_id/{fish_angler_fish_id}':
        resource.FishBaitPreferenceCollectionResource,
        '/fish_bait_preference/fish/item_id/{fish_xivapi_item_id}':
        resource.FishBaitPreferenceCollectionResource,
        '/fish_caught_count':
        resource.FishCaughtCountCollectionResource,
        '/fish_caught_count/angler_id/{fish_angler_fish_id}':
        resource.FishCaughtCountCollectionResource,
        '/fish_caught_count/item_id/{fish_xivapi_item_id}':
        resource.FishCaughtCountCollectionResource,
        '/fish_caught_per_hour':
        resource.FishCaughtPerHourCollectionResource,
        '/fish_caught_per_hour/angler_id/{fish_angler_fish_id}':
        resource.FishCaughtPerHourCollectionResource,
        '/fish_caught_per_hour/item_id/{fish_xivapi_item_id}':
        resource.FishCaughtPerHourCollectionResource,
        '/fish_caught_per_weather':
        resource.FishCaughtPerWeatherCollectionResource,
        '/fish_caught_per_weather/angler_id/{fish_angler_fish_id}':
        resource.FishCaughtPerWeatherCollectionResource,
        '/fish_caught_per_weather/item_id/{fish_xivapi_item_id}':
        resource.FishCaughtPerWeatherCollectionResource,
        '/fish_desynthesis_item':
        resource.FishDesynthesisItemCollectionResource,
        '/fish_desynthesis_item/angler_id/{fish_angler_fish_id}':
        resource.FishDesynthesisItemCollectionResource,
        '/fish_desynthesis_item/item_id/{fish_xivapi_item_id}':
        resource.FishDesynthesisItemCollectionResource,
        '/fish_involved_leve':
        resource.FishInvolvedLeveCollectionResource,
        '/fish_involved_leve/angler_id/{fish_angler_fish_id}':
        resource.FishInvolvedLeveCollectionResource,
        '/fish_involved_leve/item_id/{fish_xivapi_item_id}':
        resource.FishInvolvedLeveCollectionResource,
        '/fish_involved_recipe':
        resource.FishInvolvedRecipeCollectionResource,
        '/fish_involved_recipe/angler_id/{fish_angler_fish_id}':
        resource.FishInvolvedRecipeCollectionResource,
        '/fish_involved_recipe/item_id/{fish_xivapi_item_id}':
        resource.FishInvolvedRecipeCollectionResource,
        '/fish_tug_strength':
        resource.FishTugStrengthCollectionResource,
        '/fish_tug_strength/angler_id/{fish_angler_fish_id}':
        resource.FishTugStrengthCollectionResource,
        '/fish_tug_strength/item_id/{fish_xivapi_item_id}':
        resource.FishTugStrengthCollectionResource,
        '/spot_available_fish':
        resource.SpotAvailableFishCollectionResource,
        '/spot_available_fish/fish/angler_id/{fish_angler_fish_id}':
        resource.SpotAvailableFishCollectionResource,
        '/spot_available_fish/fish/item_id/{fish_xivapi_item_id}':
        resource.SpotAvailableFishCollectionResource,
        '/spot_available_fish/spot/angler_id/{spot_angler_spot_id}':
        resource.SpotAvailableFishCollectionResource,
        '/spot_available_fish/spot/{spot_gathering_type}/{spot_gathering_type_unique_id}':
        (resource.SpotAvailableFishCollectionResource),
        '/spot_bait_fish_catch_info':
        resource.SpotBaitFishCatchInfoCollectionResource,
        '/spot_bait_fish_catch_info/bait/angler_id/{bait_angler_bait_id}':
        (resource.SpotBaitFishCatchInfoCollectionResource),
        '/spot_bait_fish_catch_info/bait/item_id/{bait_xivapi_item_id}':
        (resource.SpotBaitFishCatchInfoCollectionResource),
        '/spot_bait_fish_catch_info/fish/angler_id/{fish_angler_fish_id}':
        (resource.SpotBaitFishCatchInfoCollectionResource),
        '/spot_bait_fish_catch_info/fish/item_id/{fish_xivapi_item_id}':
        (resource.SpotBaitFishCatchInfoCollectionResource),
        '/spot_bait_fish_catch_info/spot/angler_id/{spot_angler_spot_id}':
        (resource.SpotBaitFishCatchInfoCollectionResource),
        '/spot_bait_fish_catch_info/spot/{spot_gathering_type}/{spot_gathering_type_unique_id}':
        (resource.SpotBaitFishCatchInfoCollectionResource),
        '/spot_bait_total_fish_caught':
        resource.SpotBaitTotalFishCaughtCollectionResource,
        '/spot_bait_total_fish_caught/bait/angler_id/{bait_angler_bait_id}':
        (resource.SpotBaitTotalFishCaughtCollectionResource),
        '/spot_bait_total_fish_caught/bait/item_id/{bait_xivapi_item_id}':
        (resource.SpotBaitTotalFishCaughtCollectionResource),
        '/spot_bait_total_fish_caught/spot/angler_id/{spot_angler_spot_id}':
        (resource.SpotBaitTotalFishCaughtCollectionResource),
        '/spot_bait_total_fish_caught/spot/{spot_gathering_type}/{spot_gathering_type_unique_id}':
        (resource.SpotBaitTotalFishCaughtCollectionResource),
        '/spot_effective_bait':
        resource.SpotEffectiveBaitCollectionResource,
        '/spot_effective_bait/bait/angler_id/{bait_angler_bait_id}':
        (resource.SpotEffectiveBaitCollectionResource),
        '/spot_effective_bait/bait/item_id/{bait_xivapi_item_id}':
        (resource.SpotEffectiveBaitCollectionResource),
        '/spot_effective_bait/spot/angler_id/{spot_angler_spot_id}':
        (resource.SpotEffectiveBaitCollectionResource),
        '/spot_effective_bait/spot/{spot_gathering_type}/{spot_gathering_type_unique_id}':
        (resource.SpotEffectiveBaitCollectionResource),
        '/last_updated':
        resource.LastUpdatedCollectionResource
    }

    app.add_route('/', resource.RouteResource(list(routes.keys())))
    app.add_route('/db', resource.DataResource())

    for route_uri, collection in routes.items():
        app.add_route(route_uri, collection(db_engine))