def create_app(): pass app = Flask(__name__) app.config['CUSTOM_VAR'] = 5 # Just an example of app config :) app.config['SQLALCHEMY_DATABASE_URI'] = DATABASE_URL app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False db.init_app(app) migrate.init_app(app, db) '''ROUTING''' # Homepage @app.route('/') def root(): return render_template('home.html') # Webpage that says 'Hello [name]' when user inserts name after final '/' @app.route('/<name>') def hello_name(name): return render_template('name.html', name=name) # Webpage that describes Thanos when user inserts score after final '/' @app.route('/<int:score>') def check_score(score): return render_template('score.html', score=score) # Users route with dummy data @app.route('/users') @app.route('/users.json') def users(): users = User.query.all() # Returns a list of <class 'app.User'> print(type(users)) print(type(users[0])) print(len(users)) # Create simplified dict for users users_response = [] for u in users: user_dict = u.__dict__ del user_dict['_sa_instance_state'] users_response.append(user_dict) return jsonify(users_response) # Create new users @app.route('/users/create', methods=['POST']) def create_user(): print('CREATING A NEW USER...') print('FORM DATA:', dict(request.form)) if 'name' in request.form: name = request.form['name'] print(name) db.session.add(User(name=name)) db.session.commit() return jsonify({'message': 'CREATED OKAY', 'name': name}) else: return jsonify({'message': 'OOPS! PLEASE SPECIFY A NAME!'}) # if __name__ == '__main__': # app.run() return app
def create_app(): app = Flask(__name__) app.config["SQLALCHEMY_DATABASE_URL"] = DATABASE_URL app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = False db.init_app(app) migrate.init_app(app, db) app.register_blueprint(home_routes) app.register_blueprint(book_routes) app.register_blueprint(twitter_routes) return app
def create_app(): app = Flask(__name__) app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = False app.config["SQLALCHEMY_DATABASE_URI"] = DATABASE_URL app.config["TWITTER_API_CLIENT"] = twitter_api_client() db.init_app(app) migrate.init_app(app, db) app.register_blueprint(my_routes) return app
def create_app(): app = Flask(__name__) app.config[ 'SECRET_KEY'] = '8d96f77b72f3719a7df238f1e6347df0' #prevents cookies to be modified app.config[ 'SQLALCHEMY_DATABASE_URI'] = 'sqlite:///web_app_ls.db' # db get created in the relative path db.init_app(app) migrate.init_app(app, db) app.register_blueprint(users) app.register_blueprint(twitter_routes) app.register_blueprint(main) app.register_blueprint(admin_routes) return app
def create_app(): """Create and configure a Flask application instance. Returns: Flask application instance. """ app = Flask(__name__) app.config['SECRET_KEY'] = SECRET_KEY # configure database app.config['SQLALCHEMY_DATABASE_URI'] = DATABASE_URL app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False db.init_app(app) migrate.init_app(app, db) # configure routes app.register_blueprint(home_routes) app.register_blueprint(twitter_routes) return app
def create_app(): """Application Factory Pattern""" """Create and configure and instance of flask application.""" app = Flask(__name__) # Configures DB app.config['SQLALCHEMY_DATABASE_URI'] = config('DATABASE_URL') app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False # Initialize, and migrating DB from twitoff.models import db, migrate db.init_app(app) migrate.init_app(app, db) # Registering routes app.register_blueprint(home_routes) app.register_blueprint(user_routes) app.register_blueprint(compare_routes) app.register_blueprint(error_routes) return app
def create_app(): app = Flask(__name__) #add config for DB app.config['SQLALCHEMY_DATABASE_URI'] = DATABASE_URL #have the db know about the app db.init_app(app) migrate.init_app(app, db) def get_users_from_db(): users =[] db_users = User.query.all() for b in db_users: print(b) d = b.__dict__ del d["_sa_instance_state"] users.append(d) return users @app.route('/') def root(): return render_template("home.html") @app.route("/new") def new_data(): users = get_users_from_db() return render_template("new_data.html", message="Users Added", users=users) @app.route("/new/create", methods=["POST"]) def create_data(): try: twitter_user = twitter_api_client.get_user(request.form["user"]) db_user = User.query.get(twitter_user.id) or User(id=twitter_user.id) db_user.screen_name = twitter_user.screen_name db_user.name = twitter_user.name db_user.location = twitter_user.location db_user.followers_count = twitter_user.followers_count db.session.add(db_user) db.session.commit() statuses = twitter_api_client.user_timeline(request.form["user"], tweet_mode="extended", count=300, exclude_replies=True, include_rts=False) #db_tweets = [] for status in statuses: print(status.full_text) print("----") #print(dir(status)) # Find or create database tweet: db_tweet = Tweet.query.get(status.id) or Tweet(id=status.id) db_tweet.user_id = status.author.id # or db_user.id db_tweet.full_text = status.full_text embedding = basilica_client.embed_sentence(status.full_text, model="twitter") # todo: prefer to make a single request to basilica with all the tweet texts, instead of a request per tweet #print(len(embedding)) db_tweet.embedding = embedding db.session.add(db_tweet) #db_tweets.append(db_tweet) db.session.commit() #return 'Success' #flash(f"User Added successfully!", "success") return redirect(f"/new") except: return jsonify({"message": "OOPS User Not Found!"}) @app.route("/new/predict", methods=['Post']) def predict(): # Get users and tweet from prediction form user_a = request.form["user_a"] user_b = request.form["user_b"] tweet_text = request.form['tweet_text'] # Get tweets from database user_a = User.query.filter(User.screen_name == user_a).one() user_b = User.query.filter(User.screen_name == user_b).one() #breakpoint() # Train Model user_a_embeddings = np.array([tweet.embedding for tweet in user_a.tweets]) user_b_embeddings = np.array([tweet.embedding for tweet in user_b.tweets]) embeddings = np.vstack([user_a_embeddings, user_b_embeddings]) labels = np.concatenate([np.ones(len(user_a.tweets)), np.zeros(len(user_b.tweets))]) classifier = LogisticRegression(random_state=0, solver='lbfgs').fit(embeddings, labels) # Make Prediction tweet_embedding = basilica_client.embed_sentence(tweet_text, model="twitter") results = classifier.predict(np.array(tweet_embedding).reshape(1, -1)) if int(results[0]) == 1: prediction = user_a.name else: prediction = user_b.name probs = classifier.predict_proba(np.array(tweet_embedding).reshape(1, -1)) if prediction == user_b.name: prob = float(probs[:,0]) else: prob = float(probs[:,1]) prob = prob*100 probability = f'{prob:.2f}' return render_template("results.html", user_a=user_a.name, user_b=user_b.name, tweet_text=tweet_text, prediction=prediction, probability=probability ) @app.route("/reset") def reset_db(): print(type(db)) db.drop_all() db.create_all() return jsonify({"message": "DB RESET OK"}) # new_user = User(id=45, name=request.form["user"]) # new_tweet = Tweet(id=56, text=request.form["tweet"]) # db.session.add(new_user) # db.session.add(new_tweet) # db.session.commit() @app.route("/users") @app.route("/users.json") def list_users(): users=[] user_records = User.query.all() for user in user_records: print(user) d = user.__dict__ del d["_sa_instance_state"] users.append(d) return jsonify(users) return app
def create_app(): """ Creates and Configures a Flask application""" app = Flask(__name__) #app.config['SQLALCHEMY_DATABASE_URI'] = getenv('DATABASE_URI') app.config['SQLALCHEMY_DATABASE_URI'] = "sqlite:///db.sqlite3" app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False DB.init_app(app) migrate.init_app(app, DB) @app.route('/') def root(): #new_user = User(id=1, name="nick", newest_tweet_id=1) #DB.session.add(new_user) #DB.session.commit() return render_template("base.html", title="Home", users=User.query.all()) @app.route('/compare', methods=['POST']) def compare(): user0, user1 = sorted( [request.values['user1'], request.values['user2']]) message = "" if user0 == user1: message = "Cannot compare users to themselves!" else: prediction = predict_user(user0, user1, request.values['tweet_text']) message = "{} is more likely to be said by {} than {}".format( request.values['tweet_text'], user1 if prediction else user0, user0 if prediction else user1) return render_template('prediction.html', title='Prediction', message=message) @app.route('/user', methods=['POST']) @app.route('/user/<name>', methods=['GET']) def user(name=None, message=""): name = name or request.values['user_name'] try: if request.method == 'POST': add_or_update_user(name) message = "User {} successfully added!".format(name) tweets = User.query.filter(User.name == name).one().tweets except Exception as e: message = "Error adding {}: {}".format(name, e) tweets = [] return render_template('user.html', title=name, tweets=tweets, message=message) @app.route('/update') def update(): # adds our users insert_example_users() return render_template('base.html', title="Home", users=User.query.all()) @app.route('/reset') def reset(): # resets database DB.drop_all() DB.create_all() return render_template('base.html', title='Home') return app