-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.py
114 lines (77 loc) · 2.54 KB
/
app.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask_graphql import GraphQLView
import graphene
from graphene_sqlalchemy import SQLAlchemyObjectType, SQLAlchemyConnectionField
import os
basedir = os.path.abspath(os.path.dirname(__file__))
print('basedir: '+basedir)
app = Flask(__name__)
app.debug = True
# Configs
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///' + \
os.path.join(basedir, 'data.sqlite')
app.config['SQLALCHEMY_COMMIT_ON_TEARDOWN'] = True
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = True
# Modules
db = SQLAlchemy(app)
# Models
class User(db.Model):
__tablename__ = 'users'
uuid = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(256), index=True, unique=True)
posts = db.relationship('Post', backref='author')
def __repr__(self):
return '<User %r>' % self.username
class Post(db.Model):
__tablename__ = 'posts'
uuid = db.Column(db.Integer, primary_key=True)
title = db.Column(db.String(256), index=True)
body = db.Column(db.Text)
author_id = db.Column(db.Integer, db.ForeignKey('users.uuid'))
def __repr__(self):
return '<Post %r>' % self.title
# Schema Objects
class PostObject(SQLAlchemyObjectType):
class Meta:
model = Post
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_posts = SQLAlchemyConnectionField(PostObject)
all_users = SQLAlchemyConnectionField(UserObject)
class CreatePost(graphene.Mutation):
class Arguments:
title = graphene.String(required=True)
body = graphene.String(required=True)
username = graphene.String(required=True)
post = graphene.Field(lambda: PostObject)
def mutate(self, info, title, body, username):
user = User.query.filter_by(username=username).first()
post = Post(title=title, body=body)
if user is not None:
post.author = user
db.session.add(post)
db.session.commit()
return CreatePost(post=post)
class Mutation(graphene.ObjectType):
create_post = CreatePost.Field()
schema = graphene.Schema(query=Query, mutation=Mutation)
# Routes
app.add_url_rule(
'/graphql',
view_func=GraphQLView.as_view(
'graphql',
schema=schema,
graphiql=True
)
)
@app.route('/')
def index():
return '<p>Hello world</p>'
if __name__ == '__main__':
app.run()