How to get request headers when resolving field?
paymog opened this issue · comments
What's the right way to get request header when resolving a query/mutation? A related issue, #17, lead me to believe that info.context.headers
will work but I'm finding that doesn't exist when I try to print it:
❮❮❮ curl -i -H 'Content-Type: application/json' -H 'x-authorization-info: testing' -X POST -d '{"query": "query { latestSnapshot { url } }"}' http://localhost:5000/graphql
HTTP/1.0 200 OK
Content-Type: application/json
Content-Length: 160
Server: Werkzeug/0.14.1 Python/3.6.7
Date: Thu, 18 Apr 2019 22:21:51 GMT
{"errors":[{"message":"'dict' object has no attribute 'headers'","locations":[{"line":1,"column":9}],"path":["latestSnapshot"]}],"data":{"latestSnapshot":null}}%
with a resolver of:
def resolve_latest_snapshot(self, info: ResolveInfo, org_id: Optional[int] = None) -> models.Snapshot:
print(info.context.headers)
# more stuff
I have flask-graphql version 2.0.0.
EDIT: other related packages I have:
graphene==2.1.3
graphql-core==2.1
graphql-relay==0.4.5
graphql-server-core==1.1.1
graphene-sqlalchemy==2.1.1
Oh, looks like
from flask import request
def resolve_latest_snapshot(self, info: ResolveInfo, org_id: Optional[int] = None) -> models.Snapshot:
print(request.headers)
# more stuff
works. I wonder if there's a better, more graphene-y solution...
Looks like context
is request
(if you haven't overrided it): https://github.com/graphql-python/flask-graphql/blob/master/flask_graphql/graphqlview.py#L41
So probably info.context
is request
, and headers are in info.context.headers
, but I haven't verified it.
When trying to access info.context
in mutation I get
"graphql.error.located_error.GraphQLLocatedError: Working outside of request context"
Pretty simple setup:
class SomeMutation(graphene.Mutation):
"""
"""
def mutate(self, info):
"""
"""
print(info.context)
... snip...
return
class Mutation(graphene.ObjectType):
"""
"""
some_mutation = SomeMutation.Field()
schema = graphene.Schema(query=Query, mutation=Mutation, subscription=Subscription)
app.add_url_rule('/graphql',
view_func=GraphQLView.as_view('graphql',
schema=schema,
batch=True,
graphiql=False,
executor=GeventExecutor(),
)
)