どのようにジャンゴ、tweepyとファウナとつぶやきマネージャを構築する.
Authored in connection with the Write with Fauna program.
Tweet Analyticsの追跡と管理が容易になりました.この記事では、動物園とデータベースを実装して、Django WebフレームワークとTweepyを使用してつぶやき管理アプリケーションを構築するためにご案内いたします.このつぶやきマネージャは、ユーザーがつぶやきAnalytics、あなたがつぶやきの動向を追跡し、簡単に参照するためのデータベース内の現在のつぶやき情報のレポートを保存することができます.
必要条件
このチュートリアルを十分に理解するには、次のようにします.
目次
動物相入門
ファウナは、グラフレスAPIで様々なデータ型と特にリレーショナルデータベースをサポートするために、GraphSQLとFauna質問言語(FQL)を使用するクライアント側のデータベースレスデータベースです.あなたは彼らの公式文書で動物の詳細を学ぶことができます.あなたがFAONAについて聞くのがこれが初めてであるならば、簡単な導入のために私の前の記事Countを訪問してください.
Twitter APIの設定
Twitterの公式APIを使用するには、あなたのTwitterの開発者アカウントを設定する必要があります.サインアップするには、TwitterのAPIへのアクセスを利用する方法についての詳細な情報を提供する必要があります.情報を提供した後、あなたのアカウントを確認し、有効にするためにTwitterを待つ必要があります.
あなたのアカウントが検証されるとき、上記のイメージで見られるように、あなたの開発者ダッシュボードに行きなさい.
この時点で、複数のアプリケーションを格納できるプロジェクトを作成する必要があります.クリックcreate project
次に、プロジェクトに名前、ユースケース、および説明を与えます.
これで、アプリケーションを作成する必要があります.これを行うには、“新しいアプリケーションを作成”をクリックして、アプリケーションの名前を提供します.
あなたのTwitterのアプリケーションを作成した後、下の画像で見られるように、アプリケーションキーでページが表示されます.コピーして簡単にそれらを取得することができますどこかに保存します.
プロジェクトメニューを開き、プロジェクトを開きます.アプリのセクションでは、キーのアイコンをクリックしaccess token
and access secret
ページの下部にあるアプリケーションのトークンが表示されます.
ボタンをクリックして、ActivRankトークンを保存して保存します.
動物相データベースの設定
Foounaデータベースを作成するには、まずアカウントを作成します.を作成した後、あなたはCREATE DATABASE
ダッシュボードのボタン.
上の画像に示すようにボタンをクリックした後、あなたのデータベースに名前を付けて保存する必要があります.
データベースコレクションの作成
データベースに2つのコレクションを作成するFollowers
コレクションとTweetsReport
コレクション.The Followers
コレクションには、データベースにユーザーが持っているフォロワーの現在の数が格納されますTweetsReport
は、データベースに生成されたレポートを格納します.のためにHistory days
and TTL
提供されるデフォルト値を使用して保存します.
コレクションインデックスの作成
あなたのコレクションの2つのインデックスを作成しますreport_index
and followers_index
. The report_index
インデックスでは、データをスクロールすることができますTweetsReport
コレクション.それは1つの用語を持っていますstatus
フィールド.この用語は、簡単にクエリのためのステータスとデータを一致するようになります.
The followers_index
でデータをスクロールできるようになりますFollowers
コレクション.このインデックスは、status
クエリを実行するフィールド.
以下はインデックスを保存した後のようになります.
データベースAPIキーの生成
APIキーを生成するには、ダッシュボードの左側のセキュリティタブに移動し、クリックしますNew Key
キーを作成するにはその後、キーに接続するデータベースを提供する必要があります.必要な情報を提供するSAVE
ボタン.
ファウナはあなたの鍵を保存した後、上記の画像(プライバシーのためにここに隠さ)であなたの秘密鍵を提示します.ダッシュボードから秘密鍵をコピーして、後で後で使用するために簡単にそれを得ることができるどこかにそれを保存してください.
Djangoアプリケーションの構築
今、あなたはつぶやき管理アプリケーションのさまざまな機能を実装する方法を学習されます.
アプリケーションリポジトリのクローン
以下のコードをコマンドラインで実行し、GithubのDjangoアプリを含むREPOをクローンし、必要なすべてのライブラリをインストールします.
#cloning the repo
git clone https://github.com/Chukslord1/FAUNA_TWEETS_MANAGER.git
# installing tweepy
pip install django
# installing tweepy
pip install tweepy
# installing faunadb
pip install faunadb
必要なライブラリのインポート
我々は、すべてのアプリケーションロジックを行いますviews.py
我々のDjangoアプリケーションのためのファイル.あなたのviews.py
下のコードを参照してください.
from django.shortcuts import render,redirect
from django.contrib import messages
from django.core.paginator import Paginator
from django.http import HttpResponseNotFound
from faunadb import query as q
import pytz
from faunadb.objects import Ref
from faunadb.client import FaunaClient
import hashlib
import datetime
import tweepy
from django.http import JsonResponse
import json
ファウナクライアントとツイートの初期化
FaunaクライアントとTweepyを初期化するには、以下のコードをコピーし、必要に応じて作成したAPIキーを提供しますviews.py
ファイル.下記のコードの最初の行で、我々の秘密鍵を提供することによって、我々はFAONAクライアントを初期化しました.次のいくつかの行で、我々はTweepy APIを提供してapi key
, api secret key
, access token
, access token secret
, username
and screen name
これはユーザ名と同じです.
client = FaunaClient(secret="fauna_secret_key")
api_key = "api_key"
api_secret = "api_secret"
access_token = "access_token"
access_token_secret= "access_token_secret"
username= "username"
screen_name=username
auth = tweepy.OAuthHandler(api_key, api_secret)
auth.set_access_token(access_token, access_token_secret)
api = tweepy.API(auth)
user=api.me()
インデックスページの作成
インデックスページは、必要なデータがダッシュボード上のユーザーにレンダリングされる場所です.また、これは私たちのアプリケーションは、さえずるレポートを生成する場所です.我々はこのページのロジックを構築することに焦点を当てます.
最初に、私たちは、Tweepyをその週作成されたすべてのつぶやきに問い合わせる.以下のコードはこの機能を実装します.
# querying tweets created this week
tmpTweets = api.user_timeline(screen_name=username,count=100, include_rts = True)
today = endDate = datetime.datetime.now()
startDate = today - (datetime.timedelta(today.weekday() + 1))
tweets=[]
for tweet in tmpTweets:
if endDate >= tweet.created_at >= startDate:
tweets.append(tweet)
words.extend(set(tweet.text.lower().split()) & all_trends)
# querying for the current trends in your location you tweeted on
COUNTRY_WOE_ID = 23424908 #where on earth id of Nigeria
all_trends = set()
country_trends = api.trends_place(COUNTRY_WOE_ID)
trends = json.loads(json.dumps(country_trends, indent=1))
for trend in trends[0]["trends"]:
all_trends.add((trend["name"].lower().replace("#","")))
tweeted_keywords=(sorted([(i, words.count(i)) for i in set(words)], key=lambda x: x[1], reverse=True))
次に、我々は最後のページ訪問以来、我々が作ったすべての信者のためにTweepyを問い合わせました.我々は、現在の数のフォロワーを救ったFollowers
コレクションは、新しい信者を取得します.以下のコードはこの機能を実装します.
#querying number of new followers since last page visit
# checking if the number of followers is saved. if not, save it
try:
previous_follower = client.query(q.get(q.match(q.index("followers_index"), True)))
previous_follower_count = client.query(q.get(q.match(q.index("followers_index"), True)))["data"]["follower_count"]
except:
follower_count_create = client.query(q.create(q.collection("Followers"),{
"data": {
"follower_count": user.followers_count,
"created_at": datetime.datetime.now(pytz.UTC),
"status":True
}
}))
previous_follower_count=user.followers_count
上のコードでは、フォロワーの数を計算し、Followers
データベースから検索された信者の数と、Tweepyから取得したものが、最後のページを訪問してから異なっている場合、コレクション.
# calculating new followers since last page visit
new_followers=user.followers_count-previous_follower_count
#updating the database if there is a change in followers since last visit
if previous_follower_count == user.followers_count:
pass
else:
follower_count_update = client.query(q.update(q.ref(q.collection("Followers"), previous_follower["ref"].id()), {
"data": {
"follower_count": user.followers_count,
"created_at": datetime.datetime.now(pytz.UTC),
"status":True,
}
}))
最後にレポート作成ロジックを作成しました.以下のコードはこの機能を実装します.
# generating a report for the tweets currently and saving in the database
if request.method=="POST":
generate=request.POST.get("generated")
report_date= datetime.datetime.now(pytz.UTC)
report_details = "Number of followers :"+str(user.followers_count) + "\n Number following :"+str(user.friends_count) + "\n Number of Tweets This Week :"+str(len(tweets)) + "\n New Followers: "+str(new_followers)+ "\n Trends You Tweeted On:"+str(tweeted_keywords)
if generate == "True":
report_create = client.query(q.create(q.collection("TweetsReport"), {
"data": {
"report_date": report_date,
"report_details": report_details,
"status": True
}
}))
上のコードでは、ユーザーが投稿要求を送信すると、レポートを作成するために必要なデータが照合され、TweetsReport
コレクションは、ファウナクライアントからのクエリを行うことによって.
インデックスビューの最終コードは、以下のようになります.
def index(request):
# querying tweets created this week
tmpTweets = api.user_timeline(screen_name=username,count=100, include_rts = True)
today = endDate = datetime.datetime.now()
startDate = today - (datetime.timedelta(today.weekday() + 1))
tweets=[]
new_followers=0
words=[]
all_trends = set()
COUNTRY_WOE_ID = 23424908
country_trends = api.trends_place(COUNTRY_WOE_ID)
trends = json.loads(json.dumps(country_trends, indent=1))
for trend in trends[0]["trends"]:
all_trends.add((trend["name"].lower().replace("#","")))
for tweet in tmpTweets:
if endDate >= tweet.created_at >= startDate:
tweets.append(tweet)
words.extend(set(tweet.text.lower().split()) & all_trends)
tweeted_keywords=(sorted([(i, words.count(i)) for i in set(words)], key=lambda x: x[1], reverse=True))
try:
previous_follower = client.query(q.get(q.match(q.index("followers_index"), True)))
previous_follower_count = client.query(q.get(q.match(q.index("followers_index"), True)))["data"]["follower_count"]
except:
follower_count_create = client.query(q.create(q.collection("Followers"),{
"data": {
"follower_count": user.followers_count,
"created_at": datetime.datetime.now(pytz.UTC),
"status":True
}
}))
previous_follower_count=user.followers_count
new_followers=user.followers_count-previous_follower_count
if previous_follower_count == user.followers_count:
pass
else:
follower_count_update = client.query(q.update(q.ref(q.collection("Followers"), previous_follower["ref"].id()), {
"data": {
"follower_count": user.followers_count,
"created_at": datetime.datetime.now(pytz.UTC),
"status":True,
}
}))
if request.method=="POST":
generate=request.POST.get("generated")
report_date= datetime.datetime.now(pytz.UTC)
report_details = "Number of followers :"+str(user.followers_count) + "\n Number following :"+str(user.friends_count) + "\n Number of Tweets This Week :"+str(len(tweets)) + "\n New Followers: "+str(new_followers)+ "\n Trends You Tweeted On:"+str(tweeted_keywords)
if generate == "True":
report_create = client.query(q.create(q.collection("TweetsReport"), {
"data": {
"report_date": report_date,
"report_details": report_details,
"status": True
}
}))
context={"followers":user.followers_count,"following":user.friends_count,"weekly_tweet":len(tweets),"new_followers":new_followers}
return render(request,"index.html",context)
レポートページの作成
ユーザーは、彼らが生成し、このページのデータベースに保存されているすべてのレポートを表示することができます.
def reports(request):
get_reports= client.query(q.paginate(q.match(q.index("report_index"), True)))
all_reports=[]
for i in get_reports["data"]:
all_reports.append(q.get(q.ref(q.collection("TweetsReport"),i.id())))
reports=client.query(all_reports)
context={"reports":reports}
return render(request,"reports.html",context)
上記のコードでは、FAONAクライアントに対して、TweetsReport
ステータスフィールドがtrueのコレクションreports_index
インデックスと動物のPaginate方法.このデータは、それからユーザーによって、表示されるユーザーインターフェースに、文脈において、表示される.
アプリケーションのURL
ここでは、必要なモジュールをインポートし、我々のアプリのURLを定義されたビューに接続定義されます.
from django.conf import settings
from django.conf.urls.static import static
from django.urls import path, include
from . import views
app_name = "App"
urlpatterns = [
path("", views.index, name="index"),
path("index", views.index, name="index"),
path("reports", views.reports, name="reports"),
]
結論
この記事はどのようにつぶやき管理アプリケーションを構築する方法を教えてFauna's serverless database , tweepyとdjango.私たちはどのように簡単にパイナップルを使用して、Twitterからのデータをクエリには、Pythonのアプリケーションに動物を統合し、それらを保存してください.
当社のつぶやきマネージャのソースコードが利用可能ですGithub . 質問がある場合は、Twitterで私に連絡することを躊躇しないでください.
Reference
この問題について(どのようにジャンゴ、tweepyとファウナとつぶやきマネージャを構築する.), 我々は、より多くの情報をここで見つけました
https://dev.to/chukslord1/building-a-tweets-manager-with-django-tweepy-and-fauna-2aea
テキストは自由に共有またはコピーできます。ただし、このドキュメントのURLは参考URLとして残しておいてください。
Collection and Share based on the CC Protocol
Twitterの公式APIを使用するには、あなたのTwitterの開発者アカウントを設定する必要があります.サインアップするには、TwitterのAPIへのアクセスを利用する方法についての詳細な情報を提供する必要があります.情報を提供した後、あなたのアカウントを確認し、有効にするためにTwitterを待つ必要があります.
あなたのアカウントが検証されるとき、上記のイメージで見られるように、あなたの開発者ダッシュボードに行きなさい.
この時点で、複数のアプリケーションを格納できるプロジェクトを作成する必要があります.クリック
create project
次に、プロジェクトに名前、ユースケース、および説明を与えます.これで、アプリケーションを作成する必要があります.これを行うには、“新しいアプリケーションを作成”をクリックして、アプリケーションの名前を提供します.
あなたのTwitterのアプリケーションを作成した後、下の画像で見られるように、アプリケーションキーでページが表示されます.コピーして簡単にそれらを取得することができますどこかに保存します.
プロジェクトメニューを開き、プロジェクトを開きます.アプリのセクションでは、キーのアイコンをクリックし
access token
and access secret
ページの下部にあるアプリケーションのトークンが表示されます.ボタンをクリックして、ActivRankトークンを保存して保存します.
動物相データベースの設定
Foounaデータベースを作成するには、まずアカウントを作成します.を作成した後、あなたはCREATE DATABASE
ダッシュボードのボタン.
上の画像に示すようにボタンをクリックした後、あなたのデータベースに名前を付けて保存する必要があります.
データベースコレクションの作成
データベースに2つのコレクションを作成するFollowers
コレクションとTweetsReport
コレクション.The Followers
コレクションには、データベースにユーザーが持っているフォロワーの現在の数が格納されますTweetsReport
は、データベースに生成されたレポートを格納します.のためにHistory days
and TTL
提供されるデフォルト値を使用して保存します.
コレクションインデックスの作成
あなたのコレクションの2つのインデックスを作成しますreport_index
and followers_index
. The report_index
インデックスでは、データをスクロールすることができますTweetsReport
コレクション.それは1つの用語を持っていますstatus
フィールド.この用語は、簡単にクエリのためのステータスとデータを一致するようになります.
The followers_index
でデータをスクロールできるようになりますFollowers
コレクション.このインデックスは、status
クエリを実行するフィールド.
以下はインデックスを保存した後のようになります.
データベースAPIキーの生成
APIキーを生成するには、ダッシュボードの左側のセキュリティタブに移動し、クリックしますNew Key
キーを作成するにはその後、キーに接続するデータベースを提供する必要があります.必要な情報を提供するSAVE
ボタン.
ファウナはあなたの鍵を保存した後、上記の画像(プライバシーのためにここに隠さ)であなたの秘密鍵を提示します.ダッシュボードから秘密鍵をコピーして、後で後で使用するために簡単にそれを得ることができるどこかにそれを保存してください.
Djangoアプリケーションの構築
今、あなたはつぶやき管理アプリケーションのさまざまな機能を実装する方法を学習されます.
アプリケーションリポジトリのクローン
以下のコードをコマンドラインで実行し、GithubのDjangoアプリを含むREPOをクローンし、必要なすべてのライブラリをインストールします.
#cloning the repo
git clone https://github.com/Chukslord1/FAUNA_TWEETS_MANAGER.git
# installing tweepy
pip install django
# installing tweepy
pip install tweepy
# installing faunadb
pip install faunadb
必要なライブラリのインポート
我々は、すべてのアプリケーションロジックを行いますviews.py
我々のDjangoアプリケーションのためのファイル.あなたのviews.py
下のコードを参照してください.
from django.shortcuts import render,redirect
from django.contrib import messages
from django.core.paginator import Paginator
from django.http import HttpResponseNotFound
from faunadb import query as q
import pytz
from faunadb.objects import Ref
from faunadb.client import FaunaClient
import hashlib
import datetime
import tweepy
from django.http import JsonResponse
import json
ファウナクライアントとツイートの初期化
FaunaクライアントとTweepyを初期化するには、以下のコードをコピーし、必要に応じて作成したAPIキーを提供しますviews.py
ファイル.下記のコードの最初の行で、我々の秘密鍵を提供することによって、我々はFAONAクライアントを初期化しました.次のいくつかの行で、我々はTweepy APIを提供してapi key
, api secret key
, access token
, access token secret
, username
and screen name
これはユーザ名と同じです.
client = FaunaClient(secret="fauna_secret_key")
api_key = "api_key"
api_secret = "api_secret"
access_token = "access_token"
access_token_secret= "access_token_secret"
username= "username"
screen_name=username
auth = tweepy.OAuthHandler(api_key, api_secret)
auth.set_access_token(access_token, access_token_secret)
api = tweepy.API(auth)
user=api.me()
インデックスページの作成
インデックスページは、必要なデータがダッシュボード上のユーザーにレンダリングされる場所です.また、これは私たちのアプリケーションは、さえずるレポートを生成する場所です.我々はこのページのロジックを構築することに焦点を当てます.
最初に、私たちは、Tweepyをその週作成されたすべてのつぶやきに問い合わせる.以下のコードはこの機能を実装します.
# querying tweets created this week
tmpTweets = api.user_timeline(screen_name=username,count=100, include_rts = True)
today = endDate = datetime.datetime.now()
startDate = today - (datetime.timedelta(today.weekday() + 1))
tweets=[]
for tweet in tmpTweets:
if endDate >= tweet.created_at >= startDate:
tweets.append(tweet)
words.extend(set(tweet.text.lower().split()) & all_trends)
# querying for the current trends in your location you tweeted on
COUNTRY_WOE_ID = 23424908 #where on earth id of Nigeria
all_trends = set()
country_trends = api.trends_place(COUNTRY_WOE_ID)
trends = json.loads(json.dumps(country_trends, indent=1))
for trend in trends[0]["trends"]:
all_trends.add((trend["name"].lower().replace("#","")))
tweeted_keywords=(sorted([(i, words.count(i)) for i in set(words)], key=lambda x: x[1], reverse=True))
次に、我々は最後のページ訪問以来、我々が作ったすべての信者のためにTweepyを問い合わせました.我々は、現在の数のフォロワーを救ったFollowers
コレクションは、新しい信者を取得します.以下のコードはこの機能を実装します.
#querying number of new followers since last page visit
# checking if the number of followers is saved. if not, save it
try:
previous_follower = client.query(q.get(q.match(q.index("followers_index"), True)))
previous_follower_count = client.query(q.get(q.match(q.index("followers_index"), True)))["data"]["follower_count"]
except:
follower_count_create = client.query(q.create(q.collection("Followers"),{
"data": {
"follower_count": user.followers_count,
"created_at": datetime.datetime.now(pytz.UTC),
"status":True
}
}))
previous_follower_count=user.followers_count
上のコードでは、フォロワーの数を計算し、Followers
データベースから検索された信者の数と、Tweepyから取得したものが、最後のページを訪問してから異なっている場合、コレクション.
# calculating new followers since last page visit
new_followers=user.followers_count-previous_follower_count
#updating the database if there is a change in followers since last visit
if previous_follower_count == user.followers_count:
pass
else:
follower_count_update = client.query(q.update(q.ref(q.collection("Followers"), previous_follower["ref"].id()), {
"data": {
"follower_count": user.followers_count,
"created_at": datetime.datetime.now(pytz.UTC),
"status":True,
}
}))
最後にレポート作成ロジックを作成しました.以下のコードはこの機能を実装します.
# generating a report for the tweets currently and saving in the database
if request.method=="POST":
generate=request.POST.get("generated")
report_date= datetime.datetime.now(pytz.UTC)
report_details = "Number of followers :"+str(user.followers_count) + "\n Number following :"+str(user.friends_count) + "\n Number of Tweets This Week :"+str(len(tweets)) + "\n New Followers: "+str(new_followers)+ "\n Trends You Tweeted On:"+str(tweeted_keywords)
if generate == "True":
report_create = client.query(q.create(q.collection("TweetsReport"), {
"data": {
"report_date": report_date,
"report_details": report_details,
"status": True
}
}))
上のコードでは、ユーザーが投稿要求を送信すると、レポートを作成するために必要なデータが照合され、TweetsReport
コレクションは、ファウナクライアントからのクエリを行うことによって.
インデックスビューの最終コードは、以下のようになります.
def index(request):
# querying tweets created this week
tmpTweets = api.user_timeline(screen_name=username,count=100, include_rts = True)
today = endDate = datetime.datetime.now()
startDate = today - (datetime.timedelta(today.weekday() + 1))
tweets=[]
new_followers=0
words=[]
all_trends = set()
COUNTRY_WOE_ID = 23424908
country_trends = api.trends_place(COUNTRY_WOE_ID)
trends = json.loads(json.dumps(country_trends, indent=1))
for trend in trends[0]["trends"]:
all_trends.add((trend["name"].lower().replace("#","")))
for tweet in tmpTweets:
if endDate >= tweet.created_at >= startDate:
tweets.append(tweet)
words.extend(set(tweet.text.lower().split()) & all_trends)
tweeted_keywords=(sorted([(i, words.count(i)) for i in set(words)], key=lambda x: x[1], reverse=True))
try:
previous_follower = client.query(q.get(q.match(q.index("followers_index"), True)))
previous_follower_count = client.query(q.get(q.match(q.index("followers_index"), True)))["data"]["follower_count"]
except:
follower_count_create = client.query(q.create(q.collection("Followers"),{
"data": {
"follower_count": user.followers_count,
"created_at": datetime.datetime.now(pytz.UTC),
"status":True
}
}))
previous_follower_count=user.followers_count
new_followers=user.followers_count-previous_follower_count
if previous_follower_count == user.followers_count:
pass
else:
follower_count_update = client.query(q.update(q.ref(q.collection("Followers"), previous_follower["ref"].id()), {
"data": {
"follower_count": user.followers_count,
"created_at": datetime.datetime.now(pytz.UTC),
"status":True,
}
}))
if request.method=="POST":
generate=request.POST.get("generated")
report_date= datetime.datetime.now(pytz.UTC)
report_details = "Number of followers :"+str(user.followers_count) + "\n Number following :"+str(user.friends_count) + "\n Number of Tweets This Week :"+str(len(tweets)) + "\n New Followers: "+str(new_followers)+ "\n Trends You Tweeted On:"+str(tweeted_keywords)
if generate == "True":
report_create = client.query(q.create(q.collection("TweetsReport"), {
"data": {
"report_date": report_date,
"report_details": report_details,
"status": True
}
}))
context={"followers":user.followers_count,"following":user.friends_count,"weekly_tweet":len(tweets),"new_followers":new_followers}
return render(request,"index.html",context)
レポートページの作成
ユーザーは、彼らが生成し、このページのデータベースに保存されているすべてのレポートを表示することができます.
def reports(request):
get_reports= client.query(q.paginate(q.match(q.index("report_index"), True)))
all_reports=[]
for i in get_reports["data"]:
all_reports.append(q.get(q.ref(q.collection("TweetsReport"),i.id())))
reports=client.query(all_reports)
context={"reports":reports}
return render(request,"reports.html",context)
上記のコードでは、FAONAクライアントに対して、TweetsReport
ステータスフィールドがtrueのコレクションreports_index
インデックスと動物のPaginate方法.このデータは、それからユーザーによって、表示されるユーザーインターフェースに、文脈において、表示される.
アプリケーションのURL
ここでは、必要なモジュールをインポートし、我々のアプリのURLを定義されたビューに接続定義されます.
from django.conf import settings
from django.conf.urls.static import static
from django.urls import path, include
from . import views
app_name = "App"
urlpatterns = [
path("", views.index, name="index"),
path("index", views.index, name="index"),
path("reports", views.reports, name="reports"),
]
結論
この記事はどのようにつぶやき管理アプリケーションを構築する方法を教えてFauna's serverless database , tweepyとdjango.私たちはどのように簡単にパイナップルを使用して、Twitterからのデータをクエリには、Pythonのアプリケーションに動物を統合し、それらを保存してください.
当社のつぶやきマネージャのソースコードが利用可能ですGithub . 質問がある場合は、Twitterで私に連絡することを躊躇しないでください.
Reference
この問題について(どのようにジャンゴ、tweepyとファウナとつぶやきマネージャを構築する.), 我々は、より多くの情報をここで見つけました
https://dev.to/chukslord1/building-a-tweets-manager-with-django-tweepy-and-fauna-2aea
テキストは自由に共有またはコピーできます。ただし、このドキュメントのURLは参考URLとして残しておいてください。
Collection and Share based on the CC Protocol
今、あなたはつぶやき管理アプリケーションのさまざまな機能を実装する方法を学習されます.
アプリケーションリポジトリのクローン
以下のコードをコマンドラインで実行し、GithubのDjangoアプリを含むREPOをクローンし、必要なすべてのライブラリをインストールします.
#cloning the repo
git clone https://github.com/Chukslord1/FAUNA_TWEETS_MANAGER.git
# installing tweepy
pip install django
# installing tweepy
pip install tweepy
# installing faunadb
pip install faunadb
必要なライブラリのインポート
我々は、すべてのアプリケーションロジックを行います
views.py
我々のDjangoアプリケーションのためのファイル.あなたのviews.py
下のコードを参照してください.from django.shortcuts import render,redirect
from django.contrib import messages
from django.core.paginator import Paginator
from django.http import HttpResponseNotFound
from faunadb import query as q
import pytz
from faunadb.objects import Ref
from faunadb.client import FaunaClient
import hashlib
import datetime
import tweepy
from django.http import JsonResponse
import json
ファウナクライアントとツイートの初期化
FaunaクライアントとTweepyを初期化するには、以下のコードをコピーし、必要に応じて作成したAPIキーを提供します
views.py
ファイル.下記のコードの最初の行で、我々の秘密鍵を提供することによって、我々はFAONAクライアントを初期化しました.次のいくつかの行で、我々はTweepy APIを提供してapi key
, api secret key
, access token
, access token secret
, username
and screen name
これはユーザ名と同じです.client = FaunaClient(secret="fauna_secret_key")
api_key = "api_key"
api_secret = "api_secret"
access_token = "access_token"
access_token_secret= "access_token_secret"
username= "username"
screen_name=username
auth = tweepy.OAuthHandler(api_key, api_secret)
auth.set_access_token(access_token, access_token_secret)
api = tweepy.API(auth)
user=api.me()
インデックスページの作成
インデックスページは、必要なデータがダッシュボード上のユーザーにレンダリングされる場所です.また、これは私たちのアプリケーションは、さえずるレポートを生成する場所です.我々はこのページのロジックを構築することに焦点を当てます.
最初に、私たちは、Tweepyをその週作成されたすべてのつぶやきに問い合わせる.以下のコードはこの機能を実装します.
# querying tweets created this week
tmpTweets = api.user_timeline(screen_name=username,count=100, include_rts = True)
today = endDate = datetime.datetime.now()
startDate = today - (datetime.timedelta(today.weekday() + 1))
tweets=[]
for tweet in tmpTweets:
if endDate >= tweet.created_at >= startDate:
tweets.append(tweet)
words.extend(set(tweet.text.lower().split()) & all_trends)
# querying for the current trends in your location you tweeted on
COUNTRY_WOE_ID = 23424908 #where on earth id of Nigeria
all_trends = set()
country_trends = api.trends_place(COUNTRY_WOE_ID)
trends = json.loads(json.dumps(country_trends, indent=1))
for trend in trends[0]["trends"]:
all_trends.add((trend["name"].lower().replace("#","")))
tweeted_keywords=(sorted([(i, words.count(i)) for i in set(words)], key=lambda x: x[1], reverse=True))
次に、我々は最後のページ訪問以来、我々が作ったすべての信者のためにTweepyを問い合わせました.我々は、現在の数のフォロワーを救ったFollowers
コレクションは、新しい信者を取得します.以下のコードはこの機能を実装します.#querying number of new followers since last page visit
# checking if the number of followers is saved. if not, save it
try:
previous_follower = client.query(q.get(q.match(q.index("followers_index"), True)))
previous_follower_count = client.query(q.get(q.match(q.index("followers_index"), True)))["data"]["follower_count"]
except:
follower_count_create = client.query(q.create(q.collection("Followers"),{
"data": {
"follower_count": user.followers_count,
"created_at": datetime.datetime.now(pytz.UTC),
"status":True
}
}))
previous_follower_count=user.followers_count
上のコードでは、フォロワーの数を計算し、Followers
データベースから検索された信者の数と、Tweepyから取得したものが、最後のページを訪問してから異なっている場合、コレクション.# calculating new followers since last page visit
new_followers=user.followers_count-previous_follower_count
#updating the database if there is a change in followers since last visit
if previous_follower_count == user.followers_count:
pass
else:
follower_count_update = client.query(q.update(q.ref(q.collection("Followers"), previous_follower["ref"].id()), {
"data": {
"follower_count": user.followers_count,
"created_at": datetime.datetime.now(pytz.UTC),
"status":True,
}
}))
最後にレポート作成ロジックを作成しました.以下のコードはこの機能を実装します.# generating a report for the tweets currently and saving in the database
if request.method=="POST":
generate=request.POST.get("generated")
report_date= datetime.datetime.now(pytz.UTC)
report_details = "Number of followers :"+str(user.followers_count) + "\n Number following :"+str(user.friends_count) + "\n Number of Tweets This Week :"+str(len(tweets)) + "\n New Followers: "+str(new_followers)+ "\n Trends You Tweeted On:"+str(tweeted_keywords)
if generate == "True":
report_create = client.query(q.create(q.collection("TweetsReport"), {
"data": {
"report_date": report_date,
"report_details": report_details,
"status": True
}
}))
上のコードでは、ユーザーが投稿要求を送信すると、レポートを作成するために必要なデータが照合され、TweetsReport
コレクションは、ファウナクライアントからのクエリを行うことによって.インデックスビューの最終コードは、以下のようになります.
def index(request):
# querying tweets created this week
tmpTweets = api.user_timeline(screen_name=username,count=100, include_rts = True)
today = endDate = datetime.datetime.now()
startDate = today - (datetime.timedelta(today.weekday() + 1))
tweets=[]
new_followers=0
words=[]
all_trends = set()
COUNTRY_WOE_ID = 23424908
country_trends = api.trends_place(COUNTRY_WOE_ID)
trends = json.loads(json.dumps(country_trends, indent=1))
for trend in trends[0]["trends"]:
all_trends.add((trend["name"].lower().replace("#","")))
for tweet in tmpTweets:
if endDate >= tweet.created_at >= startDate:
tweets.append(tweet)
words.extend(set(tweet.text.lower().split()) & all_trends)
tweeted_keywords=(sorted([(i, words.count(i)) for i in set(words)], key=lambda x: x[1], reverse=True))
try:
previous_follower = client.query(q.get(q.match(q.index("followers_index"), True)))
previous_follower_count = client.query(q.get(q.match(q.index("followers_index"), True)))["data"]["follower_count"]
except:
follower_count_create = client.query(q.create(q.collection("Followers"),{
"data": {
"follower_count": user.followers_count,
"created_at": datetime.datetime.now(pytz.UTC),
"status":True
}
}))
previous_follower_count=user.followers_count
new_followers=user.followers_count-previous_follower_count
if previous_follower_count == user.followers_count:
pass
else:
follower_count_update = client.query(q.update(q.ref(q.collection("Followers"), previous_follower["ref"].id()), {
"data": {
"follower_count": user.followers_count,
"created_at": datetime.datetime.now(pytz.UTC),
"status":True,
}
}))
if request.method=="POST":
generate=request.POST.get("generated")
report_date= datetime.datetime.now(pytz.UTC)
report_details = "Number of followers :"+str(user.followers_count) + "\n Number following :"+str(user.friends_count) + "\n Number of Tweets This Week :"+str(len(tweets)) + "\n New Followers: "+str(new_followers)+ "\n Trends You Tweeted On:"+str(tweeted_keywords)
if generate == "True":
report_create = client.query(q.create(q.collection("TweetsReport"), {
"data": {
"report_date": report_date,
"report_details": report_details,
"status": True
}
}))
context={"followers":user.followers_count,"following":user.friends_count,"weekly_tweet":len(tweets),"new_followers":new_followers}
return render(request,"index.html",context)
レポートページの作成
ユーザーは、彼らが生成し、このページのデータベースに保存されているすべてのレポートを表示することができます.
def reports(request):
get_reports= client.query(q.paginate(q.match(q.index("report_index"), True)))
all_reports=[]
for i in get_reports["data"]:
all_reports.append(q.get(q.ref(q.collection("TweetsReport"),i.id())))
reports=client.query(all_reports)
context={"reports":reports}
return render(request,"reports.html",context)
上記のコードでは、FAONAクライアントに対して、TweetsReport
ステータスフィールドがtrueのコレクションreports_index
インデックスと動物のPaginate方法.このデータは、それからユーザーによって、表示されるユーザーインターフェースに、文脈において、表示される.アプリケーションのURL
ここでは、必要なモジュールをインポートし、我々のアプリのURLを定義されたビューに接続定義されます.
from django.conf import settings
from django.conf.urls.static import static
from django.urls import path, include
from . import views
app_name = "App"
urlpatterns = [
path("", views.index, name="index"),
path("index", views.index, name="index"),
path("reports", views.reports, name="reports"),
]
結論
この記事はどのようにつぶやき管理アプリケーションを構築する方法を教えてFauna's serverless database , tweepyとdjango.私たちはどのように簡単にパイナップルを使用して、Twitterからのデータをクエリには、Pythonのアプリケーションに動物を統合し、それらを保存してください.
当社のつぶやきマネージャのソースコードが利用可能ですGithub . 質問がある場合は、Twitterで私に連絡することを躊躇しないでください.
Reference
この問題について(どのようにジャンゴ、tweepyとファウナとつぶやきマネージャを構築する.), 我々は、より多くの情報をここで見つけました
https://dev.to/chukslord1/building-a-tweets-manager-with-django-tweepy-and-fauna-2aea
テキストは自由に共有またはコピーできます。ただし、このドキュメントのURLは参考URLとして残しておいてください。
Collection and Share based on the CC Protocol
Reference
この問題について(どのようにジャンゴ、tweepyとファウナとつぶやきマネージャを構築する.), 我々は、より多くの情報をここで見つけました https://dev.to/chukslord1/building-a-tweets-manager-with-django-tweepy-and-fauna-2aeaテキストは自由に共有またはコピーできます。ただし、このドキュメントのURLは参考URLとして残しておいてください。
Collection and Share based on the CC Protocol