Saravanan666/pypi-org huggingface dataset:
Package: graphene-jwt-auth-registration
Authentication and registration using graphene and JWTDocumentationQuickstartInstall Graphene JWT Auth Registration:pip install graphene-jwt-auth-registrationAdd it to yourINSTALLED_APPS:INSTALLED_APPS=["django.contrib.auth","django.contrib.contenttypes","django.contrib.sites",..."djoser","graphene_django","gjwt_auth",]Set AUTH_USER_MODEL:AUTH_USER_MODEL="gjwt_auth.User"Add JSONWebTokenBackend backend to your AUTHENTICATION_BACKENDS:AUTHENTICATION_BACKENDS=['graphql_jwt.backends.JSONWebTokenBackend','django.contrib.auth.backends.ModelBackend',]Add the JSONWebTokenMiddleware:GRAPHENE={'SCHEMA':'yourproject.schema.schema','MIDDLEWARE':['graphql_jwt.middleware.JSONWebTokenMiddleware',],}Create graphene schema inyourproject/schema.py:importgrapheneimportgraphql_jwtfromgjwt_auth.mutationsimport(Activate,DeleteAccount,Register,ResetPassword,ResetPasswordConfirm,)fromgjwt_auth.schemaimportUser,ViewerclassRootQuery(graphene.ObjectType):viewer=graphene.Field(Viewer)defresolve_viewer(self,info,**kwargs):ifinfo.context.user.is_authenticated:returninfo.context.userreturnNoneclassMutation(graphene.ObjectType):activate=Activate.Field()register=Register.Field()deleteAccount=DeleteAccount.Field()resetPassword=ResetPassword.Field()resetPasswordConfirm=ResetPasswordConfirm.Field()token_auth=graphql_jwt.ObtainJSONWebToken.Field()verify_token=graphql_jwt.Verify.Field()refresh_token=graphql_jwt.Refresh.Field()schema=graphene.Schema(query=RootQuery,mutation=Mutation)Set djoser setttings:DOMAIN=os.environ.get('DJANGO_DJOSER_DOMAIN','localhost:3000')SITE_NAME=os.environ.get('DJANGO_DJOSER_SITE_NAME','my site')DJOSER={'PASSWORD_RESET_CONFIRM_URL':'?action=set-new-password&uid={uid}&token={token}','ACTIVATION_URL':'activate?uid={uid}&token={token}','SEND_ACTIVATION_EMAIL':True,}}Add Graphenes URL patterns:fromdjango.conf.urlsimporturlfromdjango.views.decorators.csrfimportcsrf_exemptfromgraphene_django.viewsimportGraphQLView...urlpatterns=[...url(r'^graphql',csrf_exempt(GraphQLView.as_view(graphiql=True))),...]Running TestsDoes the code actually work?source <YOURVIRTUALENV>/bin/activate
(myenv) $ pip install tox
(myenv) $ toxCreditsTools used in rendering this package:Cookiecuttercookiecutter-djangopackageHistory0.1.0 (2019-06-04)First release on PyPI.
Package: graphene-luna
Graphene LunaGraphene Luna is a websocket backend for GraphQL subscriptions in Django with Graphene. It does not require
Django Channels. Luna implements thegraphql-ws protocol.Why LunaMost of the Django Graphene websocket subscription implementations are broke with newer versions of Django or require Django Channels. While Django Channels is great, it is complex and requires extra infrastructure such as Redis. With new versions of Django, the included asynchronous features allow websockets to be created more "natively" with less infrastructure and code overhead.Graphene Luna is the new modern and easy way to do GraphQL subscriptions in Django.django-wsGraphene Luna relies ondjango-ws. If you wish to customize your experience, refer to django-ws for things like middleware and customizing websocket methods.Installationpip install graphene-lunaAdding Luna to Your Django ProjectSee theLuna Starter Projectfor a fully setup Django project with Graphene and Luna installed.Step 1: Update Yourasgi.pyRemove line:from django.core.asgi import get_asgi_applicationRemove line:application = get_asgi_application()Add to the end:fromdjango_wsimportget_websocket_applicationapplication=get_websocket_application()Step 2: Connect the GraphQL Websocket inws_urls.pyNext to your rooturls.pycreate aws_urls.pylike the example below that uses your websocket.fromdjango.urlsimportpathimportluna_wsurlpatterns=[path('graphql',luna_ws.GraphQLSubscriptionHandler),]Step 3: Verify Your Schema is SetupYou should have Graphene setup with a schema. If not see theGraphene installationsteps.In your Graphene settings verify you have a schema:GRAPHENE={'SCHEMA':'myproject.schema.schema'}Step 3: Add Your First SubscriptionAdd a subscription to your schema. A simple schema to test subscriptions work is shown below.myproject/schema.pyimportasyncioimportgraphenefromgraphqlimportGraphQLErrorclassSubscription(graphene.ObjectType):count_seconds=graphene.Int(up_to=graphene.Int())asyncdefsubscribe_count_seconds(root,info,up_to):ifup_to>30:raiseGraphQLError('Count too high, must be <= 30')foriinrange(up_to):print('TestSubs: ',i)yieldiawaitasyncio.sleep(1)schema=graphene.Schema(query=Query,mutation=Mutation,subscription=Subscription,)Step 4: Run Your Django Project AsynchronouslyYou will need to pick a way torun Django asynchronously.Running with Gunicorn looks something like:gunicorn myproject.asgi:application -k uvicorn.workers.UvicornWorkerStep 5: Test Out Your SubscriptionNavigate to your GraphiQL Explorer and to test out the subscription above, use a query like:subscription{countSeconds(upTo:30)}If you're subscription test was successful, then you can proceed to writing more advanced subscriptions.Compatibility NotesCurrently Luna works withDjango Graphene3.1+ only. Also, Luna implements the newer GraphQL subscription protocolgraphql-ws.Going FurtherExample SubscriptionsImplementation Details
Package: graphenemodeling
Graphene ModelingFULL DOCUMENTATIONThis Python packagemodels the electronic and optical properties of graphene. The intent is to reproduce results found in the literature so that researchers need not write their own code which wastes time and may contain bugs that alter results. To boost confidence in the code in this repository, every piece of code should be accompanied by a figure that reproduces a result from a published paper.View thefull documentation.Installthe latest version with> pip install graphenemodelingAlternatively, if you are comfortable building from source, first select the latest stable version underBranch: master -> Tags -> v#.#.#and download or clone the repository.Testyour installation with the command> python -m graphenemodelingYou should see the greetingWelcome to graphenemodeling version #.#.#!

    For a quick overview of this package's capabilities, run
    > python -m graphenemodeling overview

    For issues, contact Gregory Holdman at gholdman@protonmail.com
    or submit an issue or pull request on github.
Package: graphene-mongo
Graphene-MongoAMongoengineintegration forGraphene.InstallationFor installing graphene-mongo, just run this command in your shellpip install graphene-mongoExamplesHere is a simple Mongoengine model asmodels.py:frommongoengineimportDocumentfrommongoengine.fieldsimportStringFieldclassUser(Document):meta={'collection':'user'}first_name=StringField(required=True)last_name=StringField(required=True)To create a GraphQL schema and sync executor; for it you simply have to write the following:importgraphenefromgraphene_mongoimportMongoengineObjectTypefrom.modelsimportUserasUserModelclassUser(MongoengineObjectType):classMeta:model=UserModelclassQuery(graphene.ObjectType):users=graphene.List(User)defresolve_users(self,info):returnlist(UserModel.objects.all())schema=graphene.Schema(query=Query)Then you can simply query the schema:query='''query {users {firstName,lastName}}'''result=awaitschema.execute(query)To create a GraphQL schema and async executor; for it you simply have to write the following:importgraphenefromgraphene_mongoimportAsyncMongoengineObjectTypefromgraphene_mongo.utilsimportsync_to_asyncfromconcurrent.futuresimportThreadPoolExecutorfrom.modelsimportUserasUserModelclassUser(AsyncMongoengineObjectType):classMeta:model=UserModelclassQuery(graphene.ObjectType):users=graphene.List(User)asyncdefresolve_users(self,info):returnawaitsync_to_async(list,thread_sensitive=False,executor=ThreadPoolExecutor())(UserModel.objects.all())schema=graphene.Schema(query=Query)Then you can simply query the schema:query='''query {users {firstName,lastName}}'''result=awaitschema.execute_async(query)To learn more check out the followingexamples:Flask MongoEngine exampleDjango MongoEngine exampleFalcon MongoEngine exampleContributingAfter cloning this repo, ensure dependencies are installed by running:pipinstall-rrequirements.txtAfter developing, the full test suite can be evaluated by running:maketest
Package: graphene-mongoengine
# graphene-mongoengine## Supporting mongonengine connection for grapheneInspired in graphene_django, we can use this package to manage information stored in MongoDB.For doing this, we will use Mongoengine package. It's quite simple:`from graphene_mongoengine import MongoEngineObjectTypeclass MyExampleNode(MongoEngineObjectType):class Meta:document = MyExampleModel`
Package: graphene-neo4j
Please readUPGRADE-v2.0.mdto learn how to upgrade to Graphene2.0.Graphene-DjangoADjangointegration forGraphene.DocumentationVisit the documentation to get started!QuickstartFor installing graphene, just run this command in your shellpipinstall"graphene-django>=2.0"SettingsINSTALLED_APPS=(# ...'graphene_django',)GRAPHENE={'SCHEMA':'app.schema.schema'# Where your Graphene schema lives}UrlsWe need to set up aGraphQLendpoint in our Django app, so we can
serve the queries.fromdjango.conf.urlsimporturlfromgraphene_django.viewsimportGraphQLViewurlpatterns=[# ...url(r'^graphql$',GraphQLView.as_view(graphiql=True)),]ExamplesHere is a simple Django model:fromdjango.dbimportmodelsclassUserModel(models.Model):name=models.CharField(max_length=100)last_name=models.CharField(max_length=100)To create a GraphQL schema for it you simply have to write the
following:fromgraphene_djangoimportDjangoObjectTypeimportgrapheneclassUser(DjangoObjectType):classMeta:model=UserModelclassQuery(graphene.ObjectType):users=graphene.List(User)@graphene.resolve_only_argsdefresolve_users(self):returnUserModel.objects.all()schema=graphene.Schema(query=Query)Then you can simply query the schema:query='''
    query {
      users {
        name,
        lastName
      }
    }
'''result=schema.execute(query)To learn more check out the followingexamples:Schema with Filtering:Cookbook exampleRelay Schema:Starwars Relay exampleContributingSeeCONTRIBUTING.md.
Package: graphene-objecttype-from-sqlalchemy-table
graphene-objecttype-from-sqlalchemy-tableTransformSQLAlchemyTableintoGrapheneObjectType.Free software: MIT licenseFeaturesThe purpose of this library is to allow a lightweight GraphQL schema creation based on database table definitions when full SQLAlchemy ORM cannot be used. It convertsTablecolumns into their Graphene counterparts and creates the corresponding GrapheneObjectTypeto be used as a schema field.Note that if your application uses SQLAlchemy ORM,graphene-sqlalchemystill offers more features and you could benefit from using it.InstallationIn shell run:pip install graphene-objecttype-from-sqlalchemy-tableExample usageLet’s start by defining a mock database table.importsqlalchemyassat=sa.Table('test_table',sa.MetaData(),sa.Column('foo',sa.String,doc='This will be passed to field description.'),sa.Column('bar',sa.Integer),)Then create a Graphene object type using a Meta class with the reference to the SQLAlchemy table.fromgraphene_objecttype_from_sqlalchemy_tableimportObjectTypeFromTableclassTestTable(ObjectTypeFromTable):classMeta:table=tAnd finally define the GraphQL query structure using the new object type.fromgrapheneimportField,ObjectType,SchemaclassQuery(ObjectType):test_table=Field(TestTable)# custom resolver for the table (probably a database query in a real world application)# returns a dictionary or an object with attributes corresponding to column namesdefresolve_test_table(root,info):return{'foo':'Hello world','bar':42}schema=Schema(query=Query)# confirm that the query resolves correctlyschema.execute('query { testTable { foo, bar } }')# {'data': {'testTable': {'foo': 'Hello world', 'bar': 42}}}It is possible to exclude specific columns from the resulting object by listing them asexcluded_columnsor to select only a subset of columns withonly_selected_columnsattribute.classTestTable(ObjectTypeFromTable):classMeta:table=texcluded_columns=('foo',)# only_selected_columns = ('bar', )CreditsThis package was created withCookiecutterand theaudreyr/cookiecutter-pypackageproject template.History0.1.2 (2020-09-02)No changes, Travis CI encryption issues caused incorrect pypi release, pypi doesn’t allow deleting and re-releasing the same version hence a new version is needed to fix this.0.1.1 (2020-08-31)Fix duplicate enum types error when multiple columns reuse one SQLAlchemy enum or when enum types are used as field arguments.0.1.0 (2020-08-17)First release on PyPI.
Package: graphene-pandas
graphene-pandas(under developing)InstallationFor instaling graphene-pandas, just run this command in your shellpip3installgraphene-pandas(notimplemented)ExamplesTo create a GraphQL schema for it, you simply have to write the following:importpandasaspdimportgraphenefromgraphene_pandasimportDataFrameObjectTypedata={"Brand":["Honda Civic","Toyota Corolla","Ford Focus","Audi A4"],"Price":[22000,25000,27000,35000]}df=pd.DataFrame(data)classRecords(DataFrameObjectType):classMeta:model=dfexclude_fields=()classQuery(graphene.ObjectType):record=graphene.Field(Records,index=graphene.Int())records=graphene.List(Records)defresolve_record(self,info,index):query=Records.get_row_int_index(info,index)returnquerydefresolve_records(self,info):query=Records.get_all_rows(info)returnqueryschema=graphene.Schema(query=Query)query="""query Test {record(index: 1) {BrandPrice}records {BrandPrice}}"""result=graphene.schema.execute(query)
Package: graphene-peewee-async
graphene+peewee-asyncintegration :heart:FeaturesQueryingFields selection (considered bySELECTstatement)Related entities subselection (using foreign key joins)Filters (django-style lookups, likepeewee.SelectQuery.filterargs)Order (multiple fields, asc/dsc support)Pagination (page,paginate_bysupport plus unpaginatedtotalcount auto-fetching)Mutations (both single object and bulk operating, filtering just like for querying)CreateUpdateDeleteCloneUsage sample# Define modelsclassAuthor(Model):name=CharField()rating=IntegerField()classBook(Model):name=CharField()year=IntegerField()author=ForeignKeyField(Author)# Create nodesclassBookNode(PeeweeObjectType):classMeta:model=Bookmanager=db_managerclassAuthorNode(PeeweeObjectType):classMeta:model=Authormanager=db_manager# Create connectionsclassBookConnection(PeeweeConnection):classMeta:node=BookNode# Aggregate queriesclassQuery(ObjectType):books=PeeweeConnectionField(BookConnection)# Create schemaschema=Schema(query=Query,auto_camelcase=False)# Execute graphql queryresult=schema.execute('''
    query {
        books (filters: {author__name__ilike: "%Lovecraft%"}) {
            total
            edges {
                node {
                    id
                    name
                    author {
                        id
                        name
                    }
                }
            }
        }
    }''',return_promise=True,executor=AsyncioExecutor())# Await result if required (failed queries are usually returning result#                           synchronously with non-empty `result.errors`#                           while successful ones requires awaiting#                           of peewee/DB level queries of course)ifnotisinstance(result,ExecutionResult):result=awaitresult# Enjoy the result :)print(result.data)## ===>## {'books': {#     'total': 2,#     'edges': [#         {'node': {#             'id': 5,#             'name': 'Dagon',#             'author': {#                 'id': 1,#                 'name': 'Howard Lovecraft'#             }#         }},#         {'node': {#             'id': 6,#             'name': 'At the Mountains of Madness',#             'author': {#                 'id': 1,#                 'name': 'H.P. Lovecraft'#             }#         }}#     ]# }}Advanced usageBe sure to checkAPI testsfor advanced query/mutation usages andauto-generatingsuch schema for them.InstallInstall as package:pip3installgraphene-peewee-async
Package: graphene-permissions
graphene-permissionsPermission system for graphene-django apps.OverviewDRF-inspired permission system based on classes for graphene-django. Allows easy customization of permission classes for
for queries and mutations.RequirementsPython 3.5+Django 2.0+graphene-django 2.0+InstallationInstall using pip:pip install graphene-permissionsExampleTo enforce permission system, add appropriate mixin and set attributepermission_classes.### models.pyfromdjango.dbimportmodelsclassPet(models.Model):name=models.CharField(max_length=32)race=models.CharField(max_length=64)### schema.pyfromgrapheneimportrelayfromgraphene_djangoimportDjangoObjectTypefromgraphene_permissions.mixinsimportAuthNodefromgraphene_permissions.permissionsimportAllowAuthenticatedclassPetNode(AuthNode,DjangoObjectType):permission_classes=(AllowAuthenticated,)classMeta:model=Petfilter_fields=('name',)interfaces=(relay.Node,)DocsSetting up permission checkFor queries useAuthNodemixin and inherite fromAuthFilterclass.classAllowAuthenticatedPetNode(AuthNode,DjangoObjectType):permission_classes=(AllowAuthenticated,)classMeta:model=Petfilter_fields=('name',)interfaces=(relay.Node,)classAllowAuthenticatedFilter(AuthFilter):permission_classes=(AllowAuthenticated,)classPetsQuery:user_pet=relay.Node.Field(AllowAuthenticatedPetNode)all_user_pets=AllowAuthenticatedFilter(AllowAuthenticatedPetNode)For mutations useAuthMutationmixin.classAuthenticatedAddPet(AuthMutation,ClientIDMutation):permission_classes=(AllowAuthenticated,)pet=graphene.Field(AllowAuthenticatedPetNode)classInput:name=graphene.String()race=graphene.String()owner=graphene.ID()@classmethoddefmutate_and_get_payload(cls,root,info,**input):ifcls.has_permission(root,info,input):owner=User.objects.get(pk=from_global_id(input['owner'])[1])pet=Pet.objects.create(name=input['name'],race=input['race'],owner=owner)returnAuthenticatedAddPet(pet=pet)returnAuthenticatedAddPet(pet=None)classPetsMutation:authenticated_add_pet=AuthenticatedAddPet.Field()Customizing permission classesDefault permission classes are:AllowAny,AllowAuthenticated,AllowStaff.
You can set up equal permission for both queries and mutations with one class, simply subclass one of these classes
and to limit access for given object, override appropriate method. Remember to returntrueif user should be given
access andfalse, if denied.classAllowMutationForStaff(AllowAuthenticated):@staticmethoddefhas_node_permission(info,id):# logic here# return boolean@staticmethoddefhas_mutation_permission(root,info,input):ifinfo.request.user.is_staff:returnTruereturnFalse@staticmethoddefhas_filter_permission(info):# logic here# return booleanMultiple permissionsYou can set up multiple permissions checks, simply adding more classes. Permission is evaluated for every class.
If one of the checks fails, access is denied.classCustomPetNode(AuthNode,DjangoObjectType):permission_classes=(AllowAuthenticated,AllowStaff,AllowCustom)classMeta:model=Petinterfaces=(relay.Node,)
Package: graphene-permissions2
Fork fromredzej/graphene-permissionsForked from the original repository and modified to run on the latest graphene (3.2~)graphene-permissionsPermission system for graphene-django apps.OverviewDRF-inspired permission system based on classes for graphene-django. Allows easy customization of permission classes for
for queries and mutations.RequirementsPython 3.5+Django 2.0+graphene-django 2.0+InstallationInstall using pip:pip install graphene-permissionsExampleTo enforce permission system, add appropriate mixin and set attributepermission_classes.### models.pyfromdjango.dbimportmodelsclassPet(models.Model):name=models.CharField(max_length=32)race=models.CharField(max_length=64)### schema.pyfromgrapheneimportrelayfromgraphene_djangoimportDjangoObjectTypefromgraphene_permissions.mixinsimportAuthNodefromgraphene_permissions.permissionsimportAllowAuthenticatedclassPetNode(AuthNode,DjangoObjectType):permission_classes=(AllowAuthenticated,)classMeta:model=Petfilter_fields=('name',)interfaces=(relay.Node,)DocsSetting up permission checkFor queries useAuthNodemixin and inherite fromAuthFilterclass.classAllowAuthenticatedPetNode(AuthNode,DjangoObjectType):permission_classes=(AllowAuthenticated,)classMeta:model=Petfilter_fields=('name',)interfaces=(relay.Node,)classAllowAuthenticatedFilter(AuthFilter):permission_classes=(AllowAuthenticated,)classPetsQuery:user_pet=relay.Node.Field(AllowAuthenticatedPetNode)all_user_pets=AllowAuthenticatedFilter(AllowAuthenticatedPetNode)For mutations useAuthMutationmixin.classAuthenticatedAddPet(AuthMutation,ClientIDMutation):permission_classes=(AllowAuthenticated,)pet=graphene.Field(AllowAuthenticatedPetNode)classInput:name=graphene.String()race=graphene.String()owner=graphene.ID()@classmethoddefmutate_and_get_payload(cls,root,info,**input):ifcls.has_permission(root,info,input):owner=User.objects.get(pk=from_global_id(input['owner'])[1])pet=Pet.objects.create(name=input['name'],race=input['race'],owner=owner)returnAuthenticatedAddPet(pet=pet)returnAuthenticatedAddPet(pet=None)classPetsMutation:authenticated_add_pet=AuthenticatedAddPet.Field()Customizing permission classesDefault permission classes are:AllowAny,AllowAuthenticated,AllowStaff.
You can set up equal permission for both queries and mutations with one class, simply subclass one of these classes
and to limit access for given object, override appropriate method. Remember to returntrueif user should be given
access andfalse, if denied.classAllowMutationForStaff(AllowAuthenticated):@staticmethoddefhas_node_permission(info,id):# logic here# return boolean@staticmethoddefhas_mutation_permission(root,info,input):ifinfo.request.user.is_staff:returnTruereturnFalse@staticmethoddefhas_filter_permission(info):# logic here# return booleanMultiple permissionsYou can set up multiple permissions checks, simply adding more classes. Permission is evaluated for every class.
If one of the checks fails, access is denied.classCustomPetNode(AuthNode,DjangoObjectType):permission_classes=(AllowAuthenticated,AllowStaff,AllowCustom)classMeta:model=Petinterfaces=(relay.Node,)
Package: graphene-prisma
Graphene prismaBrings prisma playground to graphene and moreInstallTo installgraphene_prisma, you need to specify one of the supported frameworkspipinstallgraphene_prisma[framework]orpipinstallgraphene_prismapipinstallframeworkSupported frameworks :responderstarlettee.g. starlettepipinstallgraphene_prisma[starlette]UsageTo usegraphene_prismafromgraphene_prisma.[framework]import[GraphQLHandler][framework]: name of the framework (responder, starlette,...)[GraphQLHandler]: name of the graphql view in your framework (GraphQLViewforresponderandGraphQLAppforstarlette)Here is a list of the graphql classes for each frameworkframeworkGraphQL viewresponderGraphQLViewstarletteGraphQLAppStarlettefromstarlette.applicationsimportStarlettefromgraphene_prisma.starletteimportGraphQLAppclassQuery(graphene.ObjectType):hello=graphene.String(name=graphene.String(default_value="stranger"))defresolve_hello(self,info,name):returnf"Hello{name}"app=Starlette()app.add_route('/',GraphQLApp(schema=graphene.Schema(query=Query)))Responderimportresponderfromgraphene_prisma.responderimportGraphQLViewapi=responder.API()classQuery(graphene.ObjectType):hello=graphene.String(name=graphene.String(default_value="stranger"))defresolve_hello(self,info,name):returnf"Hello{name}"schema=graphene.Schema(query=Query)view=GraphQLView(api=api,schema=schema)api.add_route("/graph",view)api.run()TODOSupport other frameworks (django, flask,...)TestsUpload
Package: graphene-prometheus
graphene-prometheus📊 Prometheus exporter middleware for the Graphene GraphQL framework.This is still under development. Use at your own risk.UsageInstall usingpip install graphene-prometheusorpoetry add graphene-prometheus.Grapheneimportgraphene_prometheusschema.execute("THE QUERY",middleware=[graphene_prometheus.PrometheusMiddleware()])Seehttps://docs.graphene-python.org/en/latest/execution/middleware/#middlewarefor more information.DjangoInsettings.py:GRAPHENE={"MIDDLEWARE":["graphene_prometheus.PrometheusMiddleware"],}Seehttps://docs.graphene-python.org/projects/django/en/latest/settings/#middlewarefor more information.FastAPI / StarletteComing soon.