Esempio n. 1
0
File: gql.py Progetto: linuseing/hub
    def __init__(self, core: "Core"):
        self.core = core
        self.type_defs = load_schema_from_path(f"{core.location}/api/schema/")
        # self.add_query("spotifyProgress: String!", self.type_defs)

        self.query.set_field(CORE_VERSION, lambda *_: core.version)
        self.query.set_field(PLUGIN_VERSION, lambda *_: VERSION)
        self.query.set_field(PLUGINS, lambda *_: list(core.plugins.keys()))
        self.query.set_field(VALUE, self.get_value)
        self.query.set_field(AVAILABLE_COMPONENTS,
                             lambda *_: list(core.registry.components.keys()))
        self.query.set_field(
            AVAILABLE_FORMATTER,
            lambda *_: list(map(lambda x: x.gql(), core.io.formatter)),
        )
        self.query.set_field(COMMIT_ID,
                             lambda *_: os.getenv("COMMIT", "unknown"))

        self.query.set_field(ENTITY, self.get_entity)
        self.query.set_field(ENTITIES, self.get_entities)

        self.subscription.set_field(ENTITY, self.entity_subscription)
        self.subscription.set_source(ENTITY, self.entity_subscription_source)

        self.subscription.set_field(VALUE, self.value_subscription)
        self.subscription.set_source(VALUE, self.value_subscription_source)

        self.subscription.set_field(EVENT, self.event_subscription)
        self.subscription.set_source(EVENT, self.event_subscription_source)

        self.mutations.set_field(SET_COMPONENT, self.set_mutation)
        self.mutations.set_field(ACTIVATE_SCENE, self.activate_scene)
Esempio n. 2
0
def test_graphql():
    type_defs = load_schema_from_path('schema.graphql')

    query = QueryType()
    building = ObjectType('Building')
    resident = ObjectType('Resident')

    # test dataset
    rec = building_with_id(None, None, "1")
    assert rec == {'id': '1', 'buildYear': 2009}
    residents = resolve_residents_in_building(rec, None)
    assert len(residents) > 0

    # field holders
    query.set_field('building_with_id', building_with_id)
    building.set_field('residents', resolve_residents_in_building)

    schema = make_executable_schema(type_defs, [building, resident, query])

    q = """{
        building_with_id(_id:"1"){
            id
            residents {
                id
                name
            }
        }
    }
    """
    result = graphql_sync(schema, q)
    pprint(result.data)
    assert result.data['building_with_id']['id'] == '1'
Esempio n. 3
0
 def load_schema(self, config):
     try:
         schema = load_schema_from_path(config.path)
         if schema:
             self.type_defs.append(schema)
             logger.debug("found schema in %s!", config.name)
     except FileNotFoundError:
         pass
Esempio n. 4
0
 def load_schema(self):
     """Load GraphQL schema."""
     if (self.package_path / self.schema_folder).is_dir() and self.schema is None:
         type_defs = [
             load_schema_from_path(self.package_path / f"{self.schema_folder}")
         ]
         if type_defs:
             self.schema = [*type_defs]
Esempio n. 5
0
    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=["*"])
Esempio n. 6
0
    def __init__(self):
        from sagas.conf import resource_path
        self.type_defs = load_schema_from_path(resource_path('schemas.graphql'))
        query = QueryType()
        bucket = ObjectType('Bucket')
        behave = ObjectType('Behave')
        desc = ObjectType('Desc')

        query.set_field('bucket_behaves', bucket_behaves)
        bucket.set_field('behaves', resolve_behaves)
        self.schema = make_executable_schema(self.type_defs, [behave, bucket, query])
Esempio n. 7
0
def create_graphql_asgi_wrapper(debug: bool = False) -> asgi.GraphQL:
    """Loads all schemas files and binds all resolvers to an ariadne ASGI's
    wrapper that is be binded to Starlette's ASGI implementation"""
    type_defs = [load_schema_from_path(schema) for schema in schemas]
    schema = make_executable_schema(type_defs,
                                    snake_case_fallback_resolvers,
                                    *bindings,
                                    directives=directives)
    return asgi.GraphQL(
        schema,
        debug=debug,
        middleware=middlewares,
    )
Esempio n. 8
0
def build_app():

    if "PGCONN" not in os.environ:
        raise Exception("Sorry, I need a connection string!")

    else:

        pgconn = psycopg2.connect(os.environ["PGCONN"])

        schema = make_executable_schema(
            load_schema_from_path("bogus_schema.graphql"),
            query)

        app = GraphQL(schema, debug=True,
            context_value=dict(pgconn=pgconn))

        return app
Esempio n. 9
0
def get_app(db: DataBase = None):
    db = resolve_db(db)
    resolvers = get_resolvers(db)
    types = [
        resolvers[k] for k in [
            'query', 'mutation', 'agent', 'flow', 'task', 'flowrun',
            'uuid_scalar', 'timestamp_scalar', 'json_scalar'
        ]
    ]
    type_defs = load_schema_from_path(SCHEMA_PATH)
    schema = make_executable_schema(type_defs, *types)
    graphql = asgi.GraphQL(schema, middleware=[logging_post_data], debug=True)

    middleware = [
        Middleware(CORSMiddleware, allow_origins=["*"], allow_methods=["*"])
    ]
    app = Starlette(debug=True, middleware=middleware)
    app.mount("/graphql", graphql)

    return app
Esempio n. 10
0
def graphql_server():
    type_defs = load_schema_from_path('schema.graphql')

    query = QueryType()
    continent = ObjectType('Continent')
    country = ObjectType('Country')

    query.set_field('continents', resolver.continents_resolver)
    query.set_field('countries', resolver.countries_resolver)
    query.set_field('country_by_name', resolver.country_by_name_resolver)
    query.set_field('continent_by_name_resolver',
                    resolver.continent_by_name_resolver)

    schema = make_executable_schema(type_defs, [continent, country, query])
    data = request.get_json()
    success, result = graphql_sync(schema,
                                   data,
                                   context_value=None,
                                   debug=app.debug)
    status_code = 200 if success else 400
    return jsonify(result), status_code
Esempio n. 11
0
from ariadne import graphql_sync, make_executable_schema, load_schema_from_path, ObjectType, QueryType
from ariadne.constants import PLAYGROUND_HTML
from flask import Flask, request, jsonify
import resolver as r
from database import init_db


app = Flask(__name__)

type_defs = load_schema_from_path('schema.graphql')

#query = QueryType()
query = ObjectType("Query")
mutation = ObjectType("Mutation")
vehicle = ObjectType("Vehicle")
booking = ObjectType("Booking")


#Set Query fields
query.set_field("vehicle", r.getVehicles)
query.set_field("booking", r.getBookings)

#Set Mutation fields
mutation.set_field("newBooking",r.addBooking)


schema = make_executable_schema(type_defs, [query, booking, vehicle, mutation])

@app.route('/graphql', methods=['GET'])
def playground():
    return PLAYGROUND_HTML, 200
from ariadne import load_schema_from_path
from os import getcwd
from os.path import dirname, basename, isfile, join
import glob

modules = glob.glob(join(dirname(__file__), "*.py"))
__all__ = [
    basename(f)[:-3] for f in modules
    if isfile(f) and not f.endswith('__init__.py')
]

from backend.scraper.queries import *

# Get all the typedefs
scraper_query_schema = load_schema_from_path(
    join(getcwd(), "backend/scraper/queries"))
Esempio n. 13
0
def load_typedef_from_schema():
    type_def = load_schema_from_path(join(dirname(dirname(__file__)), "./gql"))
    type_defs = gql(type_def)
    return type_defs
Esempio n. 14
0
import uvicorn
from ariadne import load_schema_from_path, make_executable_schema
from ariadne.asgi import GraphQL
from starlette.applications import Starlette
from starlette.requests import Request
from starlette.responses import JSONResponse

import prefect_server
from prefect_server.utilities.graphql import mutation, query
from prefect_server.graphql import scalars
from prefect_server.utilities import context
from prefect_server.utilities.logging import get_logger

logger = get_logger("GraphQL Server")
sdl = load_schema_from_path(Path(__file__).parents[2] / "graphql" / "schema")

schema = make_executable_schema(sdl, query, mutation, *scalars.resolvers)

path = prefect_server.config.services.graphql.path or "/"

if not path.endswith("/"):
    path += "/"

# The interaction of how Starlette mounts the GraphQL app appears to result in
# 404's when the path doesn't end in a trailing slash. This means GraphQL queries
# must have a trailing slash
if not path.endswith("/"):
    raise ValueError("GraphQL path must end with '/'")

app = Starlette()
Esempio n. 15
0
    graphql_sync, snake_case_fallback_resolvers, ObjectType
from ariadne.constants import PLAYGROUND_HTML
from flask import request, jsonify
from api.queries import resolve_employees, resolve_emp
from api.mutations import resolve_create_employee

query = ObjectType("Query")
print(resolve_employees)
query.set_field("employees", resolve_employees)
query.set_field("employee", resolve_emp)

print(resolve_create_employee)
mutation = ObjectType("Mutation")
mutation.set_field("createEmployee", resolve_create_employee)

type_defs = load_schema_from_path("employee.graphql")
schema = make_executable_schema(type_defs, query,
                                snake_case_fallback_resolvers)


@app.route("/graphql", methods=["GET"])
def graphql_playground():
    return PLAYGROUND_HTML, 200


@app.route("/graphql", methods=["POST"])
def graphql_server():
    data = request.get_json()
    print("data==>", data)
    success, result = graphql_sync(schema,
                                   data,
Esempio n. 16
0
}


# middleware

middleware = [
    Middleware(AuthenticationMiddleware, backend=TokenAuthenticationBackend())
]


# GraphQL

schema_path = (
    pathlib.Path(__file__).parent.absolute().joinpath("graphql", "schema.graphql")
)
type_defs = load_schema_from_path("saltapi/graphql/schema.graphql")

datetime_scalar = ScalarType("Datetime")
datetime_scalar.set_serializer(scalars.serialize_datetime)
datetime_scalar.set_value_parser(scalars.parse_datetime)

proposal_code_scalar = ScalarType("ProposalCode")
proposal_code_scalar.set_serializer(scalars.serialize_proposal_code)
proposal_code_scalar.set_value_parser(scalars.parse_proposal_code)

mutation = MutationType()
mutation.set_field("submitProposal", resolvers.resolve_submit_proposal)

subscription = SubscriptionType()
subscription.set_field("submissionProgress", resolvers.resolve_submission_progress)
subscription.set_source("submissionProgress", resolvers.submission_progress_generator)
Esempio n. 17
0
from flask import Flask, json, request, jsonify
from ariadne import graphql_sync, make_executable_schema, gql, load_schema_from_path
from ariadne.constants import PLAYGROUND_HTML
from mongoengine import connect

type_defs = gql(load_schema_from_path("./dev/schema/"))
# schema = make_executable_schema(type_defs, query, mutation)
connect("blog")

app = Flask(__name__)


@app.route('/')
def hello_world():
    return 'Hello, world!'


@app.route('/graphql', methods=["GET"])
def graphql_playground():
    return PLAYGROUND_HTML, 200


@app.route("/graphql", methods=["POST"])
def graphql_server():
    data = request.get_json()
    success, result = graphql_sync(schema,
                                   data,
                                   context_value=request,
                                   debug=app.debug)
    status_code = 200 if success else 400
    return jsonify(result), status_code
Esempio n. 18
0
#!/usr/bin/env python3
# server.py
from ariadne import gql, QueryType, make_executable_schema, ObjectType, load_schema_from_path
from ariadne.asgi import GraphQL
import uvicorn

type_defs = load_schema_from_path("ariadne_intro/schema/")

query = QueryType()


@query.field("hello")
def resolve_hello(_, info):
    request = info.context["request"]
    user_agent = request.headers.get("user-agent", "guest")
    return f"Hello, {user_agent}"


class User():
    def __init__(self, username, name):
        self.username = username
        self.name = name
        self.type = ObjectType("User")
        self.type.set_field("username", lambda _, info: self.username)
        self.type.set_field("name", lambda _, info: self.name)


bob = User("bob", "Tomas Bouska")
query.set_field("user", lambda _, info: bob.type)

schema = make_executable_schema(type_defs, query, bob.type)
Esempio n. 19
0
from ariadne import make_executable_schema, load_schema_from_path
from ariadne.asgi import GraphQL
from resolvers import query, skill, person

# import schema from GraphQL file
type_defs = load_schema_from_path("./schema.gql")

schema = make_executable_schema(type_defs, query, skill, person)
app = GraphQL(schema, debug=True)
Esempio n. 20
0
from flask import Flask, request, jsonify
from ariadne import graphql_sync, make_executable_schema, gql, load_schema_from_path
from ariadne.constants import PLAYGROUND_HTML
# The model is where we'll define our resolvers
from model import query

# We'll create this schema soon
type_defs = gql(load_schema_from_path("./schema.graphql"))
schema = make_executable_schema(type_defs, query)

app = Flask(__name__)

@app.route("/graphql", methods=["GET"])
def graphql_playground():
    """Serve GraphiQL playground"""
    return PLAYGROUND_HTML, 200


@app.route("/graphql", methods=["POST"])
def graphql_server():
    data = request.get_json()

    success, result = graphql_sync(
        schema,
        data,
        context_value=request,
        debug=app.debug
    )

    status_code = 200 if success else 400
    return jsonify(result), status_code
from ariadne import load_schema_from_path
from os import getcwd
from os.path import dirname, basename, isfile, join
import glob

modules = glob.glob(join(dirname(__file__), "*.py"))
__all__ = [
    basename(f)[:-3] for f in modules
    if isfile(f) and not f.endswith('__init__.py')
]

from backend.scraper.subscriptions import *

# Get all the typedefs
scraper_subscription_schema = load_schema_from_path(
    join(getcwd(), "backend/scraper/subscriptions"))
Esempio n. 22
0
    return None


@event.field("stateInsight")
async def resolve_event_id(obj, info):
    def decode(key, value):

        if isinstance(value, uuid.UUID):
            return dict(key=key, text=str(value), uuid=value)
        if isinstance(value, datetime.datetime):
            return dict(key=key, text=str(value), datetime=value)
        if key == "timestamp" and isinstance(value, decimal.Decimal):
            dt = datetime.datetime.fromtimestamp(
                value,
                datetime.timezone.utc,
            )
            return dict(key=key, text=str(dt), datetime=dt)

        try:
            return dict(key=key, text=str(value), json=json.dumps(value))
        except TypeError:
            pass

        return dict(key=key, text=str(value))

    return [decode(key, value) for key, value in obj["event"].__dict__.items()]


type_defs = ariadne.load_schema_from_path("gqles/")
schema = ariadne.make_executable_schema(type_defs, *types)
Esempio n. 23
0
    registered_queries,
    registered_subscriptions,
    registered_types,
)


class RequestCacheMiddleware(BaseHTTPMiddleware):
    async def dispatch(self, request, call_next):
        context["cache"] = dict()
        context["cache_disabled"] = False
        return await call_next(request)


MANAGER_ROUTER_INSTALLED_KEY = "pm/manager/installed"

type_defs = ariadne.load_schema_from_path("./schema")
query = ariadne.QueryType()
mutation = ariadne.MutationType()
subscription = ariadne.SubscriptionType()

for name, resolver in registered_queries.items():
    query.set_field(name, resolver)

for name, resolver in registered_mutations.items():
    mutation.set_field(name, resolver)

for name, resolver in registered_subscriptions.items():
    subscription.set_source(name, resolver)
    subscription.set_field(name, lambda f, *_, **__: f if f else None)

schema = ariadne.make_executable_schema(
from ariadne import load_schema_from_path
import os

scraper_type_schema = load_schema_from_path(
    os.path.join(os.getcwd(), "backend/scraper/types"))
Esempio n. 25
0
from ariadne import make_executable_schema, load_schema_from_path
from schemas.resolvers.user_resolvers import user_resolvers
from schemas.resolvers.transaction_resolvers import tranx_resolvers

resolvers = user_resolvers + tranx_resolvers

type_defs = load_schema_from_path("schemas")
schema = make_executable_schema(type_defs, resolvers)
Esempio n. 26
0
File: server.py Progetto: wl44545/al
        if todo["id"] == todo_id:
            del todos[i]
            return {"success": True}
    return {"success": False, "errors": ["Can't find todo"]}


query = ariadne.ObjectType("Query")
query.set_field("todos", resolve_todos)
query.set_field("todo", resolve_todo)

mutation = ariadne.ObjectType("Mutation")
mutation.set_field("createTodo", resolve_create_todo)
mutation.set_field("deleteTodo", resolve_delete_todo)

schema = ariadne.make_executable_schema(
    ariadne.load_schema_from_path("schema.graphql"), query, mutation,
    ariadne.snake_case_fallback_resolvers)


@app.route("/graphql", methods=["GET"])
def graphql_playground():
    data = request.args.get("query")
    if data:
        success, result = ariadne.graphql_sync(schema, {"query": data},
                                               context_value=request,
                                               debug=app.debug)

        status_code = 200 if success else 400
        return jsonify(result), status_code
    return ariadne.constants.PLAYGROUND_HTML, 200
Esempio n. 27
0
import os
import os.path
import pathlib
import asyncio

from graphql import parse
from ariadne import MutationType, SubscriptionType, load_schema_from_path

from nomine.models import Namer
from nomine.models.folder_entry import FolderEntry, FILE_TYPE, DIRECTORY_TYPE

mutation = MutationType()
subscription = SubscriptionType()
bindables = [mutation, subscription]
schema_file = load_schema_from_path(
    pathlib.Path(__file__).parent.joinpath("schema.graphql").absolute())
schema = parse(schema_file)
queue = asyncio.Queue()


def get_or_create_entry(session, folder_id, dir_entry):
    if dir_entry.is_file():
        entry_type = FILE_TYPE
    elif dir_entry.is_dir():
        entry_type = DIRECTORY_TYPE
    else:
        return

    existing = (session.query(FolderEntry).filter(
        FolderEntry.path == dir_entry.path).first())
    if existing:
Esempio n. 28
0
import os

from ariadne import QueryType, load_schema_from_path, make_executable_schema

from .analytics import analytics
from .status import status
from .versioncheck import version_check

FILE_PATH = os.path.dirname(os.path.abspath(__file__))
SCHEMA_PATH = os.path.join(FILE_PATH, "schema.graphql")

type_defs = load_schema_from_path(SCHEMA_PATH)
schema = make_executable_schema(type_defs, [analytics, status, version_check])
Esempio n. 29
0
from ariadne import load_schema_from_path
from ariadne.contrib.django.views import GraphQLView
from ariadne.contrib.federation import make_federated_schema

from parking_permits import admin_resolvers, resolvers
from parking_permits.error_formatter import error_formatter
from project.settings import BASE_DIR

type_defs = load_schema_from_path(BASE_DIR / "parking_permits" / "schema" /
                                  "parking_permit.graphql")
schema = make_federated_schema(type_defs, resolvers.schema_bindables)
view = GraphQLView.as_view(schema=schema, error_formatter=error_formatter)

admin_type_defs = load_schema_from_path(
    BASE_DIR / "parking_permits" / "schema" / "parking_permit_admin.graphql")
schema = make_federated_schema(admin_type_defs,
                               admin_resolvers.schema_bindables)
admin_view = GraphQLView.as_view(schema=schema,
                                 error_formatter=error_formatter)
Esempio n. 30
0
import os
from ariadne import make_executable_schema, load_schema_from_path

from client_api.mutations import mutation
from client_api.queries import query

type_defs = load_schema_from_path(os.path.abspath("client_api/schema.graphql"))

schema = make_executable_schema(type_defs, [query, mutation])