Code Monkey home page Code Monkey logo

graphql-server's Introduction

PyPI version Coverage Status

GraphQL-Server is a base library that serves as a helper for building GraphQL servers or integrations into existing web frameworks using GraphQL-Core.

Integrations built with GraphQL-Server

Server integration Docs
Flask flask
Sanic sanic
AIOHTTP aiohttp
WebOb (Pyramid, TurboGears) webob

Other integrations built with GraphQL-Server

Server integration Package
WSGI wsgi-graphql
Responder responder.ext.graphql

Other integrations using GraphQL-Core or Graphene

Server integration Package
Django graphene-django

Documentation

The graphql_server package provides these public helper functions:

  • run_http_query
  • encode_execution_results
  • load_json_body
  • json_encode
  • json_encode_pretty

NOTE: the json_encode_pretty is kept as backward compatibility change as it uses json_encode with pretty parameter set to True.

All functions in the package are annotated with type hints and docstrings, and you can build HTML documentation from these using bin/build_docs.

You can also use one of the existing integrations listed above as blueprint to build your own integration or GraphQL server implementations.

Please let us know when you have built something new, so we can list it here.

Contributing

See CONTRIBUTING.md

graphql-server's People

Contributors

aryaniyaps avatar blazewicz avatar carlodri avatar changeling avatar cito avatar dfee avatar ekampf avatar jkimbo avatar kelleyblackmore avatar kiendang avatar kingdarboja avatar koirikivi avatar leonardwellthy avatar lucasrcosta avatar mvanlonden avatar r-owen avatar shinybrar avatar syrusakbary avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

graphql-server's Issues

ModuleNotFoundError: No module named 'jinja2' when importing `graphql_server.aiohttp`

After installation

pip install graphql-server[aiohttp]

with output

...
Successfully installed graphql-core-3.2.0 graphql-server-3.0.0b5 typing-extensions-4.0.1

then attempt to import

from graphql_server.aiohttp import GraphQLView

gives

Traceback (most recent call last):
  File ".../main.py", line 9, in <module>
    from graphql_server.aiohttp import GraphQLView
  File ".../venv/lib/python3.9/site-packages/graphql_server/aiohttp/__init__.py", line 1, in <module>
    from .graphqlview import GraphQLView
  File ".../venv/lib/python3.9/site-packages/graphql_server/aiohttp/graphqlview.py", line 19, in <module>
    from graphql_server.render_graphiql import (
  File ".../venv/lib/python3.9/site-packages/graphql_server/render_graphiql.py", line 7, in <module>
    from jinja2 import Environment
ModuleNotFoundError: No module named 'jinja2'

so it looks like it needs to be included in install_aiohttp_requires?

Update README Integrations: minimal WSGI Application

Since I did not find a minimal implementation to get graphql running as a WSGI Application (without a framework like django or flask) I created one only depending on graphql-server-core.

For the next developer searching for this it might be useful to add wsgi-graphql to Integrations in the README.

Improve README + Docs

  • The README should have some explanation what this package does - "GraphQL Server core package" is not really very informative.

  • It should also list which classes/functions are part of the API (HttpQueryError, default_format_error, encode_execution_results, json_encode, load_json_body, run_http_query)

  • The functions that are part of the official API should all have docstrings.

  • The list of packages that use graphql-server-docs needs to be updated, too

    • graphene-django does not use graphql-server-core at all, contrary to what the README says
    • in addition to flask-graphql, sanic-graphql and webob-graphql, the following packages use it:
    • aiohttp-graphql
    • graphene-sqlalachemy (in flask example)
    • kennethreitz/responder (in graphql extension)
    • moritzmhmk/wsgi-graphql

Variables in get_response() are ignored

To reproduce:

import graphene
import graphql_server

class Query(graphene.ObjectType):
  reverse = graphene.String(word=graphene.String())

  def resolve_reverse(self, info, word):
      return word[::-1]

schema = graphene.Schema(query=Query)

params = graphql_server.GraphQLParams('query { reverse(word: $name) }', {'name': "GraphQl User"}, None)
res = graphql_server.get_response(schema, params)
print(res.data)
print(res.errors)

This gives you

None
[GraphQLError('Variable "$name" is not defined.',)]

I have encountered this error using Flask-GraphQL as any variables I pass via the HTTP request are ignored due to this issue.

Graphql-Server + Graphene + Flask issues

I'm trying to setup flask with graphene and graphql-server. As this is just a test which I am running, I'm using the latest beta releases:

  • graphene: 3.0.0b7
  • graphql-server: 3.0.0b4

Note: I had to use the beta versions of both packages, otherwise I run into dependency issues with graphql-core

Now I found some example which use graphql_server.flask.GraphQLView for the flask views. However, I couldnt use the graphene schema directly, I had to use schema.graphql_schema instead.

  • Is this expected?
  • Are there some side effects of this usage?

The following code is a minimal working example:

from flask import Flask
from graphene import ObjectType, String, Schema
from graphql_server.flask import GraphQLView


class Query(ObjectType):
    hello = String(name=String(default_value='stranger'))
    goodbye = String()

    def resolve_hello(root, info, name):
        return 'Hello {}'.format(name)

    def resolve_goodbye(root, info):
        return 'See ya!'


schema = Schema(query=Query)
app = Flask(__name__)

app.add_url_rule('/graphql', view_func=GraphQLView.as_view(
    'graphql',
    schema=schema.graphql_schema,  # TODO: Check what the consequences are of using the graphql_schema
    graphiql=True,
    graphiql_version='1.3.2'
))

app.add_url_rule('/graphql/batch', view_func=GraphQLView.as_view(
    'graphql_batch',
    schema=schema.graphql_schema,  # TODO: Check what the consequences are of using the graphql_schema
    batch=True
))

if __name__ == '__main__':
    app.run(host='0.0.0.0')

allow validation rules to be passed during schema execution

validation rules are the recommended way to implement things like depth limit validators and other sorts of protectors.
When inspecting the source code, I found out that validation_rules aren't passed as an argument during schema execution. It would be nice if this could be fixed so that we could implement our own validation rules.

execution_results, all_params = run_http_query(
self.schema,
request_method,
data,
query_data=request.args,
batch_enabled=self.batch,
catch=catch,
# Execute options
root_value=self.get_root_value(),
context_value=self.get_context(),
middleware=self.get_middleware(),
)

over here, the http query is run via the run_http_query function.
This method also takes other execution options, as shown below.

def run_http_query(
schema: GraphQLSchema,
request_method: str,
data: Union[Dict, List[Dict]],
query_data: Optional[Dict] = None,
batch_enabled: bool = False,
catch: bool = False,
run_sync: bool = True,
**execute_options,
) -> GraphQLResponse:

Inside the run_http_query method, this function is called.

get_response(
schema, params, catch_exc, allow_only_query, run_sync, **execute_options
)

this function, get_response takes another execution option, validation_rules.
This is not being passed anywhere, and always remains None.

def get_response(
schema: GraphQLSchema,
params: GraphQLParams,
catch_exc: Type[BaseException],
allow_only_query: bool = False,
run_sync: bool = True,
validation_rules: Optional[Collection[Type[ASTValidationRule]]] = None,
max_errors: Optional[int] = None,
**kwargs,
) -> Optional[AwaitableOrValue[ExecutionResult]]:

I will send a PR ASAP!

graphql-server v3.0.0b1 does not work with aiohttp in async mode with graphiql

I had to change graphqlview.py at line 155 as follows

exec_res = (
    [ex if ex is None or isinstance(ex, ExecutionResult) else await ex for ex in execution_results]
    if self.enable_async
    else execution_results
)

from

exec_res = (
    [await ex for ex in execution_results]
    if self.enable_async
    else execution_results
)

Flask - add support for custom execution_context_class argument

I am using Graphene with the Flask graphql integration. Graphql core supports an argument in its execute() function called execution_context_class, among other things as well. I would like to pass a custom ExecutionContext class but it doesn't look like there is a way to do this here in the Flask server integration (and probably the other ones as well).

My use case is that I'd like to use the new UnforgivingExecutionContext added recently in graphene (see graphql-python/graphene#1255), so that I can have better exception handling and Sentry integration in my application.

It seems like this should be an easy fix, I may look into submitting a PR shortly.

Stack traces in graphql errors

Hi,

It would be great for development purpose to include exception stack traces to graphql errors returned by graphql-server.flask when it catches an exception during the execution of a request.

For security reasons, I think it shouldn't be enabled by default, but at least offer the option to do it, since for now, it's just not possible to do.

The only way I found to debut an error is to place a break point in graphql-server.flask.GraphQLView.dispatch_request method in the excpect handler... which is not very convenient.

If you are open to the idea, I can make a PR to poc around this feature.

Queries are parsed twice

Hi,

Just noticed as I was reading trough the codebase that queries are currently parsed twice. Once in get_response and another time by graphql. Ideally, both should share the same document backend so we can keep query parsing to a minimum.

I'm not planning to send a PR as I'm not currently a user of this library. Just wanted to report it in case no one knew about it.

Cheers,
J

Flask version: Black incompatibility

Hello, I want to essentially just ask if there are plans to update Flask to version 2? The reason I ask this is because due to requirements, this library is incompatible with black... a very common python formatter.

Black requires click>=8.0
You require Flask <2
The latest version that matches that, 1.14, requires click<8

With how common black is, I think this a pretty important incompatibility to resolve.
I do notice that dev_requires includes a black version of 19.10b0, however that's a 3 year old prerelease version... I really feel this should be updated.

Add support for Subscriptions

Currently there's no support for GraphQL Subscriptions in the main release. graphql-python/graphql-ws has not been updated for a while. There's an implementation for Subscriptions using WebSocket in the v3 branch. If anyone's interested in the main release of this library supporting GraphQL Subscriptions, either by merging the v3 branch, porting graphql-ws here, or something else, please join the Graphene Discord server to discuss.

RFC: Merge `flask-graphql`, `sanic-graphql` etc into `graphql-server-core`

The problem

Currently server integrations are split into separate repos:

And they are all depend on https://github.com/graphql-python/graphql-server-core

The issue with this is that each framework specific library shares a lot of code with the other libraries and it's hard to coordinate cross cutting changes.

The solution

The suggestion is that we merge the framework specific code into the grapqhl-server-core library so that the code is consolidated into 1 place. That way it's much easier to share code and keep things up to date.

To install the integration with flask for example:

pip install graphql-server-core[flask]

Then you can use it by:

from grapqhl_server.flask import GraphQLView

...

Drawbacks

It will make the graphql-server-core library harder to maintain. At the moment it is very small and easy to test. Merging in the other server libs will make the library become more complex, harder to test (you will need to install all of the dependencies for testing) and easier to accidentally add unneeded dependencies. Any contributions will have to make sure they don't break other server variants supported by the library which they are not familiar with.

Alternatives

We keep the separation of libraries and try and consolidate folder layout and coding standards.

List of packages to merge

I'd like to change how errors are handled

I strongly dislike the fact that this library seems to catch any and all exceptions, and returns them as an error response.

If I have a bug in my resolver code, this should be a 500 error, be tracked to Sentry, and the error message should not be exposed to the user.

If the user makes a mistake in their query, this should be a 400 error, with a clear message, and should not go to Sentry.

As it stands, this library (and thus all the integrations) do not seem to let me do this. I just get an error response, and I'd have to reverse engineer which class of error it is.

Wrong execution return type with syntax errors and return_promise=True

In the presence of syntax errors in the graphql-query, graphql-server does not respect the return_promise execution setting.

The return_promise keyword argument is correctly passed down to graphql-core's graphql-function, such that the ExecutionResults are properly wrapped in a Promise. There was a bug in graphql-core where error-responses would still be unwrapped ExecutionResults, which is already fixed.

However, as the parsing of the query is separate from the actual execution, this does not cover errors due to invalid queries (e.g. because of syntax errors). graphql-server will wrap parsing errors in an ExecutionResult anyway though and return these as such, without looking at the return_promise keyword. I think it's debatable whether parsing errors should be an ExecutionResult at all (seeing as there has been no execution of anything), but as that's the way it is currently implemented at least those should be wrapped in a Promise if the user requested as much.

Module is incompatible with graphql==3.2.0

On import (for instance when running tests) you get

___________________________________________ ERROR collecting tests/test_helpers.py ___________________________________________
ImportError while importing test module '/home/tom/Programming/graphql-server/tests/test_helpers.py'.
Hint: make sure your test modules/packages have valid Python names.
Traceback:
/usr/lib/python3.8/importlib/__init__.py:127: in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
tests/test_helpers.py:8: in <module>
    from graphql_server import (
graphql_server/__init__.py:15: in <module>
    from graphql.error import format_error as format_error_default
E   ImportError: cannot import name 'format_error' from 'graphql.error' (/home/tom/Programming/graphql-server/graphql-server-dev/lib/python3.8/site-packages/graphql/error/__init__.py)

It appears that format_error is now only importable from graphql.error.graphql_error and not graphql.error. It also appears to now be deprecated:
graphql-python/graphql-core@09ff14f

Would you like a PR to fix? If so, would you prefer just a change to the import path, or a dependency bump on graphql-core>=3.2.0 and use of the new method?

Also the README for graphl-core recommends using graphql-core~=3.2.0 so I could also change that.

Support for extensions

In graphene-tornado, we've added support for extensions similar to Apollo Server. These extensions provide the capability to do things like add Apollo Tracing or distributed tracing to requests.

This capability would be great to add to graphql-server-core (it's a blocker for graphene-tornado to migrate). Is there interest in having this functionality in this project? Specifically, I'm suggesting we add the extension points defined here.

Allow contexts provided to resolvers to have attributes

(I filed this issue as graphql-python/graphene-mongo#198 in graphene-mongo, but possibly the solution should be implemented in graphql-server)

A graphql resolver function is provided a context which can hold important information like the currently logged in user or the current HTTP request

In Graphene, graphene-django, graphene-mongo and the old flask-graphql , the context is an object that can have attributes read and written to it (for example context.db.loadHumanByID(args.id) ). However, graphql-server provides a dict that must be accessed by key name e.g. context['request']

If we were programming in Javascript, both syntaxes would work. It would be nice if the context provided by graphql-server could be made more flexible, for instance by making the default context a collections.UserDict.

edit: I see now that the class property context on the GraphQLView can be specified, so that let's me workaround my particular use case

BC change in `json_encode()` breaks flask-graphql

I'm using flask-graphql 2.0.1 My builds broke today without changing a single package version. This is the error I'm getting from the GraphQL server:

[2019-12-06 12:45:23,292] ERROR in app: Exception on / [POST]
Traceback (most recent call last):
  File "/usr/local/lib/python3.7/site-packages/flask/app.py", line 2446, in wsgi_app
    response = self.full_dispatch_request()
  File "/usr/local/lib/python3.7/site-packages/flask/app.py", line 1951, in full_dispatch_request
    rv = self.handle_user_exception(e)
  File "/usr/local/lib/python3.7/site-packages/flask/app.py", line 1820, in handle_user_exception
    reraise(exc_type, exc_value, tb)
  File "/usr/local/lib/python3.7/site-packages/flask/_compat.py", line 39, in reraise
    raise value
  File "/usr/local/lib/python3.7/site-packages/flask/app.py", line 1949, in full_dispatch_request
    rv = self.dispatch_request()
  File "/usr/local/lib/python3.7/site-packages/flask/app.py", line 1935, in dispatch_request
    return self.view_functions[rule.endpoint](**req.view_args)
  File "/usr/local/lib/python3.7/site-packages/flask/views.py", line 89, in view
    return self.dispatch_request(*args, **kwargs)
  File "/usr/local/lib/python3.7/site-packages/flask_graphql/graphqlview.py", line 101, in dispatch_request
    encode=partial(self.encode, pretty=pretty)
  File "/usr/local/lib/python3.7/site-packages/graphql_server/__init__.py", line 172, in encode_execution_results
    return ServerResponse((encode or json_encode)(result), status_code)
TypeError: json_encode() got an unexpected keyword argument 'pretty'

Apparently, flask-graphql, which depends on graphql-server-core>=1.1,<2, relies on the json_encode() method exported by graphql-server-core, and it assumes it accepts a pretty argument. But this argument dissapeared in version 1.1.2 of graphql-server-core (although it's still present on the function docstring): 52b4efc

Release new package version

Loving this awesome and extremely useful package, thank you for maintaining it!

I was hoping to use the ability to pass in custom executors introduced in the following commit, but it appears that the newest published version (1.1.1) was released before that commit was merged.

Would it be possible to release the current master branch any time soon? I'm hoping to avoid having to install from a git commit hash :)

Thanks again!

Exception: NonNull could not have a mounted String() as inner type. Try with NonNull(String).

I'm encountering an issue when upgrading the graphene and graphene-sqlalchemy library versions. The issue arises in the context of defining a GraphQL type.

Error Traceback:

File "/path/to/your/file.py", line X, in <module> class GenericEntity(SQLAlchemyObjectType): File "/path/to/graphene/utils/subclass_with_meta.py", line X, in __init_subclass__ super_class.__init_subclass_with_meta__(**options) File "/path/to/graphene_sqlalchemy/types.py", line X, in __init_subclass_with_meta__ construct_fields( File "/path/to/graphene_sqlalchemy/types.py", line X, in construct_fields field = convert_sqlalchemy_column(attr, registry, resolver, **orm_field.kwargs) File "/path/to/graphene_sqlalchemy/converter.py", line X, in convert_sqlalchemy_column return Field( File "/path/to/graphene/types/field.py", line X, in __init__ type = NonNull(type) File "/path/to/graphene/types/structures.py", line X, in __init__ super(NonNull, self).__init__(*args, **kwargs) File "/path/to/graphene/types/structures.py", line X, in __init__ raise Exception( Exception: NonNull could not have a mounted String() as inner type. Try with NonNull(String).

GraphQL type definition

class GenericEntity(SQLAlchemyObjectType):
    class Meta:
        model = GenericEntityModel
        interfaces = (relay.Node,)
        exclude_fields = ('ordering_user_id',)

Database Model

Base = declarative_base(metadata=metadata)
class GenericEntity(Base):
    __tablename__ = 'generic_entity'

    id = Column(CHAR(32), default=callable(generate_id), primary_key=True, nullable=False)
    name = Column(String(length=MAX_NAME_LEN), nullable=False)
    address = Column(String(MAX_ADD_LEN), nullable=False)
    organization_id = Column(CHAR(32), ForeignKey('organization.id', ondelete='CASCADE'), nullable=False)
    status = Column(Enum(GenericEntityStatusEnum), nullable=False, default=GenericEntityStatusEnum.available)

    creation_datetime = Column(DateTime, nullable=True)

Dependencies:

  • Python: ">=3.9, <3.12"
  • SQLAlchemy: 1.4.51
  • graphene : ">=2.1.3, v3.0.0"
  • graphene-sqlalchemy: ">=2.2.2, v3.0.0rc1"

Same code was working earlier with:
graphene: "2.1.2"
graphene-sqlalchemy = "2.0.0"

Sorry!! Release notes wasn't guiding enough to fix these breaking change introduced in later versions!!

Need some inputs here!

broken support for AsyncioExecutor

The #13 PR introduced executors into request processing for batched queries. It also broken support for use of AsyncioExecutor from within asyncio context.

When using AsyncioExecutor this line blocks forever:

https://github.com/graphql-python/graphql-server-core/blob/427cccb00ae41fb88e8fcaf89aa64f5edb855394/graphql_server/__init__.py#L137

The get() method is called on Promise that must be awaited in async context, here it will stay pending forever.

Call to wait_until_finished() on executor does not help because get_response is not a coroutine and returns a Promise. Async Promises are not handled by wait_until_finished() method of AsyncioExecutor (code). Even if it was, AsyncioExecutor.wait_until_finished() cannot run from within asyncio context and would fail for any asyncio-based application like aiohttp server.

related issue: graphql-python/graphql-core#67

Fix to the above issue introduces a flag return_promise which is just what we need to handle response in async context.

implementatio details:

graphql-python/graphql-core@b4758b1
graphql-python/graphql-core@895b324
graphql-python/graphql-core@cea224a

This fragment of graphql-core test show hows its intended to be used in asyncio context:

https://github.com/graphql-python/graphql-core/blob/a600f7c662e7a6db7d6b56e7c67bf43925b6b23d/tests_py35/core_execution/test_asyncio_executor.py#L65-L75

The return_promise lets the main application handle waiting for executors to finish its task, so graphql-server-core should respect that.

I found this issue in my aiohttp application (using graphql-python/aiohttp-graphql), all queries would block forever. I had to restrict this package version to <=1.1.1

Flask 2 incompatibility

I'm trying to test this with flask, but running into package compatibility issues. Using Python 3.9.6, my requirements.txt is:

Flask
graphene
graphql-server[flask]

which ends up giving me:

$pip freeze
aniso8601==9.0.1
click==8.1.3
Flask==1.1.2
graphene==3.1.1
graphql-core==3.2.3
graphql-relay==3.2.0
graphql-server==3.0.0b5
itsdangerous==2.1.2
Jinja2==3.1.2
MarkupSafe==2.1.1
typing_extensions==4.4.0
Werkzeug==2.2.2

Trying to run my flask app results in

ImportError: cannot import name 'escape' from 'jinja2'

Trying to resolve that issue leads me to https://stackoverflow.com/questions/71718167/importerror-cannot-import-name-escape-from-jinja2:

Jinja is a dependency of Flask and Flask V1.X.X uses the escape module from Jinja, however recently support for the escape module was [dropped in newer versions of Jinja](https://jinja.palletsprojects.com/en/3.1.x/changes/#version-3-1-0).

To fix this issue, simply update to the newer version of Flask V2.X.X in your requirements.txt where Flask no longer uses the escape module from Jinja.

Flask==2.1.0
Also, do note that Flask V1.X.X is no longer supported by the team. If you want to continue to use this older version, [this Github issue may help.](https://github.com/pallets/flask/issues/4494)

Setting my requirements to:

Flask>=2.1.0
graphene
graphql-server[flask]

results in

pip freeze
aniso8601==9.0.1
click==8.1.3
Flask==2.2.2
graphene==3.1.1
graphql-core==3.2.3
graphql-relay==3.2.0
graphql-server==3.0.0b4
importlib-metadata==5.1.0
itsdangerous==2.1.2
Jinja2==3.1.2
MarkupSafe==2.1.1
typing-extensions==3.10.0.2
Werkzeug==2.2.2
zipp==3.11.0

then running my app results in

Traceback (most recent call last):
  File "main.py", line 3, in <module>
    from graphql_server.flask import GraphQLView
  File "env/lib/python3.9/site-packages/graphql_server/__init__.py", line 15, in <module>
    from graphql.error import format_error as format_error_default
ImportError: cannot import name 'format_error' from 'graphql.error' 

Trying to resolve this brings me to #85, which says to upgrade to graphql-server 3.0.0b5, so I pin my requirements.txt and when I try to install, I get:

pip install -r requirements.txt 
Requirement already satisfied: Flask>=2.1.0 in ./env/lib/python3.9/site-packages (from -r requirements.txt (line 1)) (2.2.2)
Requirement already satisfied: graphene in ./env/lib/python3.9/site-packages (from -r requirements.txt (line 2)) (3.1.1)
Collecting graphql-server[flask]==3.0.0b5
  Using cached graphql-server-3.0.0b5.tar.gz (45 kB)
Requirement already satisfied: graphql-core<3.3,>=3.2 in ./env/lib/python3.9/site-packages (from graphql-server[flask]==3.0.0b5->-r requirements.txt (line 3)) (3.2.3)
Collecting typing-extensions<5,>=4
  Using cached typing_extensions-4.4.0-py3-none-any.whl (26 kB)
ERROR: Cannot install Flask>=2.1.0 and graphql-server[flask]==3.0.0b5 because these package versions have conflicting dependencies.

The conflict is caused by:
    The user requested Flask>=2.1.0
    graphql-server[flask] 3.0.0b5 depends on flask<2 and >=1

What do I do? graphql-server should be updated to support flask v2 as flask v1 is no longer maintained.

RFC: Inherit Execute Options for GraphQLView Methods

Related to #77.

Currently the execute() method from graphql-core provides several keyword arguments to be passed on, which aren't included at all on such GraphQLView class methods. These can be passed using the **kwargs syntax but should be great to infer from execute() the available options.

So far this is being discussed at PEP-0612 and the tracking issue as this use case was discussed at this typing repository issue.

The only workaround is to manually specify the same types in order to provide each integration with the same capabilities from graphql-core out of the box.

cc @Cito

New version using graphql-core-next instead of graphql-core

We should create a version that uses graphql-core-next instead of graphql-core.

@norman-thomas has already created PR #17 for this and I have also created a private branch for this.

Since this is not fully backward compatible and needs Py 3.6+, this should be done starting with the new major version number 2.0. A branch for maintenance of version 1.x that will be backward compatible should be created from the current master.

But I think we should first discuss the version and naming strategy (graphql-python/graphql-core/issues/241) across projects because this affects serveral other projects, and do some clean-up and maintenance work before we create the new branch (ideally close all pending tickets first).

We should also notify the maintainers of the depending packages of this breaking upgrade.

request.get_data from graphql_server.quart.GraphQLView uses incorrect api

hello. I noticed that when using GraphQLView as follows,

app.add_url_rule(
    '/graphql',
    view_func=GraphQLView.as_view(
        'graphql',
        schema=schema,
        graphiql=True
    )
)

I get the following error:

[2022-09-05 22:37:21,086] ERROR in app: Exception on request POST /graphql
Traceback (most recent call last):
  File "/Users/user/code/python-gql/.venv/lib/python3.9/site-packages/quart/app.py", line 1629, in handle_request
    return await self.full_dispatch_request(request_context)
  File "/Users/user/code/python-gql/.venv/lib/python3.9/site-packages/quart/app.py", line 1654, in full_dispatch_request
    result = await self.handle_user_exception(error)
  File "/Users/user/code/python-gql/.venv/lib/python3.9/site-packages/quart/app.py", line 1099, in handle_user_exception
    raise error
  File "/Users/user/code/python-gql/.venv/lib/python3.9/site-packages/quart/app.py", line 1652, in full_dispatch_request
    result = await self.dispatch_request(request_context)
  File "/Users/user/code/python-gql/.venv/lib/python3.9/site-packages/quart/app.py", line 1697, in dispatch_request
    return await self.ensure_async(handler)(**request_.view_args)
  File "/Users/user/code/python-gql/.venv/lib/python3.9/site-packages/quart/views.py", line 62, in view
    return await current_app.ensure_async(self.dispatch_request)(**kwargs)
  File "/Users/user/code/python-gql/.venv/lib/python3.9/site-packages/graphql_server/quart/graphqlview.py", line 91, in dispatch_request
    data = await self.parse_body()
  File "/Users/user/code/python-gql/.venv/lib/python3.9/site-packages/graphql_server/quart/graphqlview.py", line 173, in parse_body
    refined_data = await request.get_data(raw=False)
TypeError: get_data() got an unexpected keyword argument 'raw'

According to https://pgjones.gitlab.io/quart/reference/source/quart.html, get_data's signature is as follows:

async get_data(cache: bool, as_text: Literal[False], parse_form_data: bool) → bytes
async get_data(cache: bool, as_text: Literal[True], parse_form_data: bool) → str
async get_data(cache: bool = True, as_text: bool = False, parse_form_data: bool = False) → AnyStr

Safe check Schema for Graphene v3

While testing locally the new server-core, I noticed I had to do this on my schema:

graphql-server-flask

Notice the graphql_schema part, I don't remember having to use it but since we assert on run_http_query function that it MUST be a GraphQLSchema, now we are forced to use the attribute graphql_schema of the Schema type.

@jkimbo suggested at the Slack channel to add a little compatibility layer to ensure it will work for both cases:

if not a graphql-core schema class then check if the object has an attribute called graphql_schema and use that instead.

This issue was made as remainder.

Asynchronous Support

I was looking through the code in init.py to try and adapt the "return_promise" option to work with Tornado's IOLoop. I started with the example in the sanic-graphql repository.

Looking through how the graphql-server package uses the promise library it looks like the query is always executed immediately. I believe this is due to the fact that the executor never yields anything for an event loop to iterate on.

I have not used the promise library before so I might be missing something. Could you help me clarify how to use graphql-server asynchronously?

python 3.10+ MutableMapping ImportError

After python 3.9 collections migrate MutableMapping from collections to collections.abc which causes an import error in this library.
I am currently running 3.11 and get the following error message:
image

When I roll my python version back to 3.9 this issue goes away.

☂️ graphql-server v3

Issue to track v3 release:

TODO

  • Upgrade to graphql-core v3
  • Merge separate server integration packages into repo (#34 )
  • Rename package and github repo to graphql-server
  • Add notices to framework specific libraries that they are deprecated and that people should use the graphql-server library
  • Add documentation to README about how to integrate with different frameworks
  • Support latest versions of frameworks (currently some are restricted to older versions):
    • Flask 2
    • Sanic 21
    • Quart 0.16

Stable non-beta release?

Hi there! We love your efforts on this project, and are curious when we might see a non-beta release?

New version of graphql-core breaks package

Description

I am using Flask-GraphQL and since graphql-core:3 was released I get an import error.

  File "app.py", line 3, in <module>
    from flask_graphql import GraphQLView
  File "/usr/local/lib/python3.7/site-packages/flask_graphql/__init__.py", line 1, in <module>
    from .blueprint import GraphQL
  File "/usr/local/lib/python3.7/site-packages/flask_graphql/blueprint.py", line 5, in <module>
    from .graphqlview import GraphQLView
  File "/usr/local/lib/python3.7/site-packages/flask_graphql/graphqlview.py", line 7, in <module>
    from graphql_server import (HttpQueryError, default_format_error,
  File "/usr/local/lib/python3.7/site-packages/graphql_server/__init__.py", line 5, in <module>
    from graphql import get_default_backend
ImportError: cannot import name 'get_default_backend' from 'graphql' (/usr/local/lib/python3.7/site-packages/graphql/__init__.py)

See:

https://raw.githubusercontent.com/graphql-python/graphql-server-core/7ff9553602cf33b5b137eaa6e8bff62dd1377043/graphql_server/__init__.py

Suggested change

Pin dependency to graphql-core==2.2.1 or even better upgrade to newer version of graphql-core.

Workaround

In my case pinning +graphql-core==2.2.1 worked.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.