2

我对 GCP 很陌生,不确定 Cloud Functions 是否适合此问题。

  1. 我有一个 python 脚本,它使用 tweepy 调用 twitter api,并生成一个 csv 文件,其中包含该特定用户名的推文列表。
#!/usr/bin/env python
# -*- coding: utf-8 -*-

import tweepy
import datetime
import csv

def fetchTweets(username):
  # credentials from https://apps.twitter.com/
  consumerKey = "" # hidden for security reasons
  consumerSecret = "" # hidden for security reasons
  accessToken = "" # hidden for security reasons
  accessTokenSecret = "" # hidden for security reasons

  auth = tweepy.OAuthHandler(consumerKey, consumerSecret)
  auth.set_access_token(accessToken, accessTokenSecret)

  api = tweepy.API(auth)

  startDate = datetime.datetime(2019, 1, 1, 0, 0, 0)
  endDate =   datetime.datetime.now()
  print (endDate)

  tweets = []
  tmpTweets = api.user_timeline(username)

  for tweet in tmpTweets:
      if tweet.created_at < endDate and tweet.created_at > startDate:
          tweets.append(tweet)

  lastid = ""
  while (tmpTweets[-1].created_at > startDate and tmpTweets[-1].id != lastid):
      print("Last Tweet @", tmpTweets[-1].created_at, " - fetching some more")
      lastid = tmpTweets[-1].id
      tmpTweets = api.user_timeline(username, max_id = tmpTweets[-1].id)
      for tweet in tmpTweets:
          if tweet.created_at < endDate and tweet.created_at > startDate:
              tweets.append(tweet)

  # # for CSV

  #transform the tweepy tweets into a 2D array that will populate the csv   
  outtweets = [[tweet.id_str, tweet.created_at, tweet.text.encode("utf-8")] for tweet in tweets]

  #write the csv    
  with open('%s_tweets.csv' % username, 'w', newline='') as f:
    writer = csv.writer(f)
    writer.writerow(["id","created","text"])
    writer.writerows(outtweets)
  pass

  f = open('%s_tweets.csv' % username, "r")
  contents = f.read()
  return contents

fetchTweets('usernameofusertoretrieve') # this will be set manually in production
  1. 我想运行这个脚本并return contents通过http请求检索结果(作为csv文件或作为),例如使用javascript。该脚本只需要每天运行一次。但生成的数据 (csv) 应根据需要提供。

因此,我的问题是

一个。GCP Cloud Functions 是完成这项工作的正确工具吗?还是这需要更广泛的东西,因此需要一个 GCP VM 实例?

湾。需要对代码进行哪些更改才能使其在 GCP 上运行?

任何有关方向的帮助/建议也值得赞赏。

4

1 回答 1

3

如果没有更多细节,您的问题就不容易回答。但是,我会尝试提供一些见解

GCP Cloud Functions 是完成这项工作的正确工具吗?还是这需要更广泛的东西,因此需要一个 GCP VM 实例?

这取决于。使用 1 个 CPU,您的处理时间是否会少于 9 分钟?您的进程是否会占用少于 2Gb 的内存(应用程序内存占用 + 文件大小 +tweets数组大小)?

为什么是文件大小?因为只有/tmp目录是可写的,而且它是一个内存文件系统。

如果你需要长达 15 分钟的超时时间,你可以看看Cloud Run,非常类似于 Cloud Function ,我个人更喜欢。Cloud Function 和 Cloud Run 的 CPU 和内存限制相同(但在 2020 年应该会改变,CPU 和内存更多)

需要对代码进行哪些更改才能使其在 GCP 上运行?

首先从/tmp目录写入和读取。最后,如果您希望您的文件全天可用,请将其存储在 Cloud Storage ( https://cloud.google.com/storage/docs ) 并在函数开始时检索它。如果不存在,则为当天生成它,否则获取现有的。

然后,将函数的签名替换为def fetchTweets(username):def fetchTweets(request):获取请求参数中的用户名

最后,如果您想要每天生成一代,请设置一个Cloud Scheduler 。


你没说安全。我建议您以私有模式部署您的功能

所以,这个答案中有很多 GCP 无服务器概念,我不知道你对 GCP 的了解。如果您想要某些零件的精度,请不要犹豫!

于 2020-01-21T08:26:58.263 回答