31
loading...
This website collects cookies to deliver better user experience
Authored in connection with the Write with Fauna program.
create project
then give your project a name, use case, and a description.access token
and access secret
token for your application at the bottom of the page displayed.CREATE DATABASE
button on the dashboard.Followers
collection, and the TweetsReport
collection. The Followers
collection will store the current number of followers the user has in the database, while the TweetsReport
will store the reports generated in the database. For the History days
and TTL
use the default values provided and save.report_index
and followers_index
. The report_index
index will allow you to scroll through data in the TweetsReport
collection. It has one term, which is the status
field. This term will enable you to match data with the status for easy querying.followers_index
will allow you to scroll through data in the Followers
collection. This index will also allow matching with the status
field to perform queries.New Key
to create a key. You will then be required to provide a database to connect to the key. After providing the information required, click the SAVE
button.#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
file for our Django application. Go to your views.py
to see the code below.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
views.py
file. On the first line in the code below, we initialized our Fauna client by providing our secret key. In the following few lines, we initialized out Tweepy API by providing our api key
, api secret key
, access token
, access token secret
, username
and screen name
which is the same as the username.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()
# 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))
Followers
collection to get the new followers. The code below implements this functionality.#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
collection if the number of followers retrieved from the database and the one retrieved from Tweepy are different since the last page visit.# 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
collection by making a query from the Fauna client.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)
TweetsReport
collection where the status field is True using the reports_index
index and Fauna’s paginate method. This data is then rendered in context to the user interface to be viewed by the user.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"),
]