-
Notifications
You must be signed in to change notification settings - Fork 0
/
lambda_function.py
85 lines (72 loc) · 2.32 KB
/
lambda_function.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
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Author:Lijiacai
Email:[email protected]
===========================================
===========================================
"""
import os
import sys
import json
import logging
from flask import Flask, jsonify
from flask_cors import CORS
from flask import request
from flask_graphql import GraphQLView
try:
reload(sys)
sys.setdefaultencoding("utf8")
except:
pass
from controller.schema import schema
def lambda_handler(event, context):
# TODO implement
operationName = event.get("operationName")
query = event.get("query")
if not query:
return {
"statusCode": 200,
"body": json.dumps({"errors": [{"message": "请给query参数"}]})}
variables = event.get("variables")
headers = event.get("headers", {})
result = schema.execute(query, variables=variables, context={"headers": headers})
if result.errors:
logging.exception(str(result.errors))
errors_list = []
for error in result.errors:
if "Cannot query field" in str(error.message):
message = "字段错误"
# todo: 这里新增错误类型
else:
message = str(error.message)
try:
stack = str(error.stack) + "-" + str(error.message) + "-" + str(error.locations)
except:
stack = str(error.message)
errors_list.append(
{"message": message, "stack": stack})
body = {"errors": errors_list}
else:
body = {"data": result.data}
response = {
"statusCode": 200,
"body": json.dumps(body)
}
return response
def flask_handler():
app = Flask(__name__)
CORS(app, supports_credentials=True)
@app.route("/graphql_api", methods=["POST"])
def api():
event = request.data.decode("utf8")
event = json.loads(event)
event["headers"] = request.headers
return jsonify(json.loads(lambda_handler(event, None).get("body")))
app.add_url_rule('/graphql_doc_ui', view_func=GraphQLView.as_view('graphql',
schema=schema, graphiql=True))
return app
app = flask_handler()
if __name__ == '__main__':
app.run(port=4901, debug=True, host="0.0.0.0")