model relationship + minor fixes

This commit is contained in:
Łukasz Jędyk 2022-05-10 11:37:54 +02:00
parent 9d95c8a411
commit 5faadaa69b
6 changed files with 82 additions and 83 deletions

View File

@ -1,9 +1,8 @@
import os import os
from flask import Flask, request from flask import Flask
from ayct_backend.twitter import twitter from ayct_backend.twitter import twitter
from ayct_backend.twitter.models import twitter_db
from ayct_backend.campaign import campaign from ayct_backend.campaign import campaign
from ayct_backend.campaign.models import campaign_db from ayct_backend.models import db
#import pbrAyctCore.core as core #import pbrAyctCore.core as core
def create_app(): def create_app():
@ -17,11 +16,8 @@ def create_app():
app.config['TWITTER_CONSUMER_KEY'] = os.getenv('TWITTER_CONSUMER_KEY') app.config['TWITTER_CONSUMER_KEY'] = os.getenv('TWITTER_CONSUMER_KEY')
app.config['TWITTER_CONSUMER_SECERT'] = os.getenv('TWITTER_CONSUMER_SECERT') app.config['TWITTER_CONSUMER_SECERT'] = os.getenv('TWITTER_CONSUMER_SECERT')
twitter_db.init_app(app) db.init_app(app)
campaign_db.init_app(app) db.create_all(app=app)
twitter_db.create_all(app=app)
campaign_db.create_all(app=app)
app.register_blueprint(twitter, url_prefix='/twitter') app.register_blueprint(twitter, url_prefix='/twitter')
app.register_blueprint(campaign, url_prefix='/campaign') app.register_blueprint(campaign, url_prefix='/campaign')

View File

@ -1,9 +1,9 @@
import requests import requests
import json import json
from uuid import uuid4
from requests_oauthlib import OAuth1Session from requests_oauthlib import OAuth1Session
from flask import Blueprint, current_app, request, jsonify from flask import Blueprint, current_app, request, jsonify
from ayct_backend.twitter.models import * from ayct_backend.models import *
from ayct_backend.campaign.models import *
from ayct_backend.firebase import verify_token from ayct_backend.firebase import verify_token
campaign = Blueprint('campaign', __name__) campaign = Blueprint('campaign', __name__)
@ -16,7 +16,7 @@ def get_twitter_campaigns():
user_id = decoded_token['sub'] user_id = decoded_token['sub']
twitter_campaigns = TwitterCampaign.query.filter_by(user_id=user_id) twitter_campaigns = TwitterCampaign.query.filter_by(user_id=user_id).all()
campaigns = [] campaigns = []
@ -44,7 +44,7 @@ def add_twitter_campaign():
return "Content-type not supported!", 400 return "Content-type not supported!", 400
request_json = request.json request_json = request.json
if not request_json['campaign_name'] or not request_json['user_input'] or not request_json['twitter_account_id']: if 'campaign_name' not in request_json or 'user_input' not in request_json or 'twitter_account_id' not in request_json:
return "Invalid request!", 400 return "Invalid request!", 400
consumer_key = current_app.config["TWITTER_CONSUMER_KEY"] consumer_key = current_app.config["TWITTER_CONSUMER_KEY"]
@ -59,17 +59,18 @@ def add_twitter_campaign():
"length": 420 "length": 420
} }
response = requests.post(core_url, headers={"Content-Type":"application/json"}, data=json.dumps(payload)) #response = requests.post(core_url, headers={"Content-Type":"application/json"}, data=json.dumps(payload))
#generated_content = response.content.decode("utf-8").replace('<|endoftext|>', '').replace(' ', ' ')
generated_content = response.content.decode("utf-8").replace('<|endoftext|>', '').replace(' ', ' ') # trimmed_text = generated_content[:270]
# dot_index = trimmed_text.rfind(".")
# space_index = trimmed_text.rfind(" ")
# if dot_index > 0:
# tweet_text = trimmed_text[:dot_index + 1].capitalize()
# else:
# tweet_text = trimmed_text[:space_index + 1].capitalize()
trimmed_text = generated_content[:270] tweet_text = "This is placeholder content generated by our application. Normal generation doesn't work."
dot_index = trimmed_text.rfind(".")
space_index = trimmed_text.rfind(" ")
if dot_index > 0:
tweet_text = trimmed_text[:dot_index + 1].capitalize()
else:
tweet_text = trimmed_text[:space_index + 1].capitalize()
# create post on twitter # create post on twitter
oauth = OAuth1Session( oauth = OAuth1Session(
@ -86,25 +87,27 @@ def add_twitter_campaign():
# save campaign to database # save campaign to database
twitter_campaign = TwitterCampaign( twitter_campaign = TwitterCampaign(
id = str(uuid4()),
user_id = user_id, user_id = user_id,
campaign_name = request_json['campaign_name'], campaign_name = request_json['campaign_name'],
twitter_account_id = request_json['twitter_account_id'], twitter_account_id = request_json['twitter_account_id'],
user_input = request_json['user_input'], user_input = request_json['user_input'],
) )
campaign_db.session.add(twitter_campaign) db.session.add(twitter_campaign)
campaign_db.session.flush() db.session.flush()
campaign_db.session.refresh() db.session.refresh()
twitter_campaign_post = TwitterPost( twitter_campaign_post = TwitterPost(
id = str(uuid4()),
campaign_id = twitter_campaign.id, campaign_id = twitter_campaign.id,
user_id = user_id, user_id = user_id,
post_content = tweet_text, post_content = tweet_text,
twitter_post_id = response['id'] twitter_post_id = response['id']
) )
campaign_db.session.add(twitter_campaign_post) db.session.add(twitter_campaign_post)
campaign_db.session.commit() db.session.commit()
return "Campaign succesfully created.", 201 return "Campaign succesfully created.", 201
@ -121,16 +124,16 @@ def delete_twitter_campaign():
return "Content-type not supported!", 400 return "Content-type not supported!", 400
request_json = request.json request_json = request.json
if not request_json['campaign_id']: if 'campaign_id' not in request_json:
return "Invalid request!", 400 return "Invalid request!", 400
twitter_campaign = TwitterAccount.query.filter_by(user_id=user_id, id=request_json['campaign_id']) twitter_campaign = TwitterAccount.query.filter_by(user_id=user_id, id=request_json['campaign_id']).first()
if not twitter_campaign: if not twitter_campaign:
return "Account not found!", 404 return "Capmaign not found!", 404
twitter_db.session.delete(twitter_campaign) db.session.delete(twitter_campaign)
twitter_db.session.commit() db.session.commit()
return "Twitter campaign succesfully deleted.", 200 return "Twitter campaign succesfully deleted.", 200
@ -147,11 +150,11 @@ def get_twitter_campaign_details():
return "Content-type not supported!", 400 return "Content-type not supported!", 400
request_json = request.json request_json = request.json
if not request_json['campaign_id']: if 'campaign_id' not in request_json:
return "Invalid request!", 400 return "Invalid request!", 400
twitter_campaign = TwitterCampaign.query.filter_by(user_id=user_id, id=request_json['campaign_id']).first() twitter_campaign = TwitterCampaign.query.filter_by(user_id=user_id, id=request_json['campaign_id']).first()
campaign_posts = TwitterPost.query.filter_by(user_id=user_id, campaign_id=request_json['campaign_id']) campaign_posts = TwitterPost.query.filter_by(user_id=user_id, campaign_id=request_json['campaign_id']).all()
posts = [] posts = []
for post in campaign_posts: for post in campaign_posts:

View File

@ -1,21 +0,0 @@
from flask_sqlalchemy import SQLAlchemy
campaign_db = SQLAlchemy()
class TwitterCampaign(campaign_db.Model):
__tablename__ = 'twitter_campaign'
id = campaign_db.Column(campaign_db.Integer, primary_key=True)
user_id = campaign_db.Column(campaign_db.String(64), nullable=False)
campaign_name = campaign_db.Column(campaign_db.String(64), nullable=False)
twitter_account_id = campaign_db.Column(campaign_db.String(32), nullable=False)
user_input = campaign_db.Column(campaign_db.String(100), nullable=False)
class TwitterPost(campaign_db.Model):
__tablename__ = 'twitter_post'
id = campaign_db.Column(campaign_db.Integer, primary_key=True)
campaign_id = campaign_db.Column(campaign_db.Integer, nullable=False)
user_id = campaign_db.Column(campaign_db.String(64), nullable=False)
post_content = campaign_db.Column(campaign_db.String(300), nullable=False)
twitter_post_id = campaign_db.Column(campaign_db.String(32), unique=True, nullable=False)

32
ayct_backend/models.py Normal file
View File

@ -0,0 +1,32 @@
from flask_sqlalchemy import SQLAlchemy
db = SQLAlchemy()
class TwitterAccount(db.Model):
__tablename__ = 'twitter_account'
id = db.Column(db.String(36), primary_key=True)
user_id = db.Column(db.String(64), nullable=False)
twitter_account_id = db.Column(db.String(32), nullable=False)
username = db.Column(db.String(16), nullable=False)
access_token = db.Column(db.String(256), nullable=False)
access_token_secret = db.Column(db.String(256), nullable=False)
class TwitterCampaign(db.Model):
__tablename__ = 'twitter_campaign'
id = db.Column(db.String(36), primary_key=True)
user_id = db.Column(db.String(64), nullable=False)
campaign_name = db.Column(db.String(64), nullable=False)
twitter_account_id = db.Column(db.String(32), nullable=False)
user_input = db.Column(db.String(100), nullable=False)
posts = db.relationship('TwitterPost', backref='campaign', lazy=True)
class TwitterPost(db.Model):
__tablename__ = 'twitter_post'
id = db.Column(db.String(36), primary_key=True)
campaign_id = db.Column(db.String(36), db.ForeignKey(TwitterCampaign.id), nullable=False)
user_id = db.Column(db.String(64), nullable=False)
post_content = db.Column(db.String(300), nullable=False)
twitter_post_id = db.Column(db.String(32), unique=True, nullable=False)

View File

@ -1,6 +1,7 @@
from uuid import uuid4
from requests_oauthlib import OAuth1Session from requests_oauthlib import OAuth1Session
from flask import Blueprint, Response, current_app, request, jsonify from flask import Blueprint, Response, current_app, request, jsonify
from ayct_backend.twitter.models import * from ayct_backend.models import *
from ayct_backend.firebase import verify_token from ayct_backend.firebase import verify_token
twitter = Blueprint('twitter', __name__) twitter = Blueprint('twitter', __name__)
@ -13,7 +14,7 @@ def get_twitter_accounts():
user_id = decoded_token['sub'] user_id = decoded_token['sub']
twitter_accounts = TwitterAccount.query.filter_by(user_id=user_id) twitter_accounts = TwitterAccount.query.filter_by(user_id=user_id).all()
accounts = [] accounts = []
@ -39,8 +40,8 @@ def add_twitter_account():
if content_type != 'application/json': if content_type != 'application/json':
return "Content-type not supported!", 400 return "Content-type not supported!", 400
json = request.json request_json = request.json
if not json['veryfier'] or not json['oauth_token'] or not json['oauth_token_secret']: if 'veryfier' not in request_json or 'oauth_token' not in request_json or 'oauth_token_secret' not in request_json:
return "Invalid request!", 400 return "Invalid request!", 400
consumer_key = current_app.config["TWITTER_CONSUMER_KEY"] consumer_key = current_app.config["TWITTER_CONSUMER_KEY"]
@ -49,19 +50,20 @@ def add_twitter_account():
access_token_url = "https://api.twitter.com/oauth/access_token" access_token_url = "https://api.twitter.com/oauth/access_token"
oauth = OAuth1Session( oauth = OAuth1Session(
consumer_key, consumer_key,
client_secret=consumer_secret, client_secret = consumer_secret,
resource_owner_key=json['oauth_token'], resource_owner_key = request_json['oauth_token'],
resource_owner_secret=json['oauth_token_secret'], resource_owner_secret = request_json['oauth_token_secret'],
verifier=json['veryfier'], verifier = request_json['veryfier'],
) )
oauth_tokens = oauth.fetch_access_token(access_token_url) oauth_tokens = oauth.fetch_access_token(access_token_url)
twitter_account = TwitterAccount.query.filter_by(user_id=user_id, twitter_account_id=oauth_tokens['user_id']) twitter_account = TwitterAccount.query.filter_by(user_id=user_id, twitter_account_id=oauth_tokens['user_id']).first()
if twitter_account: if twitter_account:
return "Account already exists!", 400 return "Account already exists!", 409
twitter_account = TwitterAccount( twitter_account = TwitterAccount(
id = str(uuid4()),
user_id = user_id, user_id = user_id,
twitter_account_id = oauth_tokens['user_id'], twitter_account_id = oauth_tokens['user_id'],
username = oauth_tokens['screen_name'], username = oauth_tokens['screen_name'],
@ -69,8 +71,8 @@ def add_twitter_account():
access_token_secret = oauth_tokens['oauth_token_secret'] access_token_secret = oauth_tokens['oauth_token_secret']
) )
twitter_db.session.add(twitter_account) db.session.add(twitter_account)
twitter_db.session.commit() db.session.commit()
return "Twitter account succesfully added.", 201 return "Twitter account succesfully added.", 201
@ -87,15 +89,15 @@ def delete_twitter_account():
return "Content-type not supported!", 400 return "Content-type not supported!", 400
request_json = request.json request_json = request.json
if not request_json['twitter_account_id']: if 'twitter_account_id' not in request_json:
return "Invalid request!", 400 return "Invalid request!", 400
twitter_account = TwitterAccount.query.filter_by(user_id=user_id, twitter_account_id=request_json['twitter_account_id']) twitter_account = TwitterAccount.query.filter_by(user_id=user_id, twitter_account_id=request_json['twitter_account_id']).first()
if not twitter_account: if not twitter_account:
return "Account not found!", 404 return "Account not found!", 404
twitter_db.session.delete(twitter_account) db.session.delete(twitter_account)
twitter_db.session.commit() db.session.commit()
return "Twitter account succesfully deleted.", 200 return "Twitter account succesfully deleted.", 200

View File

@ -1,13 +0,0 @@
from flask_sqlalchemy import SQLAlchemy
twitter_db = SQLAlchemy()
class TwitterAccount(twitter_db.Model):
__tablename__ = 'twitter_account'
id = twitter_db.Column(twitter_db.Integer, primary_key=True)
user_id = twitter_db.Column(twitter_db.String(64), nullable=False)
twitter_account_id = twitter_db.Column(twitter_db.String(32), nullable=False)
username = twitter_db.Column(twitter_db.String(16), nullable=False)
access_token = twitter_db.Column(twitter_db.String(256), nullable=False)
access_token_secret = twitter_db.Column(twitter_db.String(256), nullable=False)