Пример #1
0
def server(schema, host, port, app_dir):
    sys.path.insert(0, app_dir)

    try:
        schema_symbol = import_module_symbol(schema,
                                             default_symbol_name="schema")
    except (ImportError, AttributeError) as exc:
        message = str(exc)
        raise click.BadArgumentUsage(message)

    if not isinstance(schema_symbol, Schema):
        message = "The `schema` must be an instance of strawberry.Schema"
        raise click.BadArgumentUsage(message)

    reloader = hupper.start_reloader("strawberry.cli.run", verbose=False)
    schema_module = importlib.import_module(schema_symbol.__module__)
    reloader.watch_files([schema_module.__file__])

    app = Starlette(debug=True)
    app.add_middleware(CORSMiddleware,
                       allow_headers=["*"],
                       allow_origins=["*"],
                       allow_methods=["*"])

    graphql_app = GraphQL(schema_symbol, debug=True)

    paths = ["/", "/graphql"]
    for path in paths:
        app.add_route(path, graphql_app)
        app.add_websocket_route(path, graphql_app)

    print(f"Running strawberry on http://{host}:{port}/ 🍓")
    uvicorn.run(app, host=host, port=port, log_level="error")
Пример #2
0
def server(module, host, port):
    sys.path.append(os.getcwd())

    reloader = hupper.start_reloader("strawberry.cli.run", verbose=False)

    schema_module = importlib.import_module(module)

    reloader.watch_files([schema_module.__file__])

    app = Starlette(debug=True)

    app.add_middleware(CORSMiddleware,
                       allow_headers=["*"],
                       allow_origins=["*"],
                       allow_methods=["*"])

    graphql_app = GraphQL(schema_module.schema, debug=True)

    paths = ["/", "/graphql"]

    for path in paths:
        app.add_route(path, graphql_app)
        app.add_websocket_route(path, graphql_app)

    print(f"Running strawberry on http://{host}:{port}/ 🍓")

    uvicorn.run(app, host=host, port=port, log_level="error")
Пример #3
0
def test_client():
    @strawberry.type
    class Query:
        @strawberry.field
        async def hello(self, name: typing.Optional[str] = None) -> str:
            return f"Hello {name or 'world'}"

    async_schema = strawberry.Schema(Query)
    app = GraphQL(async_schema)
    return TestClient(app)
Пример #4
0
def run():
    logging.basicConfig(level=logging.DEBUG)
    app = GraphQL(schema, debug=True)

    async def atask():
        client = TestClient(app)
        q = {"query": "{ hello { message } }"}
        resp = await client.post("/", json=q)
        print(resp.status_code) == 200
        print(resp.json())

    asyncio.run(atask(), debug=True)
Пример #5
0
def main() -> None:
    ip = get_local_ip()

    app = Starlette()

    graphql_app = GraphQL(schema)

    app.add_route("/graphql", graphql_app)
    app.add_websocket_route("/graphql", graphql_app)

    typer.echo(f"App running on http://{ip}:8000/graphql")

    uvicorn.run(app, host="0.0.0.0", port=8000, log_level="error")
Пример #6
0
def make_app(BASE):
    class CatchAll(BaseHTTPMiddleware):
        async def dispatch(self, request: Request, handler):
            request.scope["path"] = BASE  # TODO subscriptions path
            return await handler(request)

    app = Starlette(debug=True)

    app.add_middleware(CORSMiddleware,
                       allow_headers=["*"],
                       allow_origins=["*"],
                       allow_methods=["*"])

    graphql_app = GraphQL(schema, debug=True)

    app.add_route(BASE, graphql_app)
    app.add_websocket_route(BASE, graphql_app)
    app = CatchAll(app)
    return app
Пример #7
0
def test_client_no_graphiql(schema):
    app = GraphQL(schema, graphiql=False)

    return TestClient(app)
Пример #8
0
def test_client_keep_alive(schema):
    app = GraphQL(schema, keep_alive=True, keep_alive_interval=2)

    return TestClient(app)
Пример #9
0
def test_client(schema):
    app = GraphQL(schema, root_value=Query())

    return TestClient(app)
Пример #10
0
    async def asyncSetUp(self):
        try:
            shutil.rmtree(TEST_DIR)
        except FileNotFoundError:
            pass

        os.makedirs(TEST_DIR)
        shutil.copyfile(DEFAULT_SCHEMA,
                        TEST_DIR + '/' + os.path.split(DEFAULT_SCHEMA)[-1])
        network = await Network.create(NETWORK, TEST_DIR, 'byoda')

        # Remaining environment variables used:
        config.server = PodServer(network)
        server = config.server

        global BASE_URL
        BASE_URL = BASE_URL.format(PORT=server.HTTP_PORT)

        await server.set_document_store(DocumentStoreType.OBJECT_STORE,
                                        cloud_type=CloudType.LOCAL,
                                        bucket_prefix='byodatest',
                                        root_dir=TEST_DIR)

        server.paths = network.paths

        account_id = uuid4()
        pod_account = Account(account_id, network)
        await pod_account.paths.create_account_directory()
        await pod_account.load_memberships()

        server.account = pod_account

        # We can't join the service as it doesn't exist in the network
        # so we have to use our own membership logic
        service = Service(network=network,
                          service_id=SERVICE_ID,
                          storage_driver=network.paths.storage_driver)
        service.name = 'jsonschema_test'
        await service.create_secrets(network.services_ca)

        member = Member(SERVICE_ID, pod_account)
        await member.setup()

        member.member_id = UUID(MEMBER_ID)
        pod_account.memberships[SERVICE_ID] = member

        member.tls_secret = MemberSecret(member.member_id, member.service_id,
                                         member.account)
        member.data_secret = MemberDataSecret(member.member_id,
                                              member.service_id,
                                              member.account)

        await member.create_secrets(members_ca=service.members_ca)

        member.data_secret.create_shared_key()

        member.schema = await member.load_schema(
            os.path.split(DEFAULT_SCHEMA)[-1], verify_signatures=False)

        member.data = MemberData(member, member.paths, member.document_store)
        await member.data.save_protected_shared_key()
        member.data.initalize()
        await member.data.save()

        app = Starlette(debug=True)
        graphql_app = GraphQL(member.schema.gql_schema, debug=True)
        for path in ['/', '/graphql']:
            app.add_route(path, graphql_app)

        TestJsonSchema.PROCESS = Process(target=uvicorn.run,
                                         args=(app, ),
                                         kwargs={
                                             'host': '0.0.0.0',
                                             'port': server.HTTP_PORT,
                                             'log_level': 'info'
                                         },
                                         daemon=True)
        TestJsonSchema.PROCESS.start()
        await asyncio.sleep(3)
Пример #11
0
def test_client(async_schema):
    app = GraphQL(async_schema)

    return TestClient(app)
Пример #12
0
def app(schema: "graphene.Schema", prod: bool) -> ASGIApp:
    s = importlib.import_module(schema)
    g = requires("authenticated")(GraphQL(s.schema, debug=not prod))
    app = Starlette(middleware=middleware(prod), routes=routes(g, prod), debug=not prod)
    return app
Пример #13
0
import os

from starlette.applications import Starlette
from starlette.middleware.cors import CORSMiddleware

from strawberry import Schema
from strawberry.asgi import GraphQL
from strawberry.cli.constants import DEBUG_SERVER_SCHEMA_ENV_VAR_KEY
from strawberry.utils.importer import import_module_symbol


app = Starlette(debug=True)
app.add_middleware(
    CORSMiddleware, allow_headers=["*"], allow_origins=["*"], allow_methods=["*"]
)

schema_import_string = os.environ[DEBUG_SERVER_SCHEMA_ENV_VAR_KEY]
schema_symbol = import_module_symbol(schema_import_string, default_symbol_name="schema")

assert isinstance(schema_symbol, Schema)
graphql_app = GraphQL(schema_symbol, debug=True)

paths = ["/", "/graphql"]
for path in paths:
    app.add_route(path, graphql_app)
    app.add_websocket_route(path, graphql_app)
Пример #14
0
    """
    with _answers_file_lock, shelve.open(ANSWERS_DB, 'c',
                                         writeback=True) as db:
        db.clear()


# Schema

schema = strawberry.Schema(
    query=Query,
    mutation=Mutation,
    subscription=Subscription,
)

# App
graphql_app = GraphQL(schema, keep_alive=True, keep_alive_interval=2)

routes = [
    Route('/', graphql_app),
    WebSocketRoute("/", graphql_app),  # <-- OMG!
]

middleware = [
    Middleware(CORSMiddleware, allow_origins=['*'], allow_methods=['*']),
]

app = Starlette(
    routes=routes,
    middleware=middleware,
)
Пример #15
0
from starlette.applications import Starlette
from starlette.routing import Route
from strawberry.asgi import GraphQL

from schema import schema

app = Starlette(
    debug=True,
    routes=[
        Route("/graphql", GraphQL(schema)),
    ],
)
Пример #16
0
import strawberry
from fastapi import FastAPI
from strawberry.asgi import GraphQL


@strawberry.type
class User:
    name: str
    age: int


@strawberry.type
class Query:
    @strawberry.field
    def user(self) -> User:
        return User(name="Patrick", age=100)


schema = strawberry.Schema(query=Query)

graphql_app = GraphQL(schema)

app = FastAPI()
app.add_route("/graphql", graphql_app)
app.add_websocket_route("/graphql", graphql_app)
Пример #17
0
from starlette.applications import Starlette
from starlette.routing import Route
from strawberry.asgi import GraphQL

from schema import schema

routes = [Route('/graphql', endpoint=GraphQL(schema, graphiql=True))]

app = Starlette(debug=True, routes=routes)
        return libraries[index]

    def resolve_storage(self, info):
        return storage

    def resolve_search(self, info, contains):
        search_books = [b for b in books if contains in b.name]
        search_magazines = [m for m in magazines if contains in m.name]
        return search_books + search_magazines

    def resolve_hello(self, info):
        return "Hello!"

    def resolve_echo(self, info, echo):
        return echo

    def resolve_error(self, info) -> str:
        raise RuntimeError("Runtime Error!")


@strawberry.type
class Mutation:
    @strawberry.mutation
    def storage_add(self, string: str) -> str:
        storage.append(string)
        return str(string)


_target_application = Schema(query=Query, mutation=Mutation, config=StrawberryConfig(auto_camel_case=False))
_target_asgi_application = GraphQL(_target_application)