2017-07-12 164 views
0

经过几天的搜索并寻找此问题后,我无法找到正确的答案。无法在Google App Engine上运行Cron作业(Python)

我试图在Google App Engine上运行cron作业(使用Python)。 cron作业本身并不重要,我只是想每分钟运行一次python脚本。现在,我只是试图用当前时间在一个单独的文本文件(test.txt)中添加一行。

我很确定我不太了解处理程序的概念,这就是导致我出现问题的原因。但是我花了几个小时的时间在文档上,但我仍然无法弄清楚。

我觉得我不应该使用main.py作为cron作业的脚本,但我很难理解cron.yaml中的url需要什么,以及处理程序/脚本应该是什么。

请帮忙!

Here's a list of my files.

的app.yaml

runtime: python 
env: flex 
entrypoint: gunicorn -b :$PORT main:app 

runtime_config: 
    python_version: 3 

handlers: 
- url: /main 
    script: main.py 

cron.yaml

cron: 
- description : most recent test 
    url : /main 
    schedule: every 1 minutes 

main.py

# Copyright 2015 Google Inc. All Rights Reserved. 
# 
# Licensed under the Apache License, Version 2.0 (the "License"); 
# you may not use this file except in compliance with the License. 
# You may obtain a copy of the License at 
# 
#  http://www.apache.org/licenses/LICENSE-2.0 
# 
# Unless required by applicable law or agreed to in writing, software 
# distributed under the License is distributed on an "AS IS" BASIS, 
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 
# See the License for the specific language governing permissions and 
# limitations under the License. 

# [START app] 
import logging 
from datetime import datetime 

current_time = str(datetime.now()) 

from flask import Flask 


app = Flask(__name__) 


@app.route('/') 
def hello(): 
    """Return a friendly HTTP greeting.""" 
    return 'Hello World! The time is ' + current_time 

    message = "this worked, as of " + current_time + "\n" 

    with open("test.txt", "a") as myfile: 
     myfile.write(message) 


@app.errorhandler(500) 
def server_error(e): 
    logging.exception('An error occurred during a request.') 
    return """ 
    An internal error occurred: <pre>{}</pre> 
    See logs for full stacktrace. 
    """.format(e), 500 


if __name__ == '__main__': 
    # This is used when running locally. Gunicorn is used to run the 
    # application on Google App Engine. See entrypoint in app.yaml. 
    app.run(host='127.0.0.1', port=8080, debug=True) 
# [END app] 

回答

1

您的app.yaml文件正在将标准环境Handlers元素混合到flexible environment配置中,因此可能会忽略它。

cron.yaml配置显示了一个/main网址为您的cron作业,但您的应用程序似乎并不具备这样的URL路径的路线,似乎只处理/路径。我希望你会在/main cron请求的日志中看到一些404错误。

您应该在main.py中为/main路径添加路线。或在cron.yaml中用/代替/main

旁注:你有一些非可执行代码(它如下return语句)内hello() - 万一你要寻找的是test.txt文件...

1

你没有网址处理程序/main。试试这个:

app.yaml中

:在main.py

handlers: 
- url: /.*  # wildcard. every url goes there 
    script: main.py 

from flask import Response 

@app.route('/main') 
def main(): 
    """Return a friendly HTTP greeting.""" 
    Response("Hello main viewer", mimetype='text/plain') 

注:在你的代码的另一种错误是返回的HTML视图前的脚本得到了有机会编写.txt文件。它永远不会那么远。

+0

感谢您的帮助!我做了更改,但仍然无法正常工作。我更改了main.py中的url,在main.py中添加了代码,并确保在html视图返回之前调用在text.txt中添加行的代码。 –

相关问题