按计划在Google App Engine上运行python脚本

时间:2019-01-17 22:46:56

标签: python-3.x google-app-engine cron google-cloud-platform google-cloud-firestore

我正在寻找一款优秀的撒玛利亚人,它可以提供非常基本的框架来使用Google App Engine运行python脚本。我已经阅读了文档,检查了相关的SO问题,但是我对WebApp格式迷失了。我要做的就是每周运行6次运行一个接受参数的python脚本或几个python脚本,以监听网站中的更改,然后将其发布到Firestore。

我了解cron格式和大多数配置文件。我对如何为项目安排文件以及网址的工作方式感到困惑。

我要问的是一个关于如何有效运行python脚本的非常基本的示例。 This是迄今为止我发现的最好的资源,但是我真的无法理解该站点中此代码的作用:

`#!/usr/bin/python
# -*- coding: utf-8 -*- 
from __future__ import unicode_literals   
from google.appengine.ext import webapp 
from google.appengine.ext.webapp.util import run_wsgi_app 
from google.appengine.ext import db   
import feedparser  
import time   

class Item(db.Model): 
    title = db.StringProperty(required=False)
    link = db.StringProperty(required=False)
    date = db.StringProperty(required=False)   class Scrawler(webapp.RequestHandler):

    def get(self):
        self.read_feed()      
        self.response.out.write(self.print_items())

    def read_feed(self):

        feeds = feedparser.parse( "http://www.techrepublic.com/search?t=14&o=1&mode=rss" )

        for feed in feeds[ "items" ]:
            query = Item.gql("WHERE link = :1", feed[ "link" ])
            if(query.count() == 0):
                item = Item()
                item.title = feed[ "title" ]
                item.link = feed[ "link" ]
                item.date = time.strftime("%Y-%m-%d %H:%M:%S", time.gmtime(time.time()))
                item.put()

    def print_items(self):
        s = "All items:<br>"
        for item in Item.all():
            s += item.date + " - <a href='" + item.link + "'>" + item.title + "</a><br>"
        return s   application = webapp.WSGIApplication([('/', Scrawler)], debug=True)   def main():
    run_wsgi_app(application)   if __name__ == "__main__":
    main() `

这是我尝试使用python3.7进行测试的python脚本:

import sys
from datetime import datetime

import firebase_admin
from firebase_admin import firestore

app = firebase_admin.initialize_app()
db = firestore.client()


def hello_firestore(user_name):
    db.collection('firestore_test').document('test').set({
        'time': str(datetime.now()),
        'user_name': user_name
    })


if __name__ == "__main__":
    try:
        user_name = sys.argv[1]
    except:
        print('Error with the argument', file=sys.stderr)
    try:
        hello_firestore(user_name)
    except:
        print('Error accessing the database', file=sys.stderr)
        sys.exit(0)

对于我所了解的,我必须使用Flask或类似的东西才能使其工作,但我并不太了解它是如何工作的,我要问的只是一个小样本和简短的解释,从那里我ll加两个和两个。

最好的问候

2 个答案:

答案 0 :(得分:4)

最后,我的孩子们会再次爱我。 原来我正在查看错误的GCP资源,如@Dan_Cornilescu指出的那样,这可能是一种解决方法,但最简单的方法是与“ Cloud Scheduler”结合使用“ Cloud Functions”,我发现它只是通过只是机会。

This文章是提到它的第一篇文章,由于我的需求和缺乏技术上的got惜,我暂时无法使用,因为授课者再次使用Web应用程序来说明这种情况。不要挖它。 但这确实和您想象中的一样简单,在您的Google Cloud Console中:

  1. 转到“功能”部分
  2. 选择作为触发器“ Cloud Pub / Sub”
  3. 添加/选择主题
  4. 选择运行时(当然是Python3.7)
  5. 选择要执行的功能
  6. 创建
  7. 确保在下一个标签上填写“ requirements.txt”文件
  8. 转到GCP的Cloud Scheduler部分并创建一个作业(cron作业)
  9. 选择目标:“发布/订阅”
  10. 输入您选择的功能主题
  11. 如果要为函数发送参数,请使用有效负载  为此目的。

要为您的Python函数使用一个或多个参数,您要使用有效负载并从其初始函数中使用以下参数:

pubsub_message = base64.b64decode(event['data']).decode('utf-8')

您可以将此pubsub_message用作python函数的参数。

这就是所有人,容易,超级容易,最后,我认为这就像没有可视页面的GAE一样,正是我所需要的,我知道必须有一个更好的方法。

编辑:我在这里提到的文章描述了如何使用gcloud直接从计算机上载您的函数。

enter image description here

答案 1 :(得分:1)

我提到的answer仍然适用-您将无法在GAE cron上以独立方式运行脚本,仅因为cron服务实际上只是一组计划的GET请求。您也许可以达到相同的最终结果,但是可以:

  • 安装框架应用程序
  • 将脚本分解为代码,并在请求的查询字符串中传递参数,然后将该代码填充到应用的处理程序中
  • 配置cron服务以生成并触发这些请求

您可以在Quickstart for Python 3 in the App Engine Standard Environment中找到Python 3骨架

当然,您当然可以使用IaaS服务而不是GAE,例如Google Compute Engine,在那里您可以使用传统的cron服务直接运行脚本。

相关问题