我一直在尝试按照教程进行操作,以使烧瓶应用程序在Heroku上运行,例如:https://dev.to/emcain/how-to-set-up-a-twitter-bot-with-python-and-heroku-1n39。
他们都告诉您将其放在代码server.py
中:
from flask import Flask
app = Flask(__name__)
app.run(host='0.0.0.0')
然后通过以下命令运行该应用程序:
python3 server.py
但是这些教程没有说明如何使用该应用程序连接要运行的实际功能。就我而言,我有一个文件testbot.py
,它的功能test(arg1)
包含我要执行的代码:
def test(arg1):
while(1):
#do stuff with arg1 on twitter
我想做这样的事情:
from flask import Flask
from testbot import test
from threading import Thread
app = Flask(__name__)
app.addfunction(test(arg1='hardcodedparameter'))
app.run(host='0.0.0.0')
这样,当应用程序运行时,我的test()
函数将使用参数执行。现在我的服务器正在启动,但是什么也没发生。
我是否正在正确考虑?
*编辑:我已将其与解决方案配合使用,因此我的server.py
现在看起来像这样:
from flask import Flask
from testbot import test
def main_process():
test("hardcodeparam")
app = Flask(__name__)
Thread(target=main_process).start()
app.run(debug=True,host='0.0.0.0')
现在test
运行正常。
答案 0 :(得分:0)
在app.run
之前,使用路径注册函数,例如
@app.route('/')
def test(): # no argument
... do one iteration
return 'ok'
然后访问URL将触发该功能。根据建议https://cron-job.org/,像here这样的网站可以免费自动进行定期访问。
如果常规间隔不够好,则可以尝试:
@app.route('/')
def index(): # no argument
return 'ok'
def test():
while True:
# do stuff
from threading import Thread
Thread(target=test).start()
app.run(...)
您可能仍然需要定期访问URL,以便Heroku可以看到服务器处于运行状态。