Exemple #1
0
def scrape_and_commit_zip(zipcode, shelter_ids):
    from server.database import db_session
    dog_jsons = fetch_dogs_in_zip(zipcode, shelter_ids)

    while not shelter_ids.empty():
        shelter_id = shelter_ids.get()
        print(shelter_id)
        shelter_json = fetch_shelter_html_hack(shelter_id)
        if shelter_json.get("zipcode") is None:
            api_shelter_json = fetch_shelter_info(shelter_id)
            if api_shelter_json is not None:
                shelter_json["zipcode"] = int(api_shelter_json["zipcode"])
        shelter = make_shelter(shelter_json)
        db_session.add(shelter)

    db_session.add_all(
        [make_dog_and_breeds(dog_json) for dog_json in dog_jsons])

    db_session.commit()

    for dog_json in dog_jsons:
        print("{id}: {name}".format(**dog_json))

    parks = fetch_parks_in_zip(zipcode)
    db_session.add_all(parks)
    db_session.commit()

    for park in parks:
        print(park)
Exemple #2
0
def add_domain():
    try:
        if request.form['active'] == 'true':
            active = True
        else:
            active = False
        domain = Domain(domain_name=request.form['domain_name'],
                        grade=request.form['grade'],
                        last_updated=request.form['last_updated'],
                        status=request.form['status'],
                        active=active)

        db_session.add(domain)
        db_session.commit()
        db_session.close()
        return "success!"
    except IntegrityError:
        db_session.rollback()
        # Domain already exists so just update the current one.
        domain = db_session.query(Domain)\
            .filter_by(domain_name=request.form['domain_name']).one()

        domain.grade = request.form['grade']
        domain.last_updated = request.form['last_updated']
        domain.status = request.form['status']
        domain.active = request.form['active']
        db_session.commit()
        db_session.close()
        return "updated previous host %s" % request.form['domain_name']
Exemple #3
0
def user():
    # search for the user in our db using their github 
    user = db_session.query(models.User) \
        .filter(models.User.login == g.user['login']) \
        .first()

    # if the user doesn't exist, create a new one!
    if not user:
        new_user = models.User(g.user['login'])
        db_session.add(new_user)
        db_session.commit()

        user = new_user
    
    # just for fun, keeping track of a users last activity!
    user.last_activity = datetime.now()
    
    # don't forget to save changes after making modifications to an entry in the db.
    db_session.commit()

    # return the user data
    num_happy, num_sad = utils.getCounts()
    return jsonify({
        'login': g.user['login'],
        'name': g.user['name'],
        'avatar_url': g.user['avatar_url'],
        'is_happy': user.feeling == models.FeelingStatus.HAPPY,
        'num_happy': num_happy,
        'num_sad': num_sad
    })
Exemple #4
0
def commit_theater_info(theater_url):
    theater_info = AMCTheaters(theater_url).get_theater_info()
    if theater_info != None:
        theater_db = Theater(theater_info['url'], theater_info['name'],
                             theater_info['street'], theater_info['city'],
                             theater_info['state'], theater_info['zipCode'])
        print "Committing %s info" % (theater_db.name)
        db_session.add(theater_db)
        db_session.commit()
Exemple #5
0
def insert_initial_user(*args, **kwargs):
    """
        Example function that listens for the after_create event for a 
        table. In this case, it's adding an initial pre-determined value
        to the User table.
    """
    user = User("Yohlo")
    db_session.add(user)
    db_session.commit()
Exemple #6
0
def update_pins_on_auto(pins, state_str, GPIO):
    for pin in pins:
        if pin.on_user_override:
            print('Pin %d is on user_override. Keeping current state.'
                  % pin.pin_id)
            GPIO.apply_state(pin.pin_id, pin.state_str)
        else:
            GPIO.apply_state(pin.pin_id, state_str)
            pin.state_str = state_str
            db_session.add(pin)
Exemple #7
0
def update_pins_on_auto(pins, state_str, GPIO):
    for pin in pins:
        if pin.on_user_override:
            print('Pin %d is on user_override. Keeping current state.' %
                  pin.pin_id)
            GPIO.apply_state(pin.pin_id, pin.state_str)
        else:
            GPIO.apply_state(pin.pin_id, state_str)
            pin.state_str = state_str
            db_session.add(pin)
Exemple #8
0
def create_users():
    logins = ['alex', 'vova', 'alina']

    for login in logins:
        user = User(
            login=login, 
            email=login + '@mail.ru', 
            password = '******'
        )
        db_session.add(user)
    db_session.commit()
Exemple #9
0
def create_games():
    for item in range(0,10):
        if item % 2 == 0:
            game = Game(
                creator_id=User.query.all()[0].id
            )
            db_session.add(game)
        else:
            game = Game(
                creator_id=User.query.all()[1].id
            )
            db_session.add(game)
    db_session.commit()
Exemple #10
0
def get_or_create_movie_data(RT_url, movie_title):
    # gets movie from database if exists, otherwise commits new movie to database and returns it
    movie_db = Movie.query.filter(Movie.RT_url == RT_url).first()
    if movie_db == None:
        movie = RTMovie(RT_url)
        movie_general_info = movie.get_general_info()
        movie_db = Movie(
            RT_url,
            # add actual imdb_url later
            None,
            movie_title,
            movie_general_info['rating'],
            movie_general_info['length'],
            movie.get_img(),
            # add actual imdb_score later
            None,
            movie.get_RT_score(),
            movie.get_synopsis())
        db_session.add(movie_db)
        db_session.commit()

        for genre in movie_general_info['genre']:
            db_session.add(Genre(movie_db.id, genre))
        for cast in movie.get_cast():
            db_session.add(Cast(movie_db.id, cast))
        for director in movie_general_info['director']:
            db_session.add(Director(movie_db.id, director))
        db_session.commit()
    return movie_db
Exemple #11
0
def commit_showing_info(showing_url, theater_db):
    showing_info = AMCShowingInfo(showing_url).get_showing_info()
    # will not commit to database if showing info section is not found when scraping
    if showing_info != None:
        RT_url = get_RT_url(showing_info['movie'])
        if RT_url != None:
            with lock:
                movie_db = get_or_create_movie_data(RT_url,
                                                    showing_info['movie'])
                for time in showing_info['times']:
                    print "Committing %s" % (showing_url)
                    db_session.add(
                        Showing(movie_db.id, theater_db.id, showing_url,
                                showing_info['date'], time))
                    db_session.commit()
Exemple #12
0
def follow_user(
    follower: int,
    followee: int,
) -> bool:
    """Store the follows relationship in the database"""
    follows = Follows(
        follower=follower,
        followee=followee,
    )
    try:
        db_session.add(follows)
        db_session.commit()
    except IntegrityError as e:
        raise DuplicateFollowException from e

    return True
Exemple #13
0
def put_relays(pin_id):
    data = request.get_json()
    wanted_state = data.get('state_str')
    reset_to_auto = wanted_state == 'auto'

    p = Pin.query.filter(Pin.pin_id == int(pin_id)).one()

    if reset_to_auto:
        p.reset_user_override()
    else:
        p.set_user_override(wanted_state)
    db_session.add(p)
    db_session.flush()

    p = Pin.query.filter(Pin.pin_id == int(pin_id)).one()

    return jsonify({'relay': p.as_pub_dict()}), 200
Exemple #14
0
def put_relays(pin_id):
    data = request.get_json()
    wanted_state = data.get('state_str')
    reset_to_auto = wanted_state == 'auto'

    p = Pin.query.filter(Pin.pin_id == int(pin_id)).one()

    if reset_to_auto:
        p.reset_user_override()
    else:
        p.set_user_override(wanted_state)
    db_session.add(p)
    db_session.flush()

    p = Pin.query.filter(Pin.pin_id == int(pin_id)).one()

    return jsonify({'relay': p.as_pub_dict()}), 200
Exemple #15
0
def register_user(
    first_name: str,
    last_name: str,
    username: str,
    password: str,
) -> User:
    """Store user information in the database"""
    user = User(
        first_name=first_name,
        last_name=last_name,
        username=username,
        password=generate_password_hash(password),
    )
    try:
        db_session.add(user)
        db_session.commit()
    except IntegrityError as e:
        raise UserAlreadyExistsException from e
    else:
        return user
def add_equity_order(
    user_id: int,
    ticker: str,
    order_type: OrderType,
    quantity: float,
    price: float,
) -> bool:
    """Store the equity order in the database"""
    ticker_info = get_ticker_symbol(ticker)
    if not ticker_info:
        raise ValueError("Invalid ticker symbol")

    user_transaction = EquityOrder(
        user_id=user_id,
        ticker_id=ticker_info.id,
        order_type=order_type,
        quantity=quantity,
        price=price,
    )
    db_session.add(user_transaction)
    db_session.commit()
    return user_transaction
Exemple #17
0
def create_data():
    env = sys.argv[1] if len(sys.argv) > 1 else 'default'
    print(env)

    app = Flask(__name__)

    app.config.from_pyfile('server/config/api/default.py')
    app.config.from_pyfile('server/config/api/%s.py' % env, silent=True)

    init_db(app.config['DATABASE_URI'])

    lights = Schedule(open_time_sec=5 * 60 * 60, run_for_sec=16 * 60 * 60)
    db_session.add(lights)

    fans = Schedule(open_time_sec=5 * 60 * 60,
                    run_for_sec=5 * 60,
                    repeat_every=60 * 60)
    db_session.add(fans)

    db_session.flush()

    p = Pin(pin_id=37, name='L1.1')
    p.schedule_id = lights.id
    db_session.add(p)

    p = Pin(pin_id=35, name='L1.2')
    p.schedule_id = lights.id
    db_session.add(p)

    p = Pin(pin_id=33, name='L1.3')
    p.schedule_id = lights.id
    db_session.add(p)

    p = Pin(pin_id=31, name='L1.4')
    p.schedule_id = lights.id
    db_session.add(p)

    p = Pin(pin_id=13, name='L1.5')
    p.schedule_id = lights.id
    db_session.add(p)

    p = Pin(pin_id=16, name='L2.1')
    p.schedule_id = lights.id
    db_session.add(p)

    p = Pin(pin_id=26, name='L2.2')
    p.schedule_id = lights.id
    db_session.add(p)

    p = Pin(pin_id=29, name='L2.3')
    p.schedule_id = lights.id
    db_session.add(p)

    p = Pin(pin_id=18, name='L2.4')
    p.schedule_id = lights.id
    db_session.add(p)

    p = Pin(pin_id=12, name='L2.5')
    p.schedule_id = lights.id
    db_session.add(p)

    p = Pin(pin_id=36, name='Ventilation')
    p.schedule_id = fans.id
    db_session.add(p)
    db_session.flush()
Exemple #18
0
# pylint: disable=invalid-name
import sys
import uuid
from server.database import db_session
from server.models import Organization

if __name__ == "__main__":
    if len(sys.argv) != 2:
        print("Usage: python -m scripts.create-org <org_name>")
        sys.exit(1)

    org = Organization(id=str(uuid.uuid4()), name=sys.argv[1])
    db_session.add(org)
    db_session.commit()
    print(org.id)
Exemple #19
0
def register_stock_exchange(name: str, ) -> StockExchange:
    """Store the stock exchange name in the database"""
    stock_exchange = StockExchange(name=name)
    db_session.add(stock_exchange)
    db_session.commit()
    return stock_exchange
Exemple #20
0
# pylint: disable=invalid-name
import sys, uuid

from server.models import User, ElectionAdministration
from server.database import db_session

if __name__ == "__main__":
    if len(sys.argv) != 3:
        print("Usage: python -m scripts.create-admin <org_id> <user_email>")
        sys.exit(1)

    org_id, email = sys.argv[1:]  # pylint: disable=unbalanced-tuple-unpacking
    user = User.query.filter_by(email=email).first()
    if not user:
        user = User(id=str(uuid.uuid4()), email=email, external_id=email)
        db_session.add(user)
    election_admin = ElectionAdministration(user_id=user.id, organization_id=org_id)
    db_session.add(election_admin)
    db_session.commit()

    print(user.id)
    print("Now add the user to auth0: https://manage.auth0.com/")
    print("For staging users, use the err-aa-staging tenant.")
    print("For prod users, use the err-aa tenant.")
# pylint: disable=invalid-name
import sys, uuid

from server.models import User, AuditAdministration
from server.database import db_session

if __name__ == "__main__":
    if len(sys.argv) != 3:
        print("Usage: python -m scripts.create-admin <org_id> <user_email>")
        sys.exit(1)

    org_id, email = sys.argv[1:]  # pylint: disable=unbalanced-tuple-unpacking
    user = User.query.filter_by(email=email).first()
    if not user:
        user = User(id=str(uuid.uuid4()), email=email, external_id=email)
        db_session.add(user)
    audit_admin = AuditAdministration(user_id=user.id, organization_id=org_id)
    db_session.add(audit_admin)
    db_session.commit()

    print(user.id)
    print("Now add the user to auth0: https://manage.auth0.com/")
    print("For staging users, user the arlo-aa-staging tenant.")
    print("For prod users, use the arlo-aa tenant.")
Exemple #22
0
def register_ticker_symbol(exchange_id: int, ticker: str, company_name: str,) -> Ticker:
    """Store the ticker information in the database"""
    ticker = Ticker(exchange_id=exchange_id, ticker=ticker, company_name=company_name)
    db_session.add(ticker)
    db_session.commit()
    return ticker