【发布时间】:2020-05-07 00:45:20
【问题描述】:
我对 GCP 非常陌生,不确定 Cloud Functions 是否适合此问题。
- 我有一个 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
- 我想运行此脚本并通过 http 请求检索结果(作为 csv 文件或
return contents),例如使用 JavaScript。该脚本只需要每天运行一次。但是生成的数据 (csv) 应该可以根据需要提供。
因此我的问题是
一个。 GCP Cloud Functions 是完成这项工作的正确工具吗?还是这需要更广泛的东西,因此需要一个 GCP VM 实例?
b.需要对代码进行哪些更改才能使其在 GCP 上运行?
也感谢任何有关方向的帮助/建议。
【问题讨论】:
-
这是一个相当广泛的问题。 Cloud Functions 提供了一个可扩展至 0 并满足 REST 请求的计算框架。 Cloud Functions 没有持久存储,因此必须使用 Cloud Storage 的数据库。一种可能性是将 Cloud Function 作为计划作业每天运行一次,这会导致 CSV 存储在 GCS 存储桶中,然后请求者将直接检索文件的内容。基本上,一个 Cloud Function 调用即可从 twitter 中检索您的数据并创建 GCS 文件,其他一切都只是检索该文件。
-
非常感谢您的详细评论。它真的帮助了我。我做了更多阅读并得出了使用 GCS 存储桶的相同解决方案。
标签: python google-cloud-platform google-cloud-functions tweepy twitterapi-python