Exemplo n.º 1
0
    def setUp(self):
        """Stuff to do before every test."""

        self.client = app.test_client()
        app.config['TESTING'] = True

        # Connect to test database (uncomment when testing database)
        connect_to_db(app, "postgresql:///testdb")

        # Create tables and add sample data (uncomment when testing database)
        db.create_all()
        example_data()

        with self.client as c:
        with c.session_transaction() as sess:
            sess['RSVP'] = True

    def tearDown(self):
        """Do at end of every test."""

        # (uncomment when testing database)
        db.session.close()
        db.drop_all()

    def test_games(self):
        result = self.client.get("/games")
        self.assertIn("Clue", result.data)
Exemplo n.º 2
0
def index():
    model.connect_to_db()  # connect to database, using code from model
    # do I need the post id?
    # what exactly is happening here?
    posts = model.get_all_posts()

    return render_template("index.html", all_posts=posts)
Exemplo n.º 3
0
def view_user(username):
    model.connect_to_db()
    user_id = model.get_user_by_name(username)
    posts = model.get_wall_posts(user_id[0])
    return render_template("wall.html", posts = posts,
                                        logged_in = session["user_id"],
                                        username = username)
Exemplo n.º 4
0
def post_to_wall(username):
    model.connect_to_db()
    user_id = model.get_userid_by_name(username)
    post_input = request.form.get("content")
    author_id = session['username']
    model.create_wall_post(user_id, author_id, post_input)
    return redirect(url_for("view_user", username=username))
Exemplo n.º 5
0
    def setUp(self):
        """Stuff to do before every test."""

        # Get the Flask test client
        self.client = app.test_client()

        # Mock session

        # Connect to temporary database
        connect_to_db(app, "sqlite:///")

        # Create tables and add sample data
        db.create_all()
        sample_data()


        def _mock_grab_image_dimensions(filename):
            return (920, 764)

        self._old_grab_image_dimensions = server.grab_image_dimensions
        server.grab_image_dimensions = _mock_grab_image_dimensions

        def _mock_generate_thumb(filename, crop_thumb):
            return None

        self._old_generate_thumb = server.generate_thumb
        server.generate_thumb = _mock_generate_thumb
Exemplo n.º 6
0
    def setUp(self):
        """Do before every test."""

        # Get the Flask test client
        self.client = app.test_client()

        # Show Flask errors that happen during tests
        app.config['TESTING'] = True

        # Connect to test database
        connect_to_db(app, "postgresql:///testdb")
        db.create_all()

        # Make mocks
        def _mock_get_yelp_search_results(term, location, category_filter, limit):
            """Mocks search results of Yelp API call for one restaurant."""

            search_results = {"businesses": [{"rating": 4.5, "rating_img_url": "https://s3-media2.fl.yelpcdn.com/assets/2/www/img/99493c12711e/ico/stars/v1/stars_4_half.png", "review_count": 547, "name": "Saru Sushi Bar", "rating_img_url_small": "https://s3-media2.fl.yelpcdn.com/assets/2/www/img/a5221e66bc70/ico/stars/v1/stars_small_4_half.png", "url": "http://www.yelp.com/biz/saru-sushi-bar-san-francisco?utm_campaign=yelp_api&utm_medium=api_v2_search&utm_source=6XuCRI2pZ5pIvcWc9SI3Yg", "image_url": "https://s3-media2.fl.yelpcdn.com/bphoto/5-ugy01zjSvudVsfdhmCsA/ms.jpg", "display_phone": "+1-415-400-4510", "id": "saru-sushi-bar-san-francisco", "location": {"city": "San Francisco", "postal_code": "94114", "country_code": "US", "address": ["3856 24th St"], "coordinate": {"latitude": 37.751706, "longitude": -122.4288283}, "state_code": "CA"}}]}
            return search_results

        def _mock_is_open_now_true(keyword, location):
            """Mocks Google Places API call to return True for current open status."""

            return True

        self._old_is_open_now = process_results.is_open_now
        process_results.is_open_now = _mock_is_open_now_true

        self.old_get_yelp_search_results = server.yelp.search_query
        server.yelp.search_query = _mock_get_yelp_search_results
    def setUp(self):
        # Get the Flask test client
        self.client = app.test_client()

        # Show Flask errors that happen during tests
        app.config['TESTING'] = True

        # Connect to test database
        connect_to_db(app, "postgresql:///testdb")

        # Create tables from model
        db.create_all()

        # Import different types of data from seed file
        seed.load_users()
        seed.load_groups()
        seed.load_usergroups()
        seed.load_patterns()
        seed.load_invites()
        
        # Reset auto incrementing primary keys to start after seed data
        seed.set_val_user_id()
        seed.set_val_group_id()
        seed.set_val_usergroup_id()
        seed.set_val_pattern_id()
        seed.set_val_invite_id()
Exemplo n.º 8
0
    def setUp(self):

        print "(setUp ran)"
        self.client = server.app.test_client()          # Sets up fake test browser
        server.app.config['TESTING'] = True             # Makes a 500 error in a route raise an error in a test
        connect_to_db(app, "postgresql:///testdb")      # Connect to temporary DB
        db.create_all()
    def setUp(cls):
        """Do once before all tests in this class"""
        # Get the Flask test client
        cls.client = app.test_client()

        # Show Flask errors that happen during tests
        app.config['TESTING'] = True

        # Connect to test database
        connect_to_db(app, "postgresql:///testdb")

        # Create tables from model
        db.create_all()

        # Import different types of data from seed file
        seed.load_users()
        seed.load_groups()
        seed.load_usergroups()
        seed.load_patterns()
        seed.load_invites()
        
        seed.set_val_user_id()
        seed.set_val_group_id()
        seed.set_val_usergroup_id()
        seed.set_val_pattern_id()
        seed.set_val_invite_id()

        with cls.client as c:
                with c.session_transaction() as sess:
                    sess['user_id'] = 1
                c.set_cookie('localhost', 'MYCOOKIE', 'cookie_value')
Exemplo n.º 10
0
    def setUp(self):
        """Do at the beginning of every test"""
        # Get the Flask test client
        self.client = app.test_client()

        # Show Flask errors that happen during tests
        app.config['TESTING'] = True

        # Connect to test database
        connect_to_db(app, "postgresql:///testdb")

        # Create tables from model
        db.create_all()

        # Import different types of data from seed file
        seed.load_users()
        seed.load_groups()
        seed.load_usergroups()
        seed.load_patterns()
        seed.load_invites()
        
        # Reset auto incrementing primary keys to start after seed data
        seed.set_val_user_id()
        seed.set_val_group_id()
        seed.set_val_usergroup_id()
        seed.set_val_pattern_id()
        seed.set_val_invite_id()

        with self.client as c:
                with c.session_transaction() as sess:
                    sess['user_id'] = 1
                c.set_cookie('localhost', 'MYCOOKIE', 'cookie_value')
Exemplo n.º 11
0
    def setUp(self):
        """Setup to do before every test."""

        # Get the Flask test client
        self.client = app.test_client()

        # secret key to allow sessions to be used
        app.config['SECRET_KEY'] = 'sekrit!'

        # Show Flask errors that happen during tests
        app.config['TESTING'] = True

        # Connect to test database
        connect_to_db(app, db_uri="postgresql:///testdb")

        # Create tables and add sample data
        db.create_all()
        # create db records for yarns, users, baskets, basket_yarns,
        #                       projects, and patterns
        create_example_data()
        # create db records for preferences and user_preferences
        load_preferences("test_data/preference_data.txt")
        load_user_preferences("test_data/user_preference_data.txt")

        with self.client as c:
                with c.session_transaction() as session:
                    session['username'] = '******'
Exemplo n.º 12
0
def create_account():
    username = request.form.get("username")
    password1 = request.form.get("password")
    password2 = request.form.get("password_verify")

    print "top of create account", username,password1,password2
    
    if len(username) < 1:
        flash("username must be longer than 0 characters")
        return redirect(url_for("register"))

    if password1 != password2:
        flash ("passwords must match, try again")
        return redirect(url_for("register"))

    
    else:
        print "I'm connecting to the database cause the passwords matched!"
        model.connect_to_db()
        if model.user_exists(username):
            flash ("That user already exists")
        else:
            model.create_new_account(username, password1)
            flash ("Welcome")
            
        model.CONN.close()

        return redirect(url_for("index"))
Exemplo n.º 13
0
    def setUp(self):
        """Setup to do before every test."""

        # Get the Flask test client
        self.client = app.test_client()
        app.jinja_env.undefined = StrictUndefined
        app.jinja_env.filters['prettify_preference'] = prettify_preference

        # Show Flask errors that happen during tests
        app.config['TESTING'] = True

        # Connect to test database
        connect_to_db(app, db_uri="postgresql:///testdb")

        # start with empty db
        db.drop_all()
        # Create tables and add sample data
        db.create_all()
        # create db records for yarns, users, baskets, basket_yarns,
        #                       projects, and patterns
        create_example_data()
        # create db records for preferences and user_preferences
        load_preferences("test_data/preference_data.txt")
        load_user_preferences("test_data/user_preference_data.txt")
        load_group_events("test_data/group-events.csv")
Exemplo n.º 14
0
def view_user(username):
    model.connect_to_db()
    owner_id = model.get_user_by_name(username)
    wallposts = model.get_wall_posts(owner_id)
    html = render_template("wall.html", wallposts = wallposts)
    # print "print in_view user fucntion"
    return html
Exemplo n.º 15
0
def register():
    model.connect_to_db()

    if session.get("user_id"):
        return redirect(url_for('view_user', username=session.get("username")))
    else:
        return render_template("register.html")
Exemplo n.º 16
0
    def setUp(self):
        print "\n\n\n\n (2) DOING A SEARCH TEST \n\n\n\n"
        self.client = app.test_client()
        app.config['TESTING'] = True
        postgrespassword = os.environ['POSTGRES_PASSWORD']
        db_uri = 'postgresql://' + postgrespassword + '/test'
        connect_to_db(app, db_uri)

        db.create_all()

        load_regions()
        load_users()
        load_bestuses()
        load_categories()
        load_brands()
        load_products()
        load_tents()
        load_filltypes()
        load_gendertypes()
        load_sleepingbags()
        load_padtypes()
        load_sleepingpads()
        load_ratings()
        load_histories()
        load_test_postalcodes()
Exemplo n.º 17
0
def register():
    model.connect_to_db()
    if session.get("username"):
         # get username by id 
         username = model.get_username_by_id(session["username"])
         return redirect("users/"+username)
    else:
        return render_template("register.html")
Exemplo n.º 18
0
def add_event():
    model.connect_to_db()
    title = request.args.get("title")
    body = request.args.get("body")
    user_id = request.args.get("user_id")
    created_at = request.args.get("datestamp")
    event = model.add_new_post(title, body, user_id, created_at)
    return "Successfully added an event!"
Exemplo n.º 19
0
def add_task_create():
    model.connect_to_db()
    title = request.args.get("title")
    user_id = request.args.get("user_id")
    created_at = request.args.get("datestamp")
    row = model.new_task(title, created_at, user_id)
    html = render_template("added_task.html")
    return html
Exemplo n.º 20
0
def view_user(username):
    model.connect_to_db()
    user_id = model.get_user_by_name(username)
    wall_posts = model.get_wall_posts_for_user(user_id)

    return render_template("wall_posts.html", username = username,
                                              wall_posts = wall_posts,
                                              user_id = session.get('user_id'))
Exemplo n.º 21
0
def post_to_wall(username):
    model.connect_to_db()
    wall_owner = model.get_user_by_name(username)
    current_user = session.get('user_id')
    wall_content = request.form.get("wall_content")
    model.add_wall_post(current_user, wall_owner, wall_content)

    return redirect(url_for('view_user', username=username))
Exemplo n.º 22
0
def post_to_wall(username):
    model.connect_to_db()
    owner_id = model.get_user_by_name(username)
    author_id = session.get('user_id')
    created_at = datetime.datetime.now()
    content = request.form.get('content')
    model.post_wall_posts(owner_id, author_id, created_at, content)
    return redirect(url_for('view_user', username = username))
Exemplo n.º 23
0
    def setUp(self):
        """Set up app, session key, and fake client."""

        app.config['TESTING'] = True
        self.client = app.test_client()

        connect_to_db(app, 'postgresql:///testdb')
        db.create_all()
Exemplo n.º 24
0
 def setUp(self):
     self.client = app.test_client()
     app.config['TESTING'] = True
     app.config['SECRET_KEY'] = 'BalloonicornSmash'
     # Connect to the database
     connect_to_db(app, db_uri=travis_db_uri)
     # Reset the world so we start with clean data
     seed_force(app)
Exemplo n.º 25
0
def post_to_wall(username):
    model.connect_to_db()
    content = request.form.get("content")
    author_id = session['user_id']
    owner_id = model.get_user_by_name(username)
    model.create_new_post(owner_id, author_id, content)
    # redirect_string = "/user/%s" % username
    return redirect(url_for('view_user', username=username))
Exemplo n.º 26
0
def view_post(username):

    model.connect_to_db()
    post_text = request.form.get('post_text')
    author_id = session.get('user_id')
    owner_id = model.get_user_id_by_username(username)
    model.insert_post(owner_id, author_id, post_text)
    return redirect(url_for("view_user", username = username))
Exemplo n.º 27
0
    def setUp(self):

        # Connect to test database
        connect_to_db(app, "postgresql:///testdb")

        # Create tables and add sample data
        db.create_all()
        example_data()
Exemplo n.º 28
0
    def setUpClass(cls):
        """Initializes the database."""
        app = flask.Flask(__name__)
        app.config['TESTING'] = True

        model.connect_to_db(app, db_name='chat_client_test')

        model.db.drop_all()
Exemplo n.º 29
0
    def setUp(self):
        self.client = app.test_client()
        app.config["TESTING"] = True
        app.config["SECRET_KEY"] = "key"

        connect_to_db(app, db_uri="postgresql:///testdb")

        db.create_all()
Exemplo n.º 30
0
    def setUpClass(cls):
        """Initializes the test application."""
        cls.client = server.app.test_client()
        server.app.config['TESTING'] = True

        model.connect_to_db(server.app, db_name='chat_client_test')
        # Clear any data that may be in the database.
        model.db.drop_all()
Exemplo n.º 31
0
from flask import (Flask, render_template, redirect, request, flash,
                   session, copy_current_request_context, jsonify, current_app)
from flask_debugtoolbar import DebugToolbarExtension
from flask_sqlalchemy import SQLAlchemy
from sqlalchemy import func
import datetime
import urllib
from datetime import datetime
from server import app
import string
import os
from geopy import geocoders

from server import app

connect_to_db(app, 'postgresql:///safework')
#######################################################
with app.app_context():
 	db.drop_all()
 	db.create_all()

def fill_basics():
	with app.app_context():
		Police1 = Police(police_dept_id=1, name="User_Input")
		Police2 = Police(police_dept_id=2, name="San Franciso Police Department", city="San Francisco", state="CA")
		Police3 = Police(police_dept_id=3, name="Oakland Police Department", city="Oakland", state="CA")
		Police4 = Police(police_dept_id=4, name="Alameda County Sheriff's Department", city="Oakland", state="CA")
		Police5 = Police(police_dept_id=5, name="Santa Clara County Sheriff's Office", city="San Jose", state="CA")
		Police6 = Police(police_dept_id=6, name="Fremont Police Department", city="Fremont", state="CA")
		Police7 = Police(police_dept_id=7, name="San Leandro Police Department", city="San Leandro", state="CA")
		Police8 = Police(police_dept_id=8, name="San Pablo Police Department", city="San Pablo", state="CA")
Exemplo n.º 32
0
"""Script to seed database."""

import os
import csv
import crud
import model
from server import app
from decimal import Decimal

os.system('dropdb locations')
os.system('createdb locations')

model.connect_to_db(app)
model.db.create_all()

locations_in_db = []

with open('data/DoctorWhoEpisodesInfo.csv', encoding='utf-8-sig') as csv_file:
    fieldnames = [
        'season', 'episode_number', 'doctor', 'title', 'imdb', 'ep_id',
        'companion', 'guest_star'
    ]
    episode_data = csv.DictReader(csv_file,
                                  fieldnames=fieldnames,
                                  skipinitialspace=True)
    #reads and imports Episode info from csv file

    for episode in episode_data:

        #for loop to set up database for episodes table and seeds data into episodes_in_db
Exemplo n.º 33
0
    """Diplay about page"""

    return render_template("about.html")


@app.route("/friends")
def display_friends():
    """Diplay list of contributors to open source code practice project"""

    return render_template("friends.html")


@app.route("/api/tweets")
def create_api_endpoint():
    """Using ingested dsta from twitter create an API endpoint"""

    tweedict = {}
    tweets = Tweet.query.all()

    for tweet in tweets:
        tweedict[tweet.handle] = tweet.text

    return jsonify(tweedict)


if __name__ == "__main__":
    app.debug = True
    connect_to_db(app, "postgresql:///newb")
    app.run(port=5000)
    tweet_to_db()
Exemplo n.º 34
0
def delete_item(list_id, item):
    print "I made it to the route"
    model.connect_to_db()
    model.delete_item(item)
    return redirect(url_for("todo_list_show", id=list_id))
Exemplo n.º 35
0
import os
import json
from random import choice, randint, sample
import requests, json, csv, time
from datetime import datetime
import crud, api
from model import connect_to_db, db, User, Symbol, Stock, Stockprice, Stockdetail, Stocknews, UserFavorite, Plan, Blog, Subscription, Stock_in_Subscription, Event, Comment
from server import app

os.system('dropdb stocks')
os.system('createdb stocks')

connect_to_db(app, echo=False)
db.create_all()

AA_API_KEY = os.environ['AA_API_KEY']

url = 'https://www.alphavantage.co/query?function=LISTING_STATUS&apikey=' + AA_API_KEY
res = requests.get(
    url)  # double check this line, might be a duplicate to line 65
decoded = res.content.decode('utf-8')

csv_read = csv.reader(decoded.splitlines(), delimiter=',')
all_symbols = list(csv_read)

for symbol in all_symbols:
    symbol = Symbol(symbol=symbol[0])
    db.session.add(symbol)
    db.session.commit()

print("Finished adding all stock symbols")
Exemplo n.º 36
0
                email=testUserData[user]["email"], password=pass_hash)
            db.session.add(testUser)
        db.session.commit()

    def addMessages():
        """add test message data to test db"""

        for key in testGeojsonData:
            message = Message(message_text=testGeojsonData[key]["message-text"], created_at=testGeojsonData[key]["time"], lat=testGeojsonData[key]
                              ["lat"], lng=testGeojsonData[key]["lng"], country=testGeojsonData[key]["country"], city=testGeojsonData[key]["city"])
            db.session.add(message)

        db.session.commit()

    def addLikedMessage():
        """add a message to liked list"""
        for num in range(3, 5):
            likeMessage = LikedMessage(message_id=num, user_id=2)
            db.session.add(likeMessage)
        db.session.commit()

    addUsers()
    addMessages()
    #addLikedMessage()


if __name__ == "__main__":
    connect_to_db(app, prod)
    db.create_all()
    create_test_data()
Exemplo n.º 37
0
            list_of_dates.append(date)
            start_date = date
        else:
            break

    return list_of_dates


def list_of_recurrent_entries_with_all_dates(list_of_recurrent_entries):
    """ Return a list of recurrent entries associated with all dates based on frequency."""

    updated_entry_list_with_new_dates = []

    for entry in list_of_recurrent_entries:
        date = entry.date
        stop_date = entry.stop_date
        frequency = entry.frequency
        list_of_dates = find_all_dates(date, stop_date, frequency)
        for date in list_of_dates:
            entry_copy = copy.deepcopy(entry)
            entry_copy.date = date
            updated_entry_list_with_new_dates.append(entry_copy)

    return updated_entry_list_with_new_dates


if __name__ == '__main__':
    from server import app
    local = "-local" in sys.argv
    connect_to_db(app, local=local)
Exemplo n.º 38
0
 def setUp(self):
     connect_to_db(app, "postgresql:///masseffecttest")
     db.create_all()
     make_test_data()
Exemplo n.º 39
0
def get_mood_rating():
    """Gets ratings for a mood (day/event)"""

    user_id = session['user_id']
    overall_mood = request.form.get('overall-mood')
    notes = request.form.get('notes')
    # min and max mood are not req in html, will give empty str if not filled
    # changes empty str to None in Python before passing it into Day instance
    # prevents error when making record in db (min/max mood are integers)
    if not request.form.get('min-mood'):
        min_mood = None
        max_mood = None
    else:
        min_mood = request.form.get('min-mood')
        max_mood = request.form.get('max-mood')

    return [user_id, overall_mood, min_mood, max_mood, notes]


if __name__ == "__main__":
    # We have to set debug=True here, since it has to be True at the
    # point that we invoke the DebugToolbarExtension
    app.debug = False

    connect_to_db(app, 'asgard_db')

    # Use the DebugToolbar
    DebugToolbarExtension(app)

    app.run(port=5000, host='0.0.0.0')
Exemplo n.º 40
0
        }
    else:
        abort(400)  # Bad request

    return jsonify(dict_of_posts)


@app.route("/posts/<post_id>/references")
def references(post_id):
    """References by a particular post."""

    mode = request.args.get('mode', 'full')
    post = Post.query.filter(Post.id == post_id).one()

    if mode == 'full':
        dict_of_posts = {
            post.id: post.to_dictionary()
            for post in post.references
        }
    elif mode == 'short':
        dict_of_posts = {post.id: post.title for post in post.references}
    else:
        abort(400)  # Bad request

    return jsonify(dict_of_posts)


if __name__ == '__main__':
    connect_to_db(app, DB_URI)
    app.run(debug=False, host="0.0.0.0")
Exemplo n.º 41
0
    items = PublicItem.query.all()
    places = []

    for item in items:
        item_coordinates = [item.title, item.latitude, item.longitude]
        places.append(item_coordinates)

    # change back to UTF-8
    for location in places:
        location[0] = str(location[0])

    return render_template("public-items-map.html",
                           gm_api_key=gm_api_key,
                           places=places,
                           email=email)


if __name__ == "__main__":

    app.config['DEBUG_TB_INTERCEPT_REDIRECTS'] = False
    app.debug = True
    app.jinja_env.auto_reload = app.debug  # make sure templates, etc. are not cached in debug mode
    if app.config['TESTING'] is True:
        connect_to_db(app, "postgresql:///testdb")
    else:
        connect_to_db(app)

    # Use the DebugToolbar
    # DebugToolbarExtension(app)

    app.run(port=5000, host='0.0.0.0')
Exemplo n.º 42
0
Arquivo: seed.py Projeto: leemoh/Spent
    """ Set value for the next category id after seeding database """

    # Get the Max user id in the database
    result = db.session.query(func.max(Category.id)).one()

    max_id = int(result[0])

    # Set the value for the next user_id to be max_id + 1
    query = "SELECT setval('categories_id_seq', :new_id)"

    db.session.execute(query, {'new_id': max_id + 1})
    db.session.commit()


if __name__ == "__main__":
    spent_database = os.getenv('POSTGRES_DB_URL', 'postgres:///spending')
    connect_to_db(app, spent_database)

    # In case tables haven't been created, create them
    db.create_all()

    # Import different types of data
    load_users()
    load_categories()
    load_expenditures()
    load_budget()
    set_val_user_id()
    set_val_category_id()
    set_val_expenditure_id()
    set_val_budget_id()
Exemplo n.º 43
0
import pika
import requests
from qwer import qwer
from model import Job, connect_to_db
from model import db as alchemy_db

connect_to_db(qwer)

connection = pika.BlockingConnection(pika.ConnectionParameters(host='localhost'))
channel = connection.channel()

channel.queue_declare(queue='jobs')

def callback(ch, method, properties, body):
    params = body.split()
    r = requests.get(url=params[1])
    job = Job.query.filter_by(id=params[0]).first()
    job.data = r.text
    alchemy_db.session.commit()

channel.basic_consume(callback,
                      queue='jobs',
                      no_ack=True)

print('Rabbit is waiting for messages. To exit press CTRL+C')
channel.start_consuming()
Exemplo n.º 44
0
"""Script to seed test database"""

import os
import json

import crud
import model
import server
from random import choice

os.system("dropdb testbookworm")
os.system("createdb testbookworm")

model.connect_to_db(server.app, "testbookworm")
model.db.create_all()


def test_data():

    #create books for testing
    harry_potter = crud.create_book(
        "oxxszQEACAAJ", "Harry Potter and the Half-Blood Prince",
        "J. K. Rowling",
        "Harry Potter, now sixteen-years-old, begins his sixth year at school in the midst of the battle between good and evil which has heated up with the return of the Dark Lord Voldemort.",
        652,
        "http://books.google.com/books/content?id=oxxszQEACAAJ&printsec=frontcover&img=1&zoom=1&source=gbs_api"
    )
    neverwhere = crud.create_book(
        "yuCUZ3km3qIC", "Neverwhere", "Neil Gaiman",
        "Richard Mayhew is a young man with a good heart and an ordinarylife, which is changed forever when he stops to help a girl he finds bleeding on a London sidewalk. His small act of kindness propels him into a world he never dreamed existed. There are people who fall through the cracks, and Richard has become one of them. And he must learn to survive in this city of shadows and darkness, monsters and saints, murderers and angels, if he is ever to return to the London that he knew.",
        400,
Exemplo n.º 45
0

@app.route('/seed')
def seed_and_update():
    """seed and update the database - temporart solution"""
    update_station_status()
    print 'Stations updated'

    return '<h1>DB Seeded</h1>'


#---------------------------------------------------------------------#
# JSON Routes
#---------------------------------------------------------------------#


@app.route('/user-location.JSON')
def send_user_location_availability(location):
    """Gets location from the user and finds closest stations and availability"""
    pass


if __name__ == "__main__":
    app.debug = True
    connect_to_db(app, 'postgres:///bike')
    DebugToolbarExtension(app)
    app.config['DEBUG_TB_INTERCEPT_REDIRECTS'] = False
    app.config['TEMPLATES_AUTO_RELOAD'] = True

    app.run(port=5000, host="0.0.0.0")
Exemplo n.º 46
0
    for url in urls:
        if url.shortened_url[:2]=="0x":
            created_count +=1

    custom_count = len(urls)-created_count

    return render_template('analytics.html', custom_count=custom_count, created_count=created_count, total=len(urls))

@app.route('/all_urls')
def show_all_urls():
    """Shows a list of all submitted URLs"""

    urls = Url.query.all()

    return render_template('all_urls.html', urls=urls)




if __name__ == "__main__":

    app.debug = True

    connect_to_db(app, 'postgresql:///urlshorten')

    DebugToolbarExtension(app)

    app.run()

Exemplo n.º 47
0
"""Script to seed database"""

import os
import json
from random import choice, randint
from datetime import datetime

import crud
import model
import server

os.system('dropdb ratings')
os.system('createdb ratings')

model.connect_to_db(server.app)
model.db.create_all()

with open('data/movies.json') as f:
    movie_data = json.loads(f.read())

# Create movies, store them in list so we can use them
# to create fake ratings later
movies_in_db = []
for movie in movie_data:
    title = movie.get('title')
    overview = movie.get('overview')
    poster_path = movie.get('poster_path')
    release_str = movie.get('release_date')
    format = "%Y-%m-%d"
    release_date = datetime.strptime(release_str, format)
Exemplo n.º 48
0
    # Commit to push to database
    db.session.commit()



def set_val_user_id():
    """Set value for the next user_id after seeding database"""

    # Get the Max user_id in the database
    result = db.session.query(func.max(User.user_id)).one()
    max_id = int(result[0])

    # Set the value for the next user_id to be max_id + 1
    query = "SELECT setval('users_user_id_seq', :new_id)"
    db.session.execute(query, {'new_id': max_id + 1})
    db.session.commit()


if __name__ == "__main__":
    connect_to_db(app)

    # In case tables haven't been created, create them
    db.create_all()

    # Import different types of data
    load_users()
    load_movies()
    load_ratings()
    set_val_user_id()
    
Exemplo n.º 49
0
    def setUp(self):
        """Stuff to do before every test."""

        self.client = server.app.test_client()
        server.app.config['TESTING'] = True
        server.app.config['SECRET_KEY'] = 'key'

        # Connect to test database (uncomment when testing database)
        connect_to_db(server.app, "testdb")

        # Create tables and add sample data (uncomment when testing database)
        db.create_all()
        example_data()

        self.old_api = api.yelp_api_call

        def _mock_yelp_api_call(payload_str):
            """Mock results of yelp api call at api.py"""
            return {'businesses':[{'id': 'GLW_lWB5K-4eHX-2RfzJ5g', 
                                'alias': 'davis-poultry-farms-gilroy-10', 
                                'name': 'Davis Poultry Farms', 
                                'image_url': 'https://s3-media1.fl.yelpcdn.com/bphoto/iRY9a_oHXJtLi1W8NDrSbQ/o.jpg', 
                                'is_closed': False, 
                                'url': 'https://www.yelp.com/biz/davis-poultry-farms-gilroy-2?adjust_creative=vxvAyk47rIbZXQHuMg79ww&utm_campaign=yelp_api_v3&utm_medium=api_v3_business_search&utm_source=vxvAyk47rIbZXQHuMg79ww', 
                                'review_count': 15, 
                                'categories': [{'alias': 'ranches', 'title': 'Ranches'}], 
                                'rating': 4.5, 
                                'coordinates': {'latitude': 37.0531099, 
                                                'longitude': -121.59012}, 
                                'transactions': [], 
                                'location': {'address1': '155 Santa Clara Ave', 
                                                'address2': '',
                                                'address3': '', 
                                                'city': 'Gilroy', 
                                                'zip_code': '95020', 
                                                'country': 'US', 
                                                'state': 'CA', 
                                                'display_address': ['155 Santa Clara Ave', 'Gilroy, CA 95020']}, 
                                'phone': '+14088424894', 
                                'display_phone': '(408) 842-4894', 
                                'distance': 21479.493719243506}]}            

        api.yelp_api_call = _mock_yelp_api_call


        def _mock_request_get(YELP_SEARCH_URL, headers, params):
            """Mock yelp api request for business search"""
            class MockResult:
                """Mock result of api request"""
                def json(self):
                    return {'businesses':[{'id': 'GLW_lWB5K-4eHX-2RfzJ5g', 
                                        'alias': 'davis-poultry-farms-gilroy-10', 
                                        'name': 'Davis Poultry Farms', 
                                        'image_url': 'https://s3-media1.fl.yelpcdn.com/bphoto/iRY9a_oHXJtLi1W8NDrSbQ/o.jpg', 
                                        'is_closed': False, 
                                        'url': 'https://www.yelp.com/biz/davis-poultry-farms-gilroy-2?adjust_creative=vxvAyk47rIbZXQHuMg79ww&utm_campaign=yelp_api_v3&utm_medium=api_v3_business_search&utm_source=vxvAyk47rIbZXQHuMg79ww', 
                                        'review_count': 15, 
                                        'categories': [{'alias': 'ranches', 'title': 'Ranches'}], 
                                        'rating': 4.5, 
                                        'coordinates': {'latitude': 37.0531099, 
                                                        'longitude': -121.59012}, 
                                        'transactions': [], 
                                        'location': {'address1': '155 Santa Clara Ave', 
                                                        'address2': '',
                                                        'address3': '', 
                                                        'city': 'Gilroy', 
                                                        'zip_code': '95020', 
                                                        'country': 'US', 
                                                        'state': 'CA', 
                                                        'display_address': ['155 Santa Clara Ave', 'Gilroy, CA 95020']}, 
                                        'phone': '+14088424894', 
                                        'display_phone': '(408) 842-4894', 
                                        'distance': 21479.493719243506}]}
            my_result = MockResult()
            return my_result

        api.requests.get = _mock_request_get
Exemplo n.º 50
0
    for post in posts:
        post.event_date = post.event_date.strftime('%m/%d/%Y %I:%M %P')
        user = User.query.filter_by(user_id=post.user_id).first()
        post.username = user.username

    return render_template("post_list.html", posts=posts)


# for heroku debugging
@app.route("/error")
def error():
    raise Exception("Error!")


if __name__ == '__main__':
    connect_to_db(app, os.environ.get("DATABASE_URL"))

    # Create the tables we need from our models (if they already
    # exist, nothing will happen here, so it's fine to do this each
    # time on startup)
    db.create_all(app=app)

    # Use the DebugToolbar
    app.debug = False
    DebugToolbarExtension(app)
    app.jinja_env.auto_reload = app.debug  # make sure templates, etc. are not cached in debug mode

    DEBUG = "NO_DEBUG" not in os.environ
    # app.run(port=5000, host='0.0.0.0')
    PORT = int(os.environ.get("PORT", 5000))
Exemplo n.º 51
0
    """Display list of contributors to open source code practice project"""

    return render_template("friends.html")


@app.route("/api/tweets")
def create_api_endpoint():
    """Using ingested dsta from twitter create an API endpoint"""

    tweedict = {}
    tweets = Tweet.query.all()

    for tweet in tweets:
        tweedict[tweet.handle] = tweet.text

    return jsonify(tweedict)


@app.route("/archives")
def archives():
    """ Displays previous tweets """

    return render_template("archives.html")


if __name__ == "__main__":
    app.debug = True
    # Change the postgresql info below username, password, port
    connect_to_db(app, "postgresql://*****:*****@localhost:port/newb")
    app.run(port=5000)
Exemplo n.º 52
0
    # for user_playlist in user.playlists:
    #     if user_playlist.playlist_title == playlist.playlist_title:
    #         playlist = user_playlist

    for song in artist.songs:
        playlist.songs.append(song)

    db.session.commit()


def db_create_playlist(artist_name, playlist_title, user_id):
    artist = add_artist_to_db(artist_name)
    setlists = load_setlists_from_artist(artist)
    add_songs_to_db(artist, setlists)
    playlist = create_playlist_in_db(playlist_title, user_id)
    add_songs_to_playlist(artist, user_id, playlist)


if __name__ == "__main__":
    connect_to_db(server.app)

    # In case tables haven't been created, create them
    db.create_all()

    # Import different types of data
    # load_users()

    from doctest import testmod
    if testmod().failed == 0:
        print("Setlist API tests passed.")