我是编程的初学者,所以希望能在这里得到一些帮助。
我的问题: 我得到了这段代码:
import os, json, subprocess, sys
import CallExternalServiceConfig as c
from flask import Flask, jsonify
DATAS = "datas"
SOURCE_FOLDER = "source_folder"
NAME_SCRIPT = "name_script"
PARAMETERS = "parameters"
with open("CallScript.json", "r") as read_file:
data = json.load(read_file)
for trigger in data[DATAS]:
adress=trigger[SOURCE_FOLDER]
namescript=trigger[NAME_SCRIPT]
parameter=trigger[PARAMETERS]
app= Flask(__name__)
@app.route('/Test/<string:jsonname>/')
def action():
#try:
subprocess.call([adress+namescript, parameter.split(",")], shell=True)
print(parameter.split(","))
return jsonify(adress+namescript)
if __name__ == "__main__":
app.run(host=c.get(c.SERVER_HOST, '127.0.0.1'), port=int(c.get(c.SERVER_PORT,
'5000')));
,我想从网址中获取jsonname
字符串,并用它来替换{{1}},以便其动态。但是我不知道如何在"CallScript.json"
函数之外访问该变量。
我正在使用Flask
答案 0 :(得分:0)
首先,我们初始化要在函数外部访问的变量。然后,当调用URL时,我们将json文件名传递给一个函数,该函数会将这些参数重置为该json文件中的值。
adress = ""
namescript = ""
parameter = ""
def read_json(filename):
with open(filename, "r") as read_file:
data = json.load(read_file)
for trigger in data[DATAS]:
adress=trigger[SOURCE_FOLDER]
namescript=trigger[NAME_SCRIPT]
parameter=trigger[PARAMETERS]
@app.route('/Test/<string:jsonname>/')
def action():
json_name = request.args.get('jsonname', default = '', type = str) + ".json"
read_json(json_name)
调用路由时,json_name
现在将设置为URL中的任何参数。
答案 1 :(得分:0)
import os, json, subprocess, sys
import CallExternalServiceConfig as c
from flask import Flask, jsonify
DATAS = "datas"
SOURCE_FOLDER = "source_folder"
NAME_SCRIPT = "name_script"
PARAMETERS = "parameters"
app= Flask(__name__)
@app.route('/Test/<string:jsonname>/')
def action():
json_name = request.args.get('jsonname', default = '', type = str)
with open(json_name + ".json", "r") as read_file:
data = json.load(read_file)
for trigger in data[DATAS]:
adress=trigger[SOURCE_FOLDER]
namescript=trigger[NAME_SCRIPT]
parameter=trigger[PARAMETERS]
subprocess.call([adress+namescript, parameter.split(",")], shell=True)
print(parameter.split(","))
return jsonify(adress+namescript)
if __name__ == "__main__":
app.run(host=c.get(c.SERVER_HOST, '127.0.0.1'), port=int(c.get(c.SERVER_PORT,
'5000')));