def make_app(db: AsyncIOMotorClient = None): try: if not db: db = AsyncIOMotorClient(DB_URL).get_database() graphiql = GraphiQL( # path=MONGOKE_BASE_PATH, default_headers={ "Authorization": "Bearer " + GRAPHIQL_DEFAULT_JWT } if GRAPHIQL_DEFAULT_JWT else {}, default_query=GRAPHIQL_QUERY, ) context = {"db": db, "loop": None} app = TartifletteApp( context=context, engine=engine, path=MONGOKE_BASE_PATH, graphiql=graphiql if not DISABLE_GRAPHIQL else False, ) app = CORSMiddleware( app, allow_origins=["*"], allow_methods=["*"], allow_headers=["*"], ) app = JwtMiddleware(app, ) # app = CatchAll(app,) app = ServerErrorMiddleware(app, ) return app except Exception as e: print('got an error starting the Mongoke server:') print(e) return
def __init__(self, debug=True): type_defs = load_schema_from_path("graphql_server/schema/") schema = make_executable_schema(type_defs, query, mutation, user) self._server = CORSMiddleware(GraphQL(schema, debug=debug), allow_origins=["*"], allow_headers=["*"], allow_methods=["*"])
async def setup(self): schema = make_executable_schema(self.type_defs, self.query, self.subscription, self.mutations) app = CORSMiddleware( GraphQL(schema), allow_origins=["*"], allow_methods=("GET", "POST", "OPTIONS"), ) conf = Config() conf.bind = ["0.0.0.0:8006"] conf.loglevel = "fatal" # to suppress lifespan error LOGGER.info("starting GQL API") try: # also to suppress lifespan error await serve(app, conf) except Exception as e: print(e)
def inner(request: Request, exc: Exception): response = _exception_handler(request, exc) # Since the CORSMiddleware is not executed when an unhandled server exception # occurs, we need to manually set the CORS headers ourselves if we want the FE # to receive a proper JSON 500, opposed to a CORS error. # Setting CORS headers on server errors is a bit of a philosophical topic of # discussion in many frameworks, and it is currently not handled in FastAPI. # See dotnet core for a recent discussion, where ultimately it was # decided to return CORS headers on server failures: # https://github.com/dotnet/aspnetcore/issues/2378 origin = request.headers.get("origin") if origin: # Have the middleware do the heavy lifting for us to parse # all the config, then update our response headers cors = CORSMiddleware( app=None, allow_origins=allow_origins, allow_credentials=allow_credentials, allow_methods=allow_methods, allow_headers=allow_headers, ) # Logic directly from Starlette"s CORSMiddleware: # https://github.com/encode/starlette/blob/master/starlette/middleware/cors.py#L152 response.headers.update(cors.simple_headers) has_cookie = "cookie" in request.headers # If request includes any cookie headers, then we must respond # with the specific origin instead of "*". if cors.allow_all_origins and has_cookie: response.headers["Access-Control-Allow-Origin"] = origin # If we only allow specific origins, then we have to mirror back # the Origin header in the response. elif not cors.allow_all_origins and cors.is_allowed_origin( origin=origin): response.headers["Access-Control-Allow-Origin"] = origin response.headers.add_vary_header("Origin") return response
import os from channels.routing import ProtocolTypeRouter, URLRouter from django.conf.urls import url from django.core.asgi import get_asgi_application from starlette.middleware.cors import CORSMiddleware from GradientServer import settings from GradientServer.channelsmiddleware import TokenAuthMiddleware from api.consumers import LongPollConsumer os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'GradientServer.settings') application = ProtocolTypeRouter({ 'http': URLRouter([ url( r'api/longpoll/', CORSMiddleware(TokenAuthMiddleware(LongPollConsumer.as_asgi()), allow_origins=settings.CORS_ALLOWED_ORIGINS, allow_headers=['*'], allow_methods=['*'])), url(r'', get_asgi_application()), ]), })
import uvicorn from starlette.exceptions import ExceptionMiddleware, HTTPException from starlette.responses import JSONResponse from starlette.routing import Router, Path, PathPrefix from starlette.middleware.cors import CORSMiddleware # this isn't currently working with starlette 0.3.6 on PyPI, but you can import from github. from demo.apps import homepage, chat app = Router([ Path('/', app=homepage.app, methods=['GET']), PathPrefix('/chat', app=chat.app), ]) app = CORSMiddleware(app, allow_origins=['*']) app = ExceptionMiddleware(app) def error_handler(request, exc): return JSONResponse({"detail": exc.detail}, status_code=exc.status_code) app.add_exception_handler(HTTPException, error_handler) if __name__ == '__main__': uvicorn.run(app, host='0.0.0.0', port=8000)
from ariadne import ObjectType, QueryType, gql, make_executable_schema from ariadne.asgi import GraphQL from starlette.middleware import Middleware from starlette.middleware.cors import CORSMiddleware from type_def import type_defs from resolvers import query, mutation # Define types using Schema Definition Language (https://graphql.org/learn/schema/) # Wrapping string in gql function provides validation and better error traceback # Create executable GraphQL schema schema = make_executable_schema(type_defs, [query, mutation]) # Create an ASGI app using the schema, running in debug mode graphQL_app = GraphQL( schema, debug=os.environ.get('DEBUG', True), ) app = CORSMiddleware( graphQL_app, allow_headers=['*'], allow_origins=['*'], allow_methods=['*'], ) if __name__ == "__main__": import uvicorn uvicorn.run(app, host="0.0.0.0", port=os.environ.get('PORT', 8000))
help="path to server configuration file", required=True) parser.add_argument("--schema", help="path to graphql schema file", required=True) args = parser.parse_args() with open(args.config, "r") as file: config = json.load(file) with open(args.schema, "r") as file: schema = file.read() graphql_server = GraphqlServer(schema, engine_config=config['engine-address']) graphql_server.start() server_app = Starlette(debug=True) server_app.mount( "/graphql", CORSMiddleware(graphql_server.get_app(), allow_methods=["*"], allow_origins=["*"], expose_headers=[""])) if __name__ == "__main__": server_address = config["server-address"] uvicorn.run("main:server_app", host=server_address['host'], port=server_address['port'], log_level="debug")
# ) # return response # # # Add CORS headers # @app.middleware("http") # async def add_cors_header(request, call_next): # response = check_routes(request) # if response: # return response # # response = await call_next(request) # print('Adding headers') # response.headers["Access-Control-Allow-Origin"] = ALLOWED_ORIGINS # response.headers["Access-Control-Allow-Methods"] = ALLOWED_METHODS # response.headers["Access-Control-Allow-Headers"] = ALLOWED_HEADERS # return response app.include_router(api_router, prefix="/v1") app_full = CORSMiddleware( app=app, #allow_origins='*', allow_origins=[ "http://localhost", "http://localhost:3000", "http://localhost:5000" ], #allow_origin_regex='https?://.*', allow_credentials=True, allow_methods=["*"], allow_headers=["*"], )
from ariadne.asgi import GraphQL from server.schema import schema from starlette.middleware.cors import CORSMiddleware # https://www.starlette.io/middleware/#corsmiddleware # https://github.com/mirumee/ariadne/issues/104 app = CORSMiddleware(GraphQL(schema, debug=True), allow_origins=['*'], allow_methods=['*'], allow_headers=['*'])
import uvicorn from ariadne import QueryType, gql, make_executable_schema from ariadne.asgi import GraphQL from starlette.middleware.cors import CORSMiddleware type_defs = gql(""" type Query { hello: String! } """) query = QueryType() @query.field("hello") def resolve_hello(_, info): request = info.context["request"] user_agent = request.headers.get("user-agent", "guest") return "Hello, %s!" % user_agent schema = make_executable_schema(type_defs, query) application = app = CORSMiddleware(GraphQL(schema, debug=True), allow_origins=['*'], allow_methods="GET, POST") if __name__ == '__main__': uvicorn.run(app, host="127.0.0.1", port=5000)
action for connection in connections for action in connection["actions"] ] else: all_actions = [] for connection in connections: for action in connection["actions"]: # Older is bigger, will only show action with due dates in da future if datetime.strptime(action["due"], "%c") > datetime.now(): all_actions.append(action) return all_actions @query.field("me") def resolve_me(*_, id): for user in DATABASE["users"]: if user["id"] == int(id): return user return None # Create executable GraphQL schema schema = make_executable_schema(type_defs, query, fallback_resolvers) # Create an ASGI app using the schema, running in debug mode app = CORSMiddleware( GraphQL(schema, debug=True), allow_origins=["http://localhost:3000"], allow_methods=["GET", "POST", "OPTIONS"], )
data = json.loads(raw_data, encoding='utf-8') return data['data']['continents'] @query.field("country") async def resolve_country(obj, info, continentCode, countryCode): async with AIOFile(data_file_path, 'r') as afp: raw_data = await afp.read() data = json.loads(raw_data, encoding='utf-8') continents = data['data']['continents'] continent = next( filterfalse(lambda x: x['code'] != continentCode, continents), None) if continent is None: return None countries = continent['countries'] c = next(filterfalse(lambda x: x['code'] != countryCode, countries), None) return c EXECUTABLE_SCHEMA = make_executable_schema(schema, [query, country]) app = CORSMiddleware(GraphQL(EXECUTABLE_SCHEMA, debug=True), allow_origins=['*'], allow_methods=['*'], allow_headers=['*'])