python flask grathql

tech2023-05-24  85

1 安装依赖包

pip install flask flask-graphql flask-migrate sqlalchemy graphene graphene-sqlalchemy psycopg2

2 demo app.py

# Imports from flask import Flask from flask_sqlalchemy import SQLAlchemy import graphene from graphene_sqlalchemy import SQLAlchemyObjectType, SQLAlchemyConnectionField from flask_graphql import GraphQLView # initializing our app app = Flask(__name__) app.debug = True # Configs # Replace the user, password, hostname and database according to your configuration information app.config['SQLALCHEMY_DATABASE_URI'] = 'postgresql://postgres:postgres@localhost:5432/postgres' app.config['SQLALCHEMY_COMMIT_ON_TEARDOWN'] = True app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = True # Modules db = SQLAlchemy(app) # Models class User(db.Model): __tablename__ = 'users' id = db.Column(db.Integer, primary_key=True) username = db.Column(db.String(80), unique=True, index=True) email = db.Column(db.String(120), unique=True, nullable=False) books = db.relationship('Book', backref='author') def __init__(self, username, email): self.username = username self.email = email def __repr__(self): return '<User %r>' % self.id class Book(db.Model): __tablename__ = 'books' id = db.Column(db.Integer, primary_key=True) title = db.Column(db.String(256), index=True, nullable=False) description = db.Column(db.Text, nullable=False) year = db.Column(db.Integer, nullable=False) author_id = db.Column(db.Integer, db.ForeignKey('users.id')) def __repr__(self): return '<Book %r>' % self.title % self.description % self.year % self.author_id class Author(db.Model): __tablename__ = 'authors' id = db.Column(db.Integer, primary_key=True) Name = db.Column(db.String(256), index=True, nullable=False) def __repr__(self): return '<Author %r>' % self.id %self.Name # Schema Objects class BookObject(SQLAlchemyObjectType): class Meta: model = Book interfaces = (graphene.relay.Node, ) # Schema Objects class AuthorObject(SQLAlchemyObjectType): class Meta: model = Author interfaces = (graphene.relay.Node, ) class UserObject(SQLAlchemyObjectType): class Meta: model = User interfaces = (graphene.relay.Node, ) class Query(graphene.ObjectType): node = graphene.relay.Node.Field() all_books = SQLAlchemyConnectionField(BookObject,id=graphene.Int(),description="通过 Id 查询") def resolve_all_books(self,info,**args): query=BookObject.get_query(info) # return Book.query.filter_by(id=args.get("id")) return query.filter_by(id=args.get("id")) all_users = SQLAlchemyConnectionField(UserObject) all_authors=SQLAlchemyConnectionField(AuthorObject) schema = graphene.Schema(query=Query) class AddBook(graphene.Mutation): class Arguments: title = graphene.String(required=True) description = graphene.String(required=True) year = graphene.Int(required=True) username = graphene.String(required=True) book = graphene.Field(lambda: BookObject) def mutate(self, info, title, description, year, username): user = User.query.filter_by(username=username).first() book = Book(title=title, description=description, year=year) if user is not None: book.author = user db.session.add(book) db.session.commit() return AddBook(book=book) class Mutation(graphene.ObjectType): add_book = AddBook.Field() schema = graphene.Schema(query=Query, mutation=Mutation) # Routes app.add_url_rule( '/graphql-api', view_func=GraphQLView.as_view( 'graphql', schema=schema, graphiql=True # for having the GraphiQL interface ) ) @app.route('/') def index(): return 'Welcome to Book Store Api' if __name__ == '__main__': app.run()

adddata.py

from app import db, User, Book # mike = User(username='mikedean', email='mikedean@gmail.com') # db.session.add(mike) # db.session.commit() flaskbook = Book() flaskbook.title = "fff" flaskbook.description = "fff" flaskbook.year = 2019 flaskbook.author_id = 1 db.session.add(flaskbook) db.session.commit()

3 查询

{ allBooks{ edges{ node{ title description author{ username } } } } }

4 修改

mutation { addBook( username:"mikedean", title:"Intro to GraphQL", description:"Welcome to the course", year:2018){ book{ title description author{ username } } } }

5 后续详解补充

最新回复(0)