def track_all(): cassandra = CassandraCluster() session = cassandra.connect() session.set_keyspace('musicservice') session.row_factory = dict_factory ''' query = "SELECT * FROM Track" result = g._trackshard1.execute(query) found = result.fetchall() result = g._trackshard2.execute(query) found += result.fetchall() result = g._trackshard3.execute(query) found += result.fetchall() ''' tracks = session.execute(""" SELECT * FROM track; """) result = [] for track in tracks: result.append(track) return make_response(jsonify(result))
def show_releasedaycharts(): if request.method == 'GET': return render_template('index_rd.html') elif request.method == 'POST': cassandra = CassandraCluster() app.config['CASSANDRA_NODES'] = ['52.8.153.198'] releasedayGET= request.form["second"] year = int(releasedayGET[0:4]) month = int(releasedayGET[5:7]) day = int(releasedayGET[8:10]) session = cassandra.connect() session.set_keyspace("movietweets") cql = "SELECT * FROM correlationtable7 WHERE year = %d AND month = %d AND day = %d ALLOW FILTERING" % (year, month, day) movie_results = session.execute(cql) def date_to_milli(time_tuple): epoch_sec = time.mktime((1970, 1, 1, 0, 0, 0, 0, 0, 0)) return 1000*int(time.mktime(time_tuple) - epoch_sec) releasedaystats = [] for result in movie_results: movie = result[0].encode('ascii','ignore') releasedaystats.append([movie, result[6]]) print releasedayGET return render_template('releasedaycharts.html', releasedaystats= releasedaystats, releasedayGET = releasedayGET)
def api_filter(): cassandra = CassandraCluster() session = cassandra.connect() session.set_keyspace('musicservice') session.row_factory = dict_factory query_parameters = request.args track_id = query_parameters.get('track_id') ''' found1 = None found2 = None found3 = None ''' if track_id is None: return page_not_found(404) else: #convert the track_id from string to UUID object #track_id = uuid.UUID(track_id) query = "SELECT * FROM track where track_id = {track_id};".format( track_id=track_id) track = session.execute(query) result = [] for t in track: result.append(t) #result = session.execute(query, track_id.bytes_le)) # we will need to check all 3 database shards # shard1_result = g._trackshard1.execute(query, track_title) # found1 = shard1_result.fetchone() # shard2_result = g._trackshard2.execute(query, track_title) # found2 = shard2_result.fetchone() # shard3_result = g._trackshard3.execute(query, track_title) # found3 = shard3_result.fetchone() #if not found1 and not found2 and not found3: # return page_not_found(404) ''' found = None if found1: found = found1 elif found2: found = found2 elif found3: found = found3 ''' return make_response(jsonify(result))
def init_db(): cassandra = CassandraCluster() session = cassandra.connect() session.set_keyspace('musicservice') #drop tables if exist: session.execute('DROP TABLE IF EXISTS user;') session.execute('DROP TABLE IF EXISTS track;') session.execute('DROP TABLE IF EXISTS playlist;') #create tables: #user table: session.execute(""" CREATE TABLE user ( username varchar, password varchar, display_name varchar, email varchar, homepage_url varchar, PRIMARY KEY (username) ); """) #track table: Stores all inddividu session.execute(""" CREATE TABLE track ( track_id uuid, track_title varchar, album_title varchar, artist varchar, length_seconds int, url_media varchar, url_art varchar, descriptions map<varchar, varchar>, PRIMARY KEY (track_id) ); """) #playlist table: session.execute(""" CREATE TABLE playlist ( playlist_id int, playlist_title varchar, description varchar, tracks set<uuid>, PRIMARY KEY (playlist_id) ); """)
def main_page(): if request.method == 'GET': return render_template('index.html', graph = False) elif request.method == 'POST': cassandra = CassandraCluster() app.config['CASSANDRA_NODES'] = ['52.8.153.198'] movienameGET= request.form["first"] session = cassandra.connect() session.set_keyspace("movietweets") print movienameGET cql = "SELECT * FROM correlationtable7 WHERE moviename = '%s'" % (movienameGET) movie_results = session.execute(cql) def date_to_milli(time_tuple): epoch_sec = time.mktime((1970, 1, 1, 0, 0, 0, 0, 0, 0)) return 1000*int(time.mktime(time_tuple) - epoch_sec) moviestats=[] numtweets=[] vardate=[] moviename='' voteaveragestats=[] votecount = [] for result in movie_results: year=result[1] month=result[2] day=result[3] vardate.append(date_to_milli((year, month, day, 0, 0, 0, 0, 0, 0))) numtweets.append(result[6]) moviestats.append([date_to_milli((year, month, day, 0, 0, 0, 0, 0, 0)), result[6]]) moviename=result[0] voteaveragestats.append([date_to_milli((year, month, day, 0, 0, 0, 0, 0, 0)), result[7]]) votecount.append([date_to_milli((year, month, day, 0, 0, 0, 0, 0, 0)), result[8]]) return render_template("moviecharts.html", vardate=vardate, numtweets=numtweets, moviestats=moviestats, moviename=moviename, voteaveragestats=voteaveragestats, votecount=votecount, graph =True)
from flask import Flask from flask import render_template, request, redirect from flask import stream_with_context, Response from flask_sqlalchemy import SQLAlchemy from sqlalchemy.sql import text from flask_cassandra import CassandraCluster from datetime import datetime from collections import OrderedDict app = Flask(__name__) app.config.from_object('config.DevelopmentConfig') GoogleMapsKey = app.config["GOOGLEMAPSKEY"] GoogleMapsJSKey = app.config["GOOGLEMAPSJSKEY"] db = SQLAlchemy(app) cassandra = CassandraCluster() gmaps = googlemaps.Client(key=GoogleMapsKey) API_url = "https://maps.googleapis.com/maps/api/js?key="\ + GoogleMapsJSKey + "&callback=initMap" # Parameter codes for asthma-causing pollutants ozone_code = 44201 pm_frm_code = 88101 # Federal reference methods pm_code = 88502 # Non-federal reference methods # SF coordinates as a default sf = dict() sf['lat'] = 41.8781136 sf['lon'] = -87.6297982 import models
def init_db(): global cassandra cassandra = CassandraCluster()
from flask import request from flask_api import status, exceptions from passlib.hash import bcrypt import flask_api import pugsql import uuid from cassandra.cluster import Cluster from flask_cassandra import CassandraCluster # pip3 install flask-cassandra from flask import Flask app = Flask(__name__) cassandra = CassandraCluster() app.config['CASSANDRA_NODES'] = ['172.17.02'] session = cassandra.connect() session.set_keyspace('data') @app.route('/api/v1/users', methods=['POST']) def create_user(): user = request.data required_fields = ['username', 'password', 'display_name', 'email'] # password is non-hashed at this point if not all([field in user for field in required_fields]): raise exceptions.ParseError() user_id = uuid.uuid4() username = user['username'] password = user['password']
def create_user(): #get request json data input = request.get_json() #required fields list to check if all input was correctly inputted required_fields = ['username', 'password', 'display_name', 'email'] # if not all required fields inputted if not all([field in input for field in required_fields]): return constraint_violation(409) cassandra = CassandraCluster() session = cassandra.connect() session.set_keyspace('musicservice') session.row_factory = dict_factory #Assigning all inputs to fields username = input['username'] password = input['password'] display_name = input['display_name'] email = input['email'] #initialize optional field to None #None turns to NULL when inserted into db homepage_url = None #check if optional data was sent in, if not, already set to None if 'homepage_url' in input: homepage_url = input['homepage_url'] ''' #query to see if username already exists query = "SELECT * FROM user WHERE username = \"" + username + "\";" user = session.execute(query) result = [] for name in user: result.append(name) #return first row from query, returns None of nothing found #if username already exists if len(result) == 0: return constraint_violation(409) ''' #hash inputted password: hashed_pw = generate_password_hash(password) #insert user into db after all checks passed #params = (username, hashed_pw, display_name, email, homepage_url) #g.db.execute("INSERT INTO User VALUES(?,?,?,?,?)", params) query = """ INSERT INTO user(username, password, display_name, email) VALUES({username}, {hashed_pw}, {display_name}, {email}); """.format(username=username, hashed_pw=hashed_pw, display_name=display_name, email=email) try: session.execute(query) except: file = open('errorlog.txt', 'a') file.write('something went wrong while creating user' + '\n') file.close() #set up location to be returned in response header location = 'http://localhost:8000/users?username='******'New User Created!'), 201) response.headers['Location'] = location return response
def create_track(): #takes in request (sent in with curl as JSON data) # and turn it into python dict. with 'get_json()' function input = request.get_json() required_fields = [ 'track_title', 'album_title', 'artist', 'length_seconds', 'url_media' ] if not all([field in input for field in required_fields]): return constraint_violation(409) track_title = input['track_title'] album_title = input['album_title'] artist = input['artist'] length_seconds = input['length_seconds'] url_media = input['url_media'] url_art = None #check if optional data was sent in, if not, already set to None if 'url_art' in input: url_art = input['url_art'] ''' result = g._trackshard1.execute("""SELECT * FROM Track WHERE track_title = ? and artist = ?;""", (track_title,artist,)) found = result.fetchone() result = g._trackshard2.execute("""SELECT * FROM Track WHERE track_title = ? and artist = ?;""", (track_title,artist,)) found2 = result.fetchone() result = g._trackshard3.execute("""SELECT * FROM Track WHERE track_title = ? and artist = ?;""", (track_title,artist,)) found3 = result.fetchone() if found or found2 or found3: return constraint_violation(409) track_id = uuid.uuid4() # first_char_of_track_id = ord(track_id[0]) shard = track_id.int % 3 file = open('textfile.txt', 'a') file.write('shard # [') file.write(str(shard)) file.write(']\n') file.close() ''' cassandra = CassandraCluster() session = cassandra.connect() session.set_keyspace('musicservice') session.row_factory = dict_factory query = """ INSERT INTO track(track_id, track_title, album_title, artist, length_s, url_media) VALUES(uuid(), {track_title}, {album_title}, {artist}, {length_s}, {url_media}); """.format(track_title=track_title, album_title=album_title, artist=artist, length_s=length_seconds, url_media=url_media) try: session.execute(query) except: file = open('errorlog.txt', 'a') file.write('something went wrong while adding track' + '\n') file.close() ''' try: if shard == 0: g._trackshard1.execute("INSERT INTO Track VALUES(?, ?, ?, ?, ?, ?, ?)", params) g._trackshard1.commit() elif shard == 1: g._trackshard2.execute("INSERT INTO Track VALUES(?, ?, ?, ?, ?, ?, ?)", params) g._trackshard2.commit() elif shard == 2: g._trackshard3.execute("INSERT INTO Track VALUES(?, ?, ?, ?, ?, ?, ?)", params) g._trackshard3.commit() except: file = open('errorlog.txt', 'a') file.write('something went wrong while adding track' + '\n') file.close() ''' location = 'http://localhost:8000/tracks?track_title=' + track_title #create response to return response = make_response(jsonify('New Track Created!'), 201) response.headers['Location'] = location return response