感谢大家的所有回答,他们有很多帮助。下面是一些工作示例代码,从无参数到参数,然后是带有 json 响应的参数。
希望下面的代码对某人有所帮助。
from flask import Flask
from flask import jsonify
app = Flask(__name__)
@app.route('/')
def helloworld():
response = 'HelloWorld'
return response
@app.route('/mathapi/<int:x>/<int:y>/', methods = ['GET'])
def math(x, y):
result = x + y # Sum x,t -> result
response = '%d + %d = %d' %(x, y, result) #Buld response
return response #Return response
@app.route('/mathapijson/<int:x>/<int:y>/', methods = ['GET'])
def mathjs(x, y):
result = x + y #Sum x,t -> result
data = {'x' : x, 'y' : y, 'result' : result} #Buld arrary
response = jsonify(data) #Convert to json
response.status_code = 200 #Set status code to 200=ok
response.headers['Link'] = 'http://localhost'
return response #return json response
if __name__ == '__main__':
app.run(debug=True)
用法:
localhost:port/ - 输出 - HelloWorld
本地主机:端口/mathapi/3/4/ - 输出= 3 + 4 = 7
本地主机:端口/mathapi/mathapijson/3/4/ - 输出= {“y”:4,“x”:3,“结果”:7}