我正在创建一个Flask服务器,其中将包含各种Python程序。我希望管理员能够从Flask应用程序中执行它们。例如,如果他们单击一个按钮,它将执行Python脚本。
当前,当我运行服务器时,Python文件和Flask服务器将顺序执行。像这样,首先执行Python文件,然后运行Flask服务器(但只有在我终止Python程序之后)。
作为参考,Python文件允许用户通过在窗口中双击图像来在图像上绘制点。
routes.py
from app import app, db
from flask import Flask, request, render_template, session
import datasets
app.secret_key = app.config['SECRET_KEY']
/*--------------IRREVEVANT CODE BEGINS---------------*/
@app.route('/')
@app.route('/index')
def index():
#Create connection session between SQLAlchemy database and server
#Select ALL records in tables Lot
#Store queries in data and push to INDEX template
data = db.session.execute("SELECT * FROM Lot").fetchall()
return render_template('index.html', data=data)
@app.route('/info/<lot_id>')
def info(lot_id):
lotid = lot_id
#Create connection session between SQLAlchemy database and server
#Select records in table Spot based on LOT_ID parameter
#Store queries in data and push to INFO template
data = db.session.execute("SELECT * FROM Spot WHERE lot_id = :lotid;", {"lotid": lotid}).fetchall()
return render_template('info.html', data=data)
/*------------IRRELEVANT CODE ENDS--------------*/
@app.route('/test')
def test():
return datasets.click_and_crop()
if __name__ == '__main__':
app.run(host='0.0.0.0', port='8000', debug=True)
datasets.py
import cv2
import yaml
import numpy as np
file_path = 'parking_spots.yml'
img = cv2.imread('test1.jpg')
refPt = []
data = []
cropping = False
def yaml_loader(file_path):
with open(file_path, "r") as file_descr:
data = yaml.load(file_descr)
return data
def yaml_dump(file_path, data):
with open(file_path, "a") as file_descr:
yaml.dump(data, file_descr)
def click_and_crop(event, x, y, flags, param):
info = {'id': 0, 'points': []}
global refPt, cropping
if event == cv2.EVENT_LBUTTONDBLCLK:
refPt.append((x,y))
cropping = False
if len(refPt) == 4:
if data == []:
if yaml_loader(file_path) != None:
new_data = len(yaml_loader(file_path))
else:
new_data = 0
else:
if yaml_loader(file_path) != None:
new_data = len(data) + len(yaml_loader(file_path))
else:
new_data = len(data)
cv2.line(image, refPt[0], refPt[1], (0, 0, 255), 2)
cv2.line(image, refPt[1], refPt[2], (0, 0, 255), 2)
cv2.line(image, refPt[2], refPt[3], (0, 0, 255), 2)
cv2.line(image, refPt[3], refPt[0], (0, 0, 255), 2)
corner_1 = list(refPt[2])
corner_2 = list(refPt[3])
corner_3 = list(refPt[0])
corner_4 = list(refPt[1])
info['points'] = [corner_1, corner_2, corner_3, corner_4]
info['id'] = new_data + 1
data.append(info)
refPt = []
image = cv2.resize(img, None, fx=0.6, fy=0.6)
clone = image.copy()
cv2.namedWindow("Click to mark points")
cv2.imshow("Click to mark points", image)
cv2.setMouseCallback("Click to mark points", click_and_crop)
while True:
cv2.imshow("Click to mark points", image)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
# data list into yaml file
if data != []:
yaml_dump(file_path, data)
cv2.destroyAllWindows()
在这种情况下,我希望Python程序仅在您进入localhost/test
网址时才能运行。 Flask服务器将运行,然后,当单击一个将您带到该URL的按钮时,Python程序将同时运行直到终止。
答案 0 :(得分:0)
对于在这里找到自己的任何人,我都想出了解决这个特殊问题的方法。
正如@roganjosh所提到的,from dateutil import parser
created_at = parser.parse(field_1[0]["created_at"])
语句一经解释,便在执行import requests
from dateutil import parser
URL='https://api.thingspeak.com/channels/CHANNELID/fields/1.json?api_key='
KEY='READ KEY'
HEADER='&results=1'
TIMEZONE='&timezone=America%2FChicago'
NEW_URL=URL+KEY+HEADER+TIMEZONE
#print(NEW_URL)
get_data=requests.get(NEW_URL).json()
#print(get_data)
channel_id=get_data['channel']['id']
field_1=get_data['feeds']
print(field_1)
float_numb = float(field_1[0]["field1"])
created_at = parser.parse(field_1[0]["created_at"])
中的功能。为防止这种情况,您需要在文件中包含import
,该文件告诉系统仅在datasets
未调用指定功能时才执行指定的功能。
我的if __name__ == "__main__"
代码特别要提到的另一个“问题”是,从服务器内部调用import
无效,因为该函数需要参数。我通过创建一个datasets.py
方法并调用它来缓解了这种情况。完整的解决方案如下:
datasets.py
click_and_crop
routes.py
main()