我将数据存储在文件系统中(在多个小文件中进行了标准化),并且编写了python函数来从文件系统读取/写入数据。读取API返回Job类型的对象。 Write API期望Job类型的对象作为参数传递。
def get_jobs(starttime, endtime):
''' Reads and returns jobs that ran between starttime and endtime interval '''
def put_job(job):
''' Persists Job object to a file system '''
class Job:
def __init__(self, name, key, starttime, endtime):
self.name = name
self.key = key
self.starttime = starttime
self.endtime = endtime
现在,我想通过Web服务器公开这些功能。我更喜欢将GraphQL API与Django一起公开。
问题:
注意:
答案 0 :(得分:2)
Django可能是一个(更好但更重)的解决方案,但这是使用Flask的更简单的解决方案:
from flask import Flask, jsonify
app = Flask(__name__)
class Job:
def __init__(self, name, key, starttime, endtime):
self.name = name
self.key = key
self.starttime = starttime
self.endtime = endtime
@app.route("/get", methods=['GET'])
def get_jobs(starttime, endtime):
''' Reads and returns jobs that ran between starttime and endtime interval '''
jobs = read_data(starttime, endtime) # your read_data() method
return jsonify({'jobs': jobs})
@app.route("/put", methods=['POST']) # or methods=['PUT']
def put_job(request):
# access your data trough the request object:
job_name = request.args.get('name', '')
job_key = request.args.get('key', '')
# or get it in json
job_data = request.json
write_data(Job.from_json(job_data))
我在这里使用Json是因为我对此感到更自在,但是如果GraphQL对您来说很重要,我建议您使用Graphene-Python库。