Saravanan666/pypi-org huggingface dataset:
Package: graphql-authz
graphql-authzGraphQL-Authz is a Python3.6+ port ofGraphQL-Authz, theCasbinauthorization middleware implementation inNode.js.This package should be used withGraphQL-core 3, providing the
capability to limit access to each GraphQL resource with the authorization middleware.InstallationInstall the package using pip.pipinstallgraphql-authzGet StartedLimit the access to each GraphQL resource with a policy. For example,
given this policy for anRBACmodel:p, authorized_user, hello, queryAuthorization can be enforced using:importcasbinfromauthz.middlewareimportenforcer_middlewarefromgraphqlimport(graphql_sync,GraphQLSchema,GraphQLObjectType,GraphQLField,GraphQLString,)schema=GraphQLSchema(query=GraphQLObjectType(name="RootQueryType",fields={"hello":GraphQLField(GraphQLString,resolve=lambdaobj,info:"world")}))enforcer=casbin.Enforcer("model_file.conf","policy_file.csv")authorization_middleware=enforcer_middleware(enforcer)query="""{ hello }"""# Authorized user ("authorized_user") has access to dataresponse=graphql_sync(schema,query,middleware=[authorization_middleware],context_value={"role":"authorized_user"})assertresponse.data=={"hello":"world"}# Unauthorized users ("unauthorized_user") are rejectedresponse=graphql_sync(schema,query,middleware=[authorization_middleware],context_value={"role":"unauthorized_user"})assertresponse.errors[0].message=="unauthorized_user can not query hello"For more interesting scenarios seetestsfolder.CreditsImplementation was heavily inspired by theNode.jsmiddlewareGraphQL-Authz.Authorization enforcement is based onCasbinauthorization library.This package was created withCookiecutterand theaudreyr/cookiecutter-pypackageproject template.
Package: graphql-builder
graphql-builderEasy solution for dynamic generation of GraphQL operations.InstallationPython 3.8 or higher is requiredTo install the library, you can just run the following command:# Linux/OS Xpython3.9-mpipinstall-Ugraphql-builder# Windowspy-3.9-mpipinstall-Ugraphql-builderDocumentationReadgraphql-builder's documentationLicenseDistributed under the Apache License 2.0. SeeLICENSEfor more information.Jakub Kuczys  · 
GitHub@jack1142
Package: graphqlclient
python-graphql-clientSimple GraphQL client for Python 2.7+InstallpipinstallgraphqlclientUsagefromgraphqlclientimportGraphQLClientclient=GraphQLClient('http://graphql-swapi.parseapp.com/')result=client.execute('''{allFilms {films {title}}}''')print(result)AuthorizationAuthorization tokens can be added to the request using the client'sinject_tokenmethod:client.inject_token('very-long-and-secure-token')which defaults to http header nameAuthorization.
An alternative http header name for the token can be set by passing in the alternative header name, e.g. forx-api-key:client.inject_token('very-long-and-secure-token','x-api-key')LicenseMIT License
Package: graphql_client
Getting Startedclient=GraphQLClient('https://www.graphqlhub.com/graphql')result=client.query('''
query ($id: String!) {
    hn2 {
        nodeFromHnId(id: $id, isUserId: true) {
            id
        }
    }
}
''',{'id':'clayallsopp'})The client constructor can also take a dictionary of additonal headers
in a keyword argumentheadersor as the second parameter.TestsTo Run Testsmaketest
Package: graphqldomain
A Sphinx domain for describing GraphQL schemas.Getting StartedThe following steps will walk through how to addgraphqldomainto an existing Sphinx project.
For instructions on how to set up a Sphinx project,
see Sphinx’s documentation onGetting Started.Installationgraphqldomaincan be installed through pip:pipinstallgraphqldomainNext, addgraphqldomainto theextensionslist in your Sphinx project’sconf.py.extensions.append("graphqldomain")UsageEach directive accepts a small snippet of the original schema.
For more detailed usage, see the documentation:https://graphqldomain.readthedocs.io/en/latest/..gql:schema::An example schema.:optype Query query:..gql:directive::@slow(super: Boolean = false) on FIELD_DEFINITION | ARGUMENT_DEFINITIONIndicates that the usage of this field or argument is slow,and therefore queries with this field or argument should be made sparingly.:argument super:Whether usage will be super slow, or just a bit slow...gql:enum::CharacterCaseThe casing of a character...gql:enum:value::UPPERUpper case...gql:enum:value::LOWERLower case...gql:input::Point2DA point in a 2D coordinate system...gql:input:field::x: FloatThe``x``coordinate of the point...gql:input:field::y: FloatThe``y``coordinate of the point...gql:interface::NamedEntityAn entity with a name...gql:interface:field::name(lower: Boolean = false): StringThe name of the entity.:argument lower:Whether to lowercase the name or not...gql:type::Person implements NamedEntityA human person...gql:type:field::age: IntHow old the person is in years...gql:type:field::picture: Url..gql:union::Centre = Person | Point2DA possible centre of the universe.ContributingRunning the testsTests are executed throughtox.toxCode StyleCode is formatted usingblack.You can check your formatting using black’s check mode:tox-eformatYou can also get black to format your changes for you:blackgraphqldomain.pytests/VersioningWe useSemVerfor versioning. For the versions available, see thetags on this repository.LicenseThis project is licensed under the MIT License.
See theLICENSE.rstfile for details.
Package: graphql-dsl
Compose GraphQL queries by composing Python typespipinstallgraphql-dslLet’s take a manually writtenGraphQL query from the official docs:query {
    hero {
        name
    }
    droid(id: "2000") {
        name
    }
}Withgraphql-dslyou can construct a similar query with the following Python snippet:fromtypingimportNamedTuplefromgraphql_dslimport*classHero(NamedTuple):name:strclassDroid(NamedTuple):name:strclassHeroAndDroid(NamedTuple):hero:Herodroid:DroidclassInput(NamedTuple):droid_id:IDq=GQL(QUERY|HeroAndDroid|WITH|Input|PASS|Input.droid_id*TO*HeroAndDroid.droid*AS*'id')print(q.query)and the output will be:query HeroAndDroid($droidId:ID!){hero{name}droid(id:$droidId){name}}The value ofq.queryis a GraphQL query template that should be used with instances ofInputto call
servers with GraphQL APIimportrequestsq=GQL(...)defcall_server(droid_id:ID)->HeroAndDroid:response=requests.post(url='https://<graphql-server-url>/',json=q.request_payload(Input(droid_id=droid_id)),headers={'Content-Type':'application/json','Accept':'application/json'})response.raise_for_status()returnq.get_result(response.json())Note that the queryqresides at the top-level module scope, as the query constructor doesn’t depend on the
query’s input values, it only needs to know about the shapes of input and output data.The query builder supports bothNamedTupleand@dataclasstypes, yet the latter has a slightly different
field reference syntax (because dataclasses don’t define class-level field getters):fromdataclassesimportdataclassfromgraphql_dslimport*@dataclassclassHero:name:str@dataclassclassDroid:name:str@dataclassclassHeroAndDroid:hero:Herodroid:Droid@dataclassclassInput:droid_id:IDq=GQL(QUERY|HeroAndDroid|WITH|Input|PASS|(Input,'droid_id')*TO*(HeroAndDroid,'droid')*AS*'id')Find out more fromOfficial Documentation.Test SuiteTest environment is based onNix.nix-shellpytest
Package: graphql-error-logger
Summaryallows for the logging of the exception happening in the flask-graphql framework.this hooks into the graphql error handler and logs the original error, along with its stacktracethis allows one to see the data for an error like{"errors":[{"message":"sdsd","locations":[{"line":2,"column":3}],"path":["users"]}],"data":{"users":null}}as2020-04-06 00:02:43,217 - LIA-logger:30 - ERROR - error in resolvers
Traceback (most recent call last):
  File "/Users/brianrotich/.pyenv/versions/3.6.10/envs/test-app/lib/python3.6/site-packages/graphql/execution/executor.py", line 452, in resolve_or_error
    return executor.execute(resolve_fn, source, info, **args)
  File "/Users/brianrotich/.pyenv/versions/3.6.10/envs/test-app/lib/python3.6/site-packages/graphql/execution/executors/sync.py", line 16, in execute
    return fn(*args, **kwargs)
  File "/Users/brianrotich/.pyenv/versions/3.6.10/envs/test-app/lib/python3.6/site-packages/graphene/relay/connection.py", line 161, in connection_resolver
    resolved = resolver(root, info, **args)
  File "/Users/brianrotich/codes/app/test-app/__init__.py", line 187, in resolve_users
    raise ValueError('sdsd')
ValueError: sdsdUsagea. using an existing logger in theapp.pyimportloggingimportgraphql_error_loggerdefcreate_app():# logger initialization and configurationlogger=logging.getLogger(__name__)graphql_error_logger.init_logger(logger)b. if no logger is provided, the library creates a logger calledgraphql-error-loggerautomaticallyimportgraphql_error_loggerdefcreate_app():graphql_error_logger.init_logger()this logger is configured to use theERRORlog level to log the exception stacktrace
Package: graphql-explorer
GraphQL ExplorerAn experimental package for consolidating web based graphql viewers & explorers. This was initially developed for a talk, and now continues to improved to provide enhanced features.InterfacesApollo Sandbox ExplorerGraphiQLGraphQL VoyagerPathfinder GraphQL IDEIntegrations/HelpersFastAPIDjangoFlaskFalconInstructionsInstallationpipinstallgraphql-explorer
Package: graphql-limits
graphql-limitsFeatures included:Limit Query DepthLimit Query NodesPrerequisitesgraphql-coreInstallationpip install graphql-limitsUsage examplequery_string='''query Test($first: Int) {viewer {books(first: $first) {author {books(first: 4) {author {books(first: 100) {author {id}}}}}}}}'''schema=graphene.Schema(query=Query)backend=ProtectorBackend(nodes_limit=399,depth_limit=5,variable_values={'first':2})result=schema.execute(query_string,backend=backend,variable_values={'first':2})
Package: graphqlparser
Python2.7+ Python3.4+ class-based bindings to libgraphqlparser; just a thin layer on top oflibgraphqlparserC API.StillEXPERIMENTALInstallingFirst installlibgraphqlparserfollowing instructions onlibgraphqlparser github page.Next you can installgraphqlparser. The easiest way is using precompiled wheels which are usually available
ongraphqlparser github releasesPick the right wheel for your platform and python version, then install it using pip:pip install https://github.com/elastic-coders/py-graphqlparser/releases/download/v0.0.3/graphqlparser-0.0.3-cp27-none-linux_x86_64.whlAs an alternative you can installgraphqlparserfrom source distribution:InstallcythonSet an env var$GRAPHQL_HOMEto the folder wherelibgraphqlparser.soandAst.hareInstallgraphqlparserwith pip:LDFLAGS="-L$GRAPHQL_HOME" CFLAGS="-I$GRAPHQL_HOME/c -I$GRAPHQL_HOME" pip install graphqlparserUsageMake surelibgraphqlparseris available to the loader. You can add its base dir toLD_LIBRARY_PATH.Then you can start parsing by creating your custom visitor class:fromgraphql_parserimportGraphQLAstVisitorclassMyVisitor(GraphQLAstVisitor.GraphQLAstVisitor):defvisit_field(self,node):print('start field%svisit'%node)# Return 1 to keep visiting children, 0 to skip themreturn1defend_visit_field(self,node):print('end field%svisit'%node)And using it to visit a parsed query:fromgraphql_parserimportGraphQLParserquery='{query{}}'node=GraphQLParser.graphql_parse_string(query)MyVisitor().visit_node(node)See alsoexamplesfolder.Building from source checkoutRebuild the generated cython files from the libgraphql AST (usually not needed)download submodules withgit checkout--recursivebuild libgraphql library in folder./libgraphqlparser(python2.7 required for building)
(usuallypushd libgraphqlparser && cmake . && make && popdworks)generate source code withpython ast/build_ast.pyyou can now switch to python 3installcythonrun:LDFLAGS="-L./libgraphqlparser" CFLAGS="-Ilibgraphqlparser/c -Ilibgraphqlparser" python setup.py build_extTo create a wheel distribution:install wheel:pip install wheelcreate wheelhousemkdir .wheelhousebuild withpip wheel--wheel-dir=.wheelhouse.Known issuesOnly (lightly) tested on python3Unicode string handling not yet complete (a mixture of bytes and strings all over)Exceptions in the visitor’s class callbacks are ignoredlibgraphqlparser isdynamicallylinked but It would be better if it was linked staticallyTODObuild more wheel packages for linux 32 bit and other platformsNewsv0.0.3fixed packaging and building
Package: graphql-py
GraphQL lexer and parser written in pure Python, produces AST. Features:Complies with latestworking draft of GraphQL specification;Fast enough, built onPLY;Tested vs. Python 2.7, 3.4 - 3.9, and PyPyInstallation$pipinstallgraphql-pyUsagefromgraphql.parserimportGraphQLParserparser=GraphQLParser()ast=parser.parse("""
  query UserQuery {
    user(id: 4) {
      id
      name
      profilePic
      avatar: profilePic(width: 30, height: 30)
    }
  }
""")print(ast)LicenseMIT
Package: graphql-python
GraphQL parser for Python=========================This is an experimental, generic parser for the [GraphQL language][1] in Python. Consider it unstable since there's no spec for the language yey (that's why it's *experimental* ;)Install and usage-----------------$ pip install graphql-pythonAnd just `import graphql` to get started. This library mimics the standard `json` module, so there's a `dumps` and a `loads` function. Consider this query:query = """{user(232) {id,name,photo(size: 50) {url,width,height}}}"""objects = graphql.loads(query)# objects has now:[{"name": "user","params": 232,"properties": [{"name": "id"},{"name": "name"},{"name": "photo","params": {"size": 50},"properties": [{"name": "url"},{"name": "width"},{"name": "height"}]},]}]To understand how `loads` works, let's split this query into small parts:friends(user_id: 232).first(10) {url,name,address}This query represents an *object* composed of:- a name (`friends`)- can be anything that matches the `r'`[a-zA-Z_][a-zA-Z0-9_/]*'` regex.- some parameters (`user_id: 232`)- can match literals (strings, numbers with or without signal, true, false and null) and pairs of values- `(true)` will be loaded as `"params": True`. Likewise, `(232)` will be `"params": 232`.- `(foo: "bar", bar: "baz")` will be loaded as `"params": {"foo": "bar", "bar": "baz"}`. Any valid identifier (the regex for *name*) can be used as an argument.- some custom filters (`first(10)`)- it's a sequence of identifiers followed by a list of parameters. Order is important, so for example, `.after(id: 243442).first(10)` will be loaded as:"filters": [("after", {"id": 243442}),("first", 10)]- and a list of properties (`url, name, address`)... basically either an identifier or another nested object.Some advices------------Right now, this parser is *strict* (at least until the spec is released, obviously). It'll yell at you for not using commas in the right places. For example:# Will fail :(graphql.loads("""user(42) {id,name}""")# Much better :) ... don't forget those { } in the beginning and end of the querygraphql.loads("""{user(42) {id,name}}""")# Will fail :(graphql.loads("""{user(42) {id,name}company(2) {address}}""")# Much better :) ... see that little comma right after the first object?graphql.loads("""{user(42) {id,name},  # <-- right herecompany(2) {address}}""")A note about performance & pyParsing------------------------------------I didn't test the numbers, just dropping [this link][2] for you to tell there's a way to improve pyParsing's performance.This flag isn't enabled because it's global, so [YMMV][3].[1]: https://facebook.github.io/react/blog/2015/05/01/graphql-introduction.html[2]: http://stackoverflow.com/a/21371472[3]: http://www.urbandictionary.com/define.php?term=ymmv
Package: graphql-query
graphql-querygraphql_queryis a complete Domain Specific Language (DSL) for GraphQL query in Python. With this package
you can togenerate a correct GraphQL query string from a python classes;use and share similar Arguments, Variables and e.t.c between different queries;easily add new fields to your query;add Fragments and Directives to queries;generategraphql_queryclasses from pydantic data-model;The documentation forgraphql_querycan be found athttps://denisart.github.io/graphql-query/.QuickstartInstall with pippipinstallgraphql_querySimple queryCode for the simple query{hero{name}}it isfromgraphql_queryimportOperation,Queryhero=Query(name="hero",fields=["name"])operation=Operation(type="query",queries=[hero])print(operation.render())"""query {hero {name}}"""Therendermethod for thegraphql_query.Operationobject
just returns the final string with a query. Inside thefieldsarray of thegraphql_query.Queryobject
you can usestr(a field name);object ofgraphql_query.Fieldtype;graphql_query.Fragmentandgraphql_query.InlineFragment.Arguments, Variables and DirectivesFor generation of the following queryqueryHero($episode:Episode,$withFriends:Boolean!){hero(episode:$episode){namefriends@include(if:$withFriends){name}}}we can use the following python codefromgraphql_queryimportArgument,Directive,Field,Operation,Query,Variableepisode=Variable(name="episode",type="Episode")withFriends=Variable(name="withFriends",type="Boolean!")arg_episode=Argument(name="episode",value=episode)arg_if=Argument(name="if",value=withFriends)hero=Query(name="hero",arguments=[arg_episode],fields=["name",Field(name="friends",fields=["name"],directives=[Directive(name="include",arguments=[arg_if])])])operation=Operation(type="query",name="Hero",variables=[episode,withFriends],queries=[hero])print(operation.render())"""query Hero($episode: Episode$withFriends: Boolean!) {hero(episode: $episode) {namefriends @include(if: $withFriends) {name}}}"""You can find other examples in the documentation.
Package: graphql-server
GraphQL-Server is a base library that serves as a helper
for building GraphQL servers or integrations into existing web frameworks usingGraphQL-Core.Integrations built with GraphQL-ServerServer integrationDocsFlaskflaskSanicsanicAIOHTTPaiohttpWebOb (Pyramid, TurboGears)webobOther integrations built with GraphQL-ServerServer integrationPackageWSGIwsgi-graphqlResponderresponder.ext.graphqlOther integrations using GraphQL-Core or GrapheneServer integrationPackageDjangographene-djangoDocumentationThegraphql_serverpackage provides these public helper functions:run_http_queryencode_execution_resultsload_json_bodyjson_encodejson_encode_prettyNOTE:thejson_encode_prettyis kept as backward compatibility change as it usesjson_encodewithprettyparameter set toTrue.All functions in the package are annotated with type hints and docstrings,
and you can build HTML documentation from these usingbin/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.ContributingSeeCONTRIBUTING.md
Package: graphql-server-core
GraphQL-Server-CoreGraphQL-Server-Core is a base library that serves as a helper
for building GraphQL servers or integrations into existing web frameworks usingGraphQL-Core.Existing integrations built with GraphQL-Server-CoreServer integrationPackageFlaskflask-graphqlSanicsanic-graphqlAIOHTTPaiohttp-graphqlWebOb (Pyramid, TurboGears)webob-graphqlWSGIwsgi-graphqlResponderresponder.ext.graphqlOther integrations using GraphQL-Core or GrapheneServer integrationPackageDjangographene-djangoDocumentationThegraphql_serverpackage provides these public helper functions:run_http_queryencode_execution_resultsload_json_bodyjson_encodejson_encode_prettyAll functions in the package are annotated with type hints and docstrings,
and you can build HTML documentation from these usingbin/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.ContributingSeeCONTRIBUTING.md
Package: graphql-sqlalchemy
graphql-sqlalchemyGenerate GraphQL Schemas from your SQLAlchemy modelsInstallpip install graphql-sqlalchemyUsagefromariadne.asgiimportGraphQLfromfastapiimportFastAPIfromsqlalchemyimportcreate_enginefromsqlalchemy.ext.declarativeimportdeclarative_basefromsqlalchemy.ormimportsessionmakerfromgraphql_sqlalchemyimportbuild_schemaengine=create_engine('sqlite:///config.db')Base=declarative_base()Session=sessionmaker(bind=engine)app=FastAPI()session=Session()schema=build_schema(Base)app.mount("/graphql",GraphQL(schema,context_value=dict(session=session)))Queryquery{user(where:{_or:[{id:{_gte:5}},{name:{_like:"%bob%"}},]}){idname}user_by_pk(id:5){createtime}}
Package: graphql-utilities
graphql-utilitiesgraphql-utilitiestries to secure your GraphQL API from malicious queries and provides utilities to make usinggraphql-coreeasier.It comes with a custom configurableExtendedExecutionContextclass that is capable of performing:query cost analysis: define the cost of your queries using the@cost()directive provided,graphql-utilitiesprovides helper functions and custom execution context to protect you from overly complex queries.depth limiting: limit the maximum depth of queries, it's especially useful with object types with recursive relationshipIt also ships decorators for:resource-level/one-shot middleware: middleware ingraphql-coreis run at field-level, it is handly when you need your middleware to run only once, especially auth-related middleware.Installationpipinstallgraphql-utilitiesAlternatively, if you use pipenv:pipenvinstallgraphql-utilitiesExamplesOperation-level middleware (One-shot middleware)fromgraphql_utilities.decoratorsimportrun_only_onceclassAuthMiddleware:@run_only_oncedefresolve(self,next_,root,info,*args,**kwargs):# middleware logicreturnnext_(root,info,*args,**kwargs)Limiting Query Depth# import your schemafromgraphqlimportexecute,parse# Requires `graphql-core>=3.0`fromgraphql_utilities.executionimportExtendedExecutionContextquery='{ field_1_str field_2_int field_3_obj { field_3_obj_sub_1 { xxx } } }'graphql_sync(schema=schema,source=query,context_value={"depth_analysis":{"max_depth":2# Maximum depth allowed}},execution_context_class=ExtendedExecutionContext# Use the `ExtendedExecutionContext` provided in `graphql-utilities`)Query Cost AnalysisSee the documentation athttps://graphql-utilities.readthedocs.io/en/latest/MotivationIn recent projects, I ran into some problems withgrapheneandgraphql-coreincluding missing operation-level middleware (Seeissue here), etc.graphql-utilitiesis a compilation of utilities and custom execution context for depth analysis, etc targetinggraphql-core>=3.0.ContributingAny form of contribution, feature requests, bug reports, pull requests are largely welcome.LicensesMIT Licensed. GraphQL logo is licensed under FacebookBSD.
Package: graphql-utils
Thegraphql-utilsPython package is a collection of utilities function for
interacting with GraphQL libraries. It is meant to be library agnostic so it
should work with whatever library or protocol you want.UsageMulti-requestsThe multi-requests module allows you to send a request multiple times with
different parameter. It also supports pagination, making sure that you’ll get
all the results for all the requests you sent.Example:import requests

from graphql_utils import multi

def requests_api(query):
    return requests.post("https://myapi.com/graphql", json=query)

userlist = (
    {"login": "jd"},
    {"login": "sileht"},
    {"login": "foo"},
    {"login": "bar"},
)

result_iterator = multi.multi_query("""
    user(login: "{login}") {{
      pets(first: 100{after}) {{
        nodes {{
          name
        }}
        pageInfo {{
          hasNextPage
          endCursor
        }}
      }}
    }}""",
    iterable=userlist,
    pageinfo_path=("pets", "pageInfo"),
    send_fn=requests_api,
)This will send one GraphQL requests with 4 queries (one for each user fromuserlist). Aspageinfo_pathwas specified, if any of the query does not
return all information in one request, a new query using theendCursorwill
be automatically sent to get the next results.