def __init__(self, core, *args, static_folder=None, **kwargs): cors = falcon_cors.CORS(allow_all_origins=True, allow_all_headers=True, allow_all_methods=True) middleware = [cors.middleware, RequireJSON(), JSONTranslator()] # , cors.middleware] super().__init__(*args, middleware=middleware, **kwargs) self.registry = {} for (name, ext) in core.get_extensions_for(kit.APIEndpoint): self.setup_extension(name, ext) self.add_route('/', MainResource()) self.add_route('/_/', IntrospectionResource(self.registry)) if static_folder: sink = StaticSink(static_folder, prefix='/static').on_get self.add_sink(sink, prefix='/static/')
from backend.static_server import IndexServer from falcon_multipart.middleware import MultipartMiddleware from backend.paths import STATIC_DIR from wsgiref import simple_server from socketserver import ThreadingMixIn class ThreadedWSGIServer(ThreadingMixIn, simple_server.WSGIServer): """A WSGI server that has threading enabled.""" pass public_cors = falcon_cors.CORS(allow_all_origins=True, allow_all_headers=True, allow_all_methods=True) api = application = falcon.API( middleware=[public_cors.middleware, MultipartMiddleware()]) api.add_static_route(prefix="/", directory=str(STATIC_DIR)) index = IndexServer() api.add_route('/', index) authenticator = Authenticator() api.add_route('/api/auth', authenticator) accounts = Accounts()
from typing import Optional import falcon import falcon_cors from werkzeug.contrib.profiler import ProfilerMiddleware from werkzeug.serving import run_simple from .openapi import Specification from .resources import autowire_resources __all__ = ["global_cors", "serve"] global_cors = falcon_cors.CORS( allow_all_origins=True, allow_all_methods=True, allow_all_headers=True, ).middleware def serve( api: falcon.API, spec: Optional[Specification]=None, resources: Optional[list]=None, autowire: bool=True, autowire_ignore_errors: bool=True, port: int=8080, local: bool=True, debug: bool=True, profile: bool=True) -> None: logging.basicConfig(level=logging.DEBUG if debug else logging.INFO)
class StatusResource: def on_get(self, req, resp): resp.media = { 'name': 'brightsky', 'version': brightsky.__version__, 'status': 'ok', } def on_head(self, req, resp): pass cors = falcon_cors.CORS( allow_origins_list=settings.CORS_ALLOWED_ORIGINS, allow_all_origins=settings.CORS_ALLOW_ALL_ORIGINS, allow_headers_list=settings.CORS_ALLOWED_HEADERS, allow_all_headers=settings.CORS_ALLOW_ALL_HEADERS, allow_all_methods=True) app = falcon.API(middleware=[cors.middleware]) app.req_options.auto_parse_qs_csv = True app.add_route('/', StatusResource()) app.add_route('/weather', WeatherResource()) app.add_route('/current_weather', CurrentWeatherResource()) app.add_route('/synop', SynopResource()) app.add_route('/sources', SourcesResource()) class StandaloneApplication(BaseApplication):
def on_get(self, req, resp): lat, lon = self.parse_location(req) max_dist = self.parse_max_dist(req) dwd_station_id = req.get_param('dwd_station_id') wmo_station_id = req.get_param('wmo_station_id') source_id = req.get_param_as_int('source_id') with convert_exceptions(): result = query.sources( lat=lat, lon=lon, dwd_station_id=dwd_station_id, wmo_station_id=wmo_station_id, source_id=source_id, max_dist=max_dist, ignore_type=True) self.process_sources(result.get('sources', [])) resp.media = result cors = falcon_cors.CORS(allow_origins_list=settings.CORS_ALLOWED_ORIGINS) app = falcon.API(middleware=[cors.middleware]) app.add_route('/weather', WeatherResource()) app.add_route('/current_weather', CurrentWeatherResource()) app.add_route('/synop', SynopResource()) app.add_route('/sources', SourcesResource()) class StandaloneApplication(BaseApplication): def __init__(self, app_uri, **options): self.app_uri = app_uri self.options = options super().__init__()
def debug_error_handler(ex, req, resp, params): print(ex) raise ex startup_migrations.migrate(config.DATABASE_URL, config.MIGRATIONS_PATH) the_clock = clock.Clock() sql_engine = sqlalchemy.create_engine(config.DATABASE_URL, echo=True) model = model.Model(the_clock, sql_engine) orders_resource = handlers.OrdersResource(model) order_resource = handlers.OrderResource(model) cors_middleware = falcon_cors.CORS( allow_origins_list=config.CLIENTS, allow_headers_list=['Authorization', 'Content-Type'], allow_all_methods=True).middleware app = falcon.API(middleware=[cors_middleware]) if config.ENV != 'PROD': app.add_error_handler(Exception, handler=debug_error_handler) app.add_route('/org/{org_id}/restaurants/{restaurant_id}/orders', orders_resource) app.add_route('/org/{org_id}/restaurants/{restaurant_id}/orders/{order_id}', order_resource) def main(): """Server entry point."""
import json import falcon import falcon_cors from bson import json_util, ObjectId from pymongo import MongoClient from waitress import serve cors = falcon_cors.CORS(allow_all_origins=True) client = MongoClient('#login/password') contacts = client.vueproject.contacts class GetContacts: def on_get(self, req, resp): data = [{ 'id': str(contact['_id']), 'name': contact['name'], 'email': contact['email'], 'phone': contact['phone'] } for contact in contacts.find()] data = json_util.dumps(contacts.find()) data = json.loads(data) resp.body = json.dumps(data) resp.status = falcon.HTTP_200 class RemoveContacts: def on_get(self, req, resp, cont_id):
import falcon import json import logging import time import datetime import falcon_cors import psycopg2 from psycopg2.extras import RealDictCursor cors = falcon_cors.CORS(allow_origins_list=['http://localhost:4200'], allow_all_methods=True, allow_all_headers=True) class Parent(): def __init__(self, connection): self.connection = connection pass def get_body(self, req): return req.stream.read(req.content_length or 0).decode('utf-8') def get_json_body(self, req): try: return json.loads(self.get_body(req)) except json.decoder.JSONDecodeError: raise falcon.HTTPError(falcon.HTTP_400, 'Malformed JSON') def date_handler(self, obj): if hasattr(obj, 'isoformat'): return obj.isoformat()
queues.append({'name': processing_queue, 'items': ret_proc}) resp.body = json.dumps(queues) def on_post(self, req, resp): """Handles POST requests""" resp.status = falcon.HTTP_200 # This is the default status fake_task = req.get_param('task', required=True) ret = r.lpush(work_queue, fake_task) # Todo: exception handling resp.body = ('task added:' + fake_task + 'work queue length: ' + str(ret) + "\n") cors = falcon_cors.CORS( allow_origins_list=['pyzam.com', 'pyz.am', 'http://pyz.am']) falcon_cors.log.get_default_logger().setLevel(logging.DEBUG) # falcon.API instances are callable WSGI apps app = falcon.API(middleware=[cors.middleware]) # Set any urlencoded form posts to be able to be gotten by get_param falcon.RequestOptions.auto_parse_form_urlencoded = True # json.loads(raw_json, encoding='utf-8') # Resources are represented by long-lived class instances tasks = TaskResource() # tasks will handle all requests to the '/tasks' URL path app.add_route('/tasks', tasks) app.add_route('/', MainHandler())
class ProtectedResource(object): def on_get(self, req, resp): '''GET /protected ''' prefix, token = req.get_header('Authorization').split(' ') if prefix != 'Bearer:': raise falcon.HTTPBadRequest('Invalid authorization token.') claims = decode_jwt(token) logger.info(claims) resp.body = claims['username'] init_logging() cors = falcon_cors.CORS( allow_origins_list=['http://localhost:8081', 'https://www.awdyer.com'], allow_all_headers=True, allow_all_methods=True) middleware = [cors.middleware] app = falcon.API(middleware=middleware) app.add_route('/', RootResource()) app.add_route('/protected', ProtectedResource()) app.add_error_handler(Exception, CatchAllHandler.handle) if __name__ == '__main__': # Program can be started with --dev flag log to auto reload when changes are made. dev = '--dev' in sys.argv if dev:
def __init__(self): cors = falcon_cors.CORS(allow_all_origins=True, allow_credentials_all_origins=True, allow_all_headers=True, allow_all_methods=True) super().__init__(cors)