如何在没有flask/Django的heroku上运行一个简单的python脚本?

2024-06-02 07:09:36 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图在我的heroku服务器上运行一个简单的hello world python程序。我是heroku的新手。我成功地将我的脚本部署到了heroku。 我的python脚本和procfile如下所示

嗨,py

print("hello world")

程序文件

web: python hi.py

当我在终端上运行heroku run web时,得到了“Hello world”作为输出,但是当我尝试使用heroku web url运行应用程序时,显示以下错误。

Application Error An error occurred in the application and your page could not be served. Please try again in a few moments.

我在这里做错了什么?我对heroku&its的概念还不熟悉,请直说吧。


Tags: 文件inpy程序服务器脚本webhello
2条回答

Heroku上有three types of dyno configurations可用:

  • Web—接收Web流量。
  • Worker——在后台继续处理任务/队列。
  • 一次性——执行一次。e、 g:后备。

如果您对运行一个脚本感兴趣,不关心在它上接收web流量,并且没有要处理的队列,那么One-off dynos可能是您想要使用的。这对于数据库迁移或备份以及其他方面都很有用。

下面是最简单的例子。


使用Heroku和python的一次性dyno示例AKA“hello world”

这假设您已经在Heroku上创建了应用程序,并且能够从命令行使用Herolu CLI。

一个最小的“hello world”Python脚本将如下所示。只需要2个文件:

  • requirements.txt必需,但可以保留为空。
  • task.py有内容print("hello world")

然后部署到Heroku,例如:

git add .;
git commit -m "My first commit";
git push heroku master

之后,您就可以使用heroku run python task.py运行脚本(并且应该可以在输出中看到等待已久的hello world

如果要在特定时间运行程序,请使用免费的Heroku Scheduler附加模块。

仅供参考,Procfile是可选的。如果将其设置为hello: python task.py,则只需heroku run hello即可运行程序。

(注意,让requirements.txt为空将在部署时触发You must give at least one requirement to install (see "pip help install")警告。不过,这只是一个警告,并不妨碍程序的正确部署。)

我不同意你说你想要烧瓶

主应用程序py

import flask
app = flask.Flask(__name__)

@app.route("/")
def index():
    #do whatevr here...
    return "Hello Heruko"

然后将procfile更改为web: gunicorn main_app:app --log-file -

相关问题 更多 >