Comments (10)
I'm working on something with no security implications (all data is public), so s a make-shift solution (don't use in production), I'm registering (pseudo code) all models using the following approach crufty:
import Base # = some declarative_base(cls=mixin), see [1]
import graphene
class Query(graphene.ObjectType): pass
for k, v in Base._decl_class_registry.items():
setattr(Query, k.lower(), v)
setattr(Query, 'resolve_%s' % k, lambda self, args, info: v.get(args.get('id')).dict()) #dict() coming from [1]
[1] see https://github.com/thegroovebox/api.groovebox.org/blob/master/groovebox/api/core.py#L33
Note: _decl_class_registry has some non-models registered with it (e.g. _sa_module_registry), so additional error handling / logic is required.
from graphene.
@jfeinstein10 already did an amazing work trying to integrate sqlalchemy
into graphene
.
I'm going to fork its sqlalchemy graphene branch and preserve his work updated with the recent changes of graphene.
from graphene.
Work in progress pull request: #87
from graphene.
@jfeinstein10 I saw this code :
class SQLAlchemyNode(BaseNode, SQLAlchemyInterface):
id = GlobalIDField()
@classmethod
def get_node(cls, id, info=None):
try:
instance = cls._meta.model.filter(id=id).one()
return cls(instance)
except cls._meta.model.DoesNotExist:
return None
In the cls._meta.model.filter(id=id).one()
, I'm concern:
- use a django like model query , not original sqlalchemy orm usage.
- use id as id. Relay ID is a string, model id maybe integer always.
@syrusakbary I'm working on sqlalchemy backend, any progress would be interested.
from graphene.
@gwind some code ported by @jfeinstein10 was not updated to reflect the SQLAlchemy nature, as you exposed.
However is actually fixed by some commits I did recently: https://github.com/graphql-python/graphene/blob/sqlalchemy/graphene/contrib/sqlalchemy/types.py#L122
- The Relay ID field have to be a String, by spec. The field id in the SQLAlchemy model is mapped to an integer, but this query
.filter(id='1')
works also well in this cases.
Feel free to fork this work and do any improvements!
from graphene.
@syrusakbary may be a raise NotImplementedError()
would be a good choice.
I have a local sqlachemy binding, but it is very basic, and i am not familiar with graphql - relay.
Thanks,
from graphene.
@syrusakbary I've saw that graphene.relay.NodeField
in root query would convert original id (int or string) to a uniq ID ( type + id => base64) .
So my concern about instance = cls._meta.model.filter(id=id).one()
was wrong: id is the object id in table exactly now.
I've another question: the graphene convert all id to type + id => base64
string, but how to get object by id nicely?
example:
class RootQuery(graphene.ObjectType):
group = graphene.Field(Group, id=graphene.String().NonNull)
def resolve_group(self, args, info):
print("args.get('id') = ", args.get('id'))
this query is ok:
query MyQuery {
node (id: "R3JvdXA6NA==") {
id
... on Group {
name
description
}
}
}
but query one object is failed:
query MyQuery {
group(id:"R3JvdXA6NA==") {
id
name
}
}
In graphene/relay/types , there is a to_global_id() , but no a reverse method such like from_global_id() :
class Node(six.with_metaclass(NodeMeta, Interface)):
'''An object with an ID'''
id = GlobalIDField()
class Meta:
abstract = True
def to_global_id(self):
type_name = self._meta.type_name
return to_global_id(type_name, self.id)
connection_type = Connection
edge_type = Edge
@classmethod
def get_connection_type(cls):
return cls.connection_type
@classmethod
def get_edge_type(cls):
return cls.edge_type
graphql_relay/node/node.py have a from_global_id() indeed
def from_global_id(global_id):
'''
Takes the "global ID" created by toGlobalID, and retuns the type name and ID
used to create it.
'''
unbased_global_id = unbase64(global_id)
_type, _id = unbased_global_id.split(':', 1)
return ResolvedGlobalId(_type, _id)
Is there a nice method to handle this ?
from graphene.
Graphene is using from_global_id
from graphql_relay
right now.
However you can customize the id_fetcher
function in NodeField
(https://github.com/graphql-python/graphene/blob/master/graphene/relay/fields.py#L68)
from graphene.
I see, thanks 😄
from graphene.
SQLAlchemy support is now merged into master, closing the issue 😎
from graphene.
Related Issues (20)
- Enum conversion to Graphene Enum fails if Enum name is "type" HOT 1
- Enum equality comparison is inconsistent
- http://www.graphene-python.org Has EXPIRED HOT 3
- Upload file HOT 2
- Unexpected argument in Pycharm 2023.2.1 HOT 1
- Default_value option in Arguments inside Mutation is not working as expected HOT 2
- Exception: NonNull could not have a mounted String() as inner type. Try with NonNull(String).
- Returning non fatal errors alongside data HOT 1
- Conversion to snake_case fails on nested inputs
- Depth limit validator key error if fragment undefined
- Tests in `graphene/relay/tests/test_custom_global_id.py` fail due incompatibility with pytest 8.x HOT 2
- Enum.from_enum() fails with Django IntegerChoices
- Do you support GQL over websocket? HOT 1
- More documentation for DisableIntrospection?
- Subclass built-in scalars without creating new GraphQL type
- In 3.1.0, `resolve_type` method on Interfaces and Unions no longer supports returning the GraphQL Type as a string HOT 1
- release 3.4.0 HOT 2
- grphene.List not work correctly HOT 1
- When passing the empty string to Date Type, it occurs `IndexError: string index out of range` HOT 2
- Schema execution timing out after upgrade from 2.1.9 to 3.3
Recommend Projects
-
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
Vue.js
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
TensorFlow
An Open Source Machine Learning Framework for Everyone
-
Django
The Web framework for perfectionists with deadlines.
-
Laravel
A PHP framework for web artisans
-
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.
-
Visualization
Some thing interesting about visualization, use data art
-
Game
Some thing interesting about game, make everyone happy.
Recommend Org
-
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Microsoft
Open source projects and samples from Microsoft.
-
Google
Google ❤️ Open Source for everyone.
-
Alibaba
Alibaba Open Source for everyone
-
D3
Data-Driven Documents codes.
-
Tencent
China tencent open source team.
from graphene.