-
Notifications
You must be signed in to change notification settings - Fork 72
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Initial version of the GraphQL server core package
- Loading branch information
0 parents
commit 33debff
Showing
14 changed files
with
934 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,10 @@ | ||
*.pyc | ||
.idea | ||
.cache | ||
.tox | ||
*.egg | ||
*.egg-info | ||
.coverage | ||
/build/ | ||
|
||
/dist/ |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,31 @@ | ||
language: python | ||
sudo: false | ||
matrix: | ||
include: | ||
- python: pypy | ||
env: TOX_ENV=pypy | ||
- python: '2.7' | ||
env: TOX_ENV=py27 | ||
- python: '3.3' | ||
env: TOX_ENV=py33 | ||
- python: '3.4' | ||
env: TOX_ENV=py34 | ||
- python: '3.5' | ||
env: TOX_ENV=py35,import-order,flake8 | ||
cache: | ||
directories: | ||
- $HOME/.cache/pip | ||
- $TRAVIS_BUILD_DIR/.tox | ||
install: | ||
- pip install tox coveralls | ||
script: | ||
- tox -e $TOX_ENV -- --cov=flask_graphql | ||
after_success: | ||
- coveralls | ||
deploy: | ||
provider: pypi | ||
user: syrusakbary | ||
on: | ||
tags: true | ||
password: | ||
secure: GB3YHihKAbmfh9kzMxzsZQDMf5h1aIJYwESfaYMc4DjMA1Qms+ZhBN2RiH3irwJ6FW47ZsS/O6ZsrlNxu75J/Mc1NJfzFev1d0xt7cYp+s0umYHhheelR6wmP8KOt3ugK7qmWuk5bykljpxsRKzKJCvGH+LOM7mDQy3NZOfYPTAM2znWjuBr+X4iUv6pUCKk5N20GBbs9T+jNttE7K8TH4zuXCWxgbE7xVHth76pB5Q/9FZkB8hZQ7K2esO3QyajDO7FzsOk8Z/jXRJ3MOxZCI3vGgmSzKTH4fMqmSrtyr1sCaBO5tgS8ytqQBjsuV1vIWl+75bXrAXfdkin63zMne4Rsb+uSWj3djP+iy2yML8a2mWMizxr803v8lwaGnMZ26f4rwdZnHGUPlTp3geVKq23vidVTQwF8v2o1rHvtdD4KJ5Mi41TXAfnih3XUf+fCTXdbAXKqweDuhcZg09/r7U/6zo76wjnt1cePPZe63/xG6bAVQ+Gz1J+HZz55ofDZV9g9kwyNll4Jfdzj9hUHO8AfBMvXQJewRj/LbzbmbBp5peov+DFhx7TWofvqxjreVKxDiDN89pC+WKy5BwZMcpB3dRVGuZ25ZrENLgoTX7W4PHPb1+OF4edP6xM44egcJLamk7vhvpZQqukJGRQZFtIMw8KIkC7OWzpCFIXN08= |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,21 @@ | ||
The MIT License (MIT) | ||
|
||
Copyright (c) 2017-Present Syrus Akbary | ||
|
||
Permission is hereby granted, free of charge, to any person obtaining a copy | ||
of this software and associated documentation files (the "Software"), to deal | ||
in the Software without restriction, including without limitation the rights | ||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell | ||
copies of the Software, and to permit persons to whom the Software is | ||
furnished to do so, subject to the following conditions: | ||
|
||
The above copyright notice and this permission notice shall be included in all | ||
copies or substantial portions of the Software. | ||
|
||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR | ||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, | ||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE | ||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER | ||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, | ||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE | ||
SOFTWARE. |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1 @@ | ||
include README.md |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,16 @@ | ||
# GraphQL-Server | ||
|
||
[](https://travis-ci.org/graphql-python/graphql-server) [](https://coveralls.io/github/graphql-python/graphql-server?branch=master) [](https://badge.fury.io/py/graphql-server) | ||
|
||
GraphQL Server core package. | ||
|
||
## Integrations | ||
|
||
GraphQL Server powers the following integrations | ||
|
||
| Server integration | Package | | ||
|---------------|-------------------| | ||
| Django | [graphene-django](https://github.com/graphql-python/graphene-django/) | | ||
| Flask | [flask-graphql](https://github.com/graphql-python/flask-graphql/) | | ||
| Sanic | [sanic-graphql](https://github.com/graphql-python/sanic-graphql/) | | ||
| WebOb (Pyramid, Pylons) | [webob-graphql](https://github.com/graphql-python/webob-graphql/) | |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,30 @@ | ||
GraphQL-Server | ||
============== | ||
|
||
|Build Status| |Coverage Status| |PyPI version| | ||
|
||
GraphQL Server core package. | ||
|
||
Integrations | ||
------------ | ||
|
||
GraphQL Server powers the following integrations | ||
|
||
+---------------------------+----------------------------------------------------------------------------+ | ||
| Server integration | Package | | ||
+===========================+============================================================================+ | ||
| Django | `graphene-django <https://github.com/graphql-python/graphene-django/>`__ | | ||
+---------------------------+----------------------------------------------------------------------------+ | ||
| Flask | `flask-graphql <https://github.com/graphql-python/flask-graphql/>`__ | | ||
+---------------------------+----------------------------------------------------------------------------+ | ||
| Sanic | `sanic-graphql <https://github.com/graphql-python/sanic-graphql/>`__ | | ||
+---------------------------+----------------------------------------------------------------------------+ | ||
| WebOb (Pyramid, Pylons) | `webob-graphql <https://github.com/graphql-python/webob-graphql/>`__ | | ||
+---------------------------+----------------------------------------------------------------------------+ | ||
|
||
.. |Build Status| image:: https://travis-ci.org/graphql-python/graphql-server.svg?branch=master | ||
:target: https://travis-ci.org/graphql-python/graphql-server | ||
.. |Coverage Status| image:: https://coveralls.io/repos/graphql-python/graphql-server/badge.svg?branch=master&service=github | ||
:target: https://coveralls.io/github/graphql-python/graphql-server?branch=master | ||
.. |PyPI version| image:: https://badge.fury.io/py/graphql-server.svg | ||
:target: https://badge.fury.io/py/graphql-server |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,3 @@ | ||
#!/bin/bash | ||
|
||
pandoc README.md --from markdown --to rst -s -o README.rst |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,210 @@ | ||
import json | ||
from collections import namedtuple, MutableMapping | ||
|
||
import six | ||
from graphql import Source, execute, parse, validate | ||
from graphql.error import format_error as format_graphql_error | ||
from graphql.error import GraphQLError | ||
from graphql.execution import ExecutionResult | ||
from graphql.type.schema import GraphQLSchema | ||
from graphql.utils.get_operation_ast import get_operation_ast | ||
|
||
from .error import HttpQueryError | ||
|
||
|
||
class SkipException(Exception): | ||
pass | ||
|
||
|
||
GraphQLParams = namedtuple('GraphQLParams', 'query,variables,operation_name') | ||
GraphQLResponse = namedtuple('GraphQLResponse', 'result,status_code') | ||
|
||
|
||
def default_format_error(error): | ||
if isinstance(error, GraphQLError): | ||
return format_graphql_error(error) | ||
|
||
return {'message': six.text_type(error)} | ||
|
||
|
||
def run_http_query(schema, request_method, data, query_data=None, batch_enabled=False, catch=False, **execute_options): | ||
if request_method not in ('get', 'post'): | ||
raise HttpQueryError( | ||
405, | ||
'GraphQL only supports GET and POST requests.', | ||
headers={ | ||
'Allow': 'GET, POST' | ||
} | ||
) | ||
if catch: | ||
catch = HttpQueryError | ||
else: | ||
catch = SkipException | ||
is_batch = isinstance(data, list) | ||
|
||
is_get_request = request_method == 'get' | ||
allow_only_query = is_get_request | ||
|
||
if not is_batch: | ||
if not isinstance(data, (dict, MutableMapping)): | ||
raise HttpQueryError( | ||
400, | ||
'GraphQL params should be a dict. Received {}.'.format(data) | ||
) | ||
data = [data] | ||
elif not batch_enabled: | ||
raise HttpQueryError( | ||
400, | ||
'Batch GraphQL requests are not enabled.' | ||
) | ||
|
||
if not data: | ||
raise HttpQueryError( | ||
400, | ||
'Received an empty list in the batch request.' | ||
) | ||
|
||
extra_data = {} | ||
# If is a batch request, we don't consume the data from the query | ||
if not is_batch: | ||
extra_data = query_data or {} | ||
|
||
all_params = [get_graphql_params(entry, extra_data) for entry in data] | ||
|
||
responses = [get_response( | ||
schema, | ||
params, | ||
catch, | ||
allow_only_query, | ||
**execute_options | ||
) for params in all_params] | ||
|
||
return responses, all_params | ||
|
||
|
||
def encode_execution_results(execution_results, format_error, is_batch, encode): | ||
responses = [ | ||
format_execution_result(execution_result, format_error) | ||
for execution_result in execution_results | ||
] | ||
result, status_codes = zip(*responses) | ||
status_code = max(status_codes) | ||
|
||
if not is_batch: | ||
result = result[0] | ||
|
||
return encode(result), status_code | ||
|
||
|
||
def json_encode(data, pretty=False): | ||
if not pretty: | ||
return json.dumps(data, separators=(',', ':')) | ||
|
||
return json.dumps( | ||
data, | ||
indent=2, | ||
separators=(',', ': ') | ||
) | ||
|
||
|
||
def load_json_variables(variables): | ||
if variables and isinstance(variables, six.string_types): | ||
try: | ||
return json.loads(variables) | ||
except: | ||
raise HttpQueryError(400, 'Variables are invalid JSON.') | ||
return variables | ||
|
||
|
||
def get_graphql_params(data, query_data): | ||
query = data.get('query') or query_data.get('query') | ||
variables = data.get('variables') or query_data.get('variables') | ||
# id = data.get('id') | ||
operation_name = data.get('operationName') or query_data.get('operationName') | ||
|
||
return GraphQLParams(query, load_json_variables(variables), operation_name) | ||
|
||
|
||
def get_response(schema, params, catch=None, allow_only_query=False, **kwargs): | ||
try: | ||
execution_result = execute_graphql_request( | ||
schema, | ||
params, | ||
allow_only_query, | ||
**kwargs | ||
) | ||
except catch: | ||
return None | ||
|
||
return execution_result | ||
|
||
|
||
def format_execution_result(execution_result, format_error): | ||
status_code = 200 | ||
|
||
if execution_result: | ||
response = {} | ||
|
||
if execution_result.errors: | ||
response['errors'] = [format_error(e) for e in execution_result.errors] | ||
|
||
if execution_result.invalid: | ||
status_code = 400 | ||
else: | ||
status_code = 200 | ||
response['data'] = execution_result.data | ||
|
||
else: | ||
response = None | ||
|
||
return GraphQLResponse(response, status_code) | ||
|
||
|
||
def execute_graphql_request(schema, params, allow_only_query=False, **kwargs): | ||
if not params.query: | ||
raise HttpQueryError(400, 'Must provide query string.') | ||
|
||
try: | ||
source = Source(params.query, name='GraphQL request') | ||
ast = parse(source) | ||
validation_errors = validate(schema, ast) | ||
if validation_errors: | ||
return ExecutionResult( | ||
errors=validation_errors, | ||
invalid=True, | ||
) | ||
except Exception as e: | ||
return ExecutionResult(errors=[e], invalid=True) | ||
|
||
if allow_only_query: | ||
operation_ast = get_operation_ast(ast, params.operation_name) | ||
if operation_ast and operation_ast.operation != 'query': | ||
raise HttpQueryError( | ||
405, | ||
'Can only perform a {} operation from a POST request.'.format(operation_ast.operation), | ||
headers={ | ||
'Allow': ['POST'], | ||
} | ||
) | ||
|
||
try: | ||
return execute( | ||
schema, | ||
ast, | ||
operation_name=params.operation_name, | ||
variable_values=params.variables, | ||
**kwargs | ||
) | ||
|
||
except Exception as e: | ||
return ExecutionResult(errors=[e], invalid=True) | ||
|
||
|
||
def load_json_body(data): | ||
try: | ||
return json.loads(data) | ||
except: | ||
raise HttpQueryError( | ||
400, | ||
'POST body sent invalid JSON.' | ||
) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,13 @@ | ||
class HttpQueryError(Exception): | ||
def __init__(self, status_code, message=None, is_graphql_error=False, headers=None): | ||
self.status_code = status_code | ||
self.message = message | ||
self.is_graphql_error = is_graphql_error | ||
self.headers = headers | ||
super(HttpQueryError, self).__init__(message) | ||
|
||
def __eq__(self, other): | ||
return isinstance(other, HttpQueryError) and \ | ||
other.status_code == self.status_code and \ | ||
other.message == self.message and \ | ||
other.headers == self.headers |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,9 @@ | ||
[flake8] | ||
exclude = tests,scripts,setup.py,docs | ||
max-line-length = 160 | ||
|
||
[isort] | ||
known_first_party=graphql_server | ||
|
||
[pytest] | ||
norecursedirs = venv .tox .cache |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,35 @@ | ||
from setuptools import setup, find_packages | ||
|
||
required_packages = ['graphql-core', 'promise'] | ||
|
||
setup( | ||
name='graphql-server', | ||
version='1.0.dev20170322001', | ||
description='GraphQL Server tools for powering your server', | ||
long_description=open('README.rst').read(), | ||
url='https://github.com/graphql-python/graphql-server', | ||
download_url='https://github.com/graphql-python/graphql-server/releases', | ||
author='Syrus Akbary', | ||
author_email='[email protected]', | ||
license='MIT', | ||
classifiers=[ | ||
'Development Status :: 5 - Production/Stable', | ||
'Intended Audience :: Developers', | ||
'Topic :: Software Development :: Libraries', | ||
'Programming Language :: Python :: 2', | ||
'Programming Language :: Python :: 2.7', | ||
'Programming Language :: Python :: 3', | ||
'Programming Language :: Python :: 3.3', | ||
'Programming Language :: Python :: 3.4', | ||
'Programming Language :: Python :: 3.5', | ||
'Programming Language :: Python :: Implementation :: PyPy', | ||
'License :: OSI Approved :: MIT License', | ||
], | ||
keywords='api graphql protocol rest', | ||
packages=find_packages(exclude=['tests']), | ||
install_requires=required_packages, | ||
tests_require=['pytest>=2.7.3'], | ||
include_package_data=True, | ||
zip_safe=False, | ||
platforms='any', | ||
) |
Empty file.
Oops, something went wrong.