Ejemplo n.º 1
0
def add_or_update_coffee(coffee_data, coffees_updated, coffees_entered,
                         error_coffees):
    old_coffees = Coffee.query(Coffee.name == coffee_data['name'],
                               Coffee.roaster == coffee_data['roaster'],
                               Coffee.active == True).fetch()
    if old_coffees:
        if len(old_coffees) > 1:
            logging.warning(
                "Query for coffee name: {}, roaster: {} returned {} results. Result are {}"
                .format(coffee_data['name'], coffee_data['roaster'],
                        len(old_coffees), old_coffees))
        for key, value in coffee_data.iteritems():
            setattr(old_coffees[0], key, value)
        try:
            old_coffees[0].put()
            coffees_updated += 1
        except AttributeError:
            # error putting the coffee into the datastore
            error_coffees.append(coffee_data['product_page'])
    else:
        coffee = Coffee(**coffee_data)
        try:
            coffee.put()
            coffees_entered += 1
        except AttributeError:
            # error putting the coffee into the datastore
            error_coffees.append(coffee_data['product_page'])
    return [coffees_updated, coffees_entered, error_coffees]
Ejemplo n.º 2
0
def delete_coffee(payload, coffee_id):
    coffee_to_delete = Coffee.query.filter_by(id=coffee_id).first()
    deleted_id = coffee_to_delete.id

    try:
        Coffee.delete(coffee_to_delete)
    except:
        abort(500)

    return jsonify(success=True, coffee=deleted_id)
Ejemplo n.º 3
0
def mobile_synccoffee():
    # Parse JSON
    # Try to add
    # Return success or failure, with ID or error
    if request.headers["Content-Type"] == "application/json":
        coffeejson = request.get_json()
    else:
        return redirect(url_for("home"))
    try:
        print "Coffee JSON Request", coffeejson
        if "id" in coffeejson:
            coffee = Coffee.query.filter_by(id=coffeejson["id"]).first()
        else:
            coffee = Coffee(coffeejson["coffeetype"])
        person = get_person(coffeejson["person"])
        coffee.person = person.id
        coffee.addict = person
        coffee.size = coffeejson["size"]
        coffee.sugar = coffeejson["sugar"]
        coffee.run = coffeejson["run"]
        coffee.runobj = Run.query.filter_by(id=coffeejson["run"]).first()
        if "id" not in coffeejson:
            db.session.add(coffee)
        db.session.commit()
        return jsonify(msg="success",
                       id=coffee.id,
                       modified=coffee.jsondatetime("modified"))
    except:
        return jsonify(msg="error")
Ejemplo n.º 4
0
def index():
    """Lists the coffeez"""
    coffees = memcache.get(ALL_COFFEES_KEY)
    if not coffees:
        coffees = Coffee.query(Coffee.active == True).fetch()
        # cannot store all images into memcached due to size limits
        for coffee in coffees:
            coffee.image = None
        memcache.set(ALL_COFFEES_KEY, coffees)
    roaster_query = memcache.get(ALL_ROASTERS_KEY)
    if not roaster_query:
        roaster_query = Coffee.query(projection=["roaster"], distinct=True).fetch()
        memcache.set(ALL_ROASTERS_KEY, roaster_query)
    roasters = [data.roaster for data in roaster_query]
    return render_template('index.html', coffees=coffees, roasters=roasters)
Ejemplo n.º 5
0
def index():
    """Lists the coffeez"""
    coffees = memcache.get(ALL_COFFEES_KEY)
    if not coffees:
        coffees = Coffee.query(Coffee.active == True).fetch()
        # cannot store all images into memcached due to size limits
        for coffee in coffees:
            coffee.image = None
        memcache.set(ALL_COFFEES_KEY, coffees)
    roaster_query = memcache.get(ALL_ROASTERS_KEY)
    if not roaster_query:
        roaster_query = Coffee.query(projection=["roaster"],
                                     distinct=True).fetch()
        memcache.set(ALL_ROASTERS_KEY, roaster_query)
    roasters = [data.roaster for data in roaster_query]
    return render_template('index.html', coffees=coffees, roasters=roasters)
Ejemplo n.º 6
0
def add_coffee(runid=None):
    runs = Run.query.filter(Run.deadline >= sydney_timezone_now()).filter(Run.statusid==1).all()
    if not runs:
        flash("There are no upcoming coffee runs. Would you like to make one instead?", "warning")
        return redirect(url_for("home"))
    lastcoffee = Coffee.query.filter(Coffee.addict==current_user).order_by(Coffee.id.desc()).first()
    form = CoffeeForm(request.form)
    form.runid.choices = [(r.id, r.time) for r in runs]
    if runid:
        run = Run.query.filter_by(id=runid).first()
        localmodified = run.deadline.replace(tzinfo=pytz.timezone("Australia/Sydney"))
        if sydney_timezone_now() > localmodified:
            flash("You can't add coffees to this run", "danger")
            return redirect(url_for("view_run", runid=runid))
        form.runid.data = runid
    users = User.query.all()
    form.person.choices = [(user.id, user.name) for user in users]
    if request.method == "GET":
        form.person.data = current_user.id
        if lastcoffee:
            form.coffeetype.data = lastcoffee.coffeetype
            form.size.data = lastcoffee.size
            form.sugar.data = lastcoffee.sugar
        return render_template("coffeeform.html", form=form, formtype="Add", current_user=current_user)
    if form.validate_on_submit():
        print form.data
        coffee = Coffee(form.data["coffeetype"])
        coffee.size = form.data["size"]
        coffee.sugar = form.data["sugar"]
        person = User.query.filter_by(id=form.data["person"]).first()
        coffee.personid = person.id
        coffee.addict = person
        coffee.runid = form.data["runid"]
        run = Run.query.filter_by(id=form.data["runid"]).first()
        coffee.price = form.data["price"]
        print coffee.price
        coffee.modified = sydney_timezone_now()
        db.session.add(coffee)
        db.session.commit()
        write_to_events("created", "coffee", coffee.id)
        notify_run_owner_of_coffee(run.fetcher, person, coffee)
        flash("Coffee order added", "success")
        return redirect(url_for("view_coffee", coffeeid=coffee.id))
    else:
        for field, errors in form.errors.items():
            flash("Error in %s: %s" % (field, "; ".join(errors)), "danger")
        return render_template("coffeeform.html", form=form, current_user=current_user)
Ejemplo n.º 7
0
def get_coffee_image(coffee_id):
    """Gets the image attached to the coffee"""
    coffee_int_id = int(coffee_id)
    coffee = memcache.get("coffee_image_{}".format(coffee_int_id))
    if not coffee:
        coffee = Coffee.get_by_id(coffee_int_id)
        memcache.set("coffee_image_{}".format(coffee_int_id), coffee)
    if coffee:
        if coffee.image:
            return send_file(io.BytesIO(coffee.image))
    return app.send_static_file('coffee.png')
Ejemplo n.º 8
0
def create_coffee(payload):
    body = request.get_json()
    name = body['name']
    origin = body.get('origin', None)
    roaster = body.get('roaster', None)
    description = body.get('description', None)
    brewing_method = body.get('brewing_method', None)

    new_coffee = Coffee(name=name,
                        origin=origin,
                        roaster=roaster,
                        description=description,
                        brewing_method=brewing_method)

    try:
        Coffee.insert(new_coffee)
    except:
        abort(500)

    return jsonify(success=True, coffee=new_coffee.format_long())
Ejemplo n.º 9
0
def get_coffee_image(coffee_id):
    """Gets the image attached to the coffee"""
    coffee_int_id = int(coffee_id)
    coffee = memcache.get("coffee_image_{}".format(coffee_int_id))
    if not coffee:
        coffee = Coffee.get_by_id(coffee_int_id)
        memcache.set("coffee_image_{}".format(coffee_int_id), coffee)
    if coffee:
        if coffee.image:
            return send_file(io.BytesIO(coffee.image))
    return app.send_static_file('coffee.png')
Ejemplo n.º 10
0
def add_or_update_coffee(coffee_data, coffees_updated, coffees_entered, error_coffees):
    old_coffees = Coffee.query(Coffee.name == coffee_data['name'], Coffee.roaster == coffee_data['roaster'], Coffee.active==True).fetch()
    if old_coffees:
        if len(old_coffees) > 1:
            logging.warning("Query for coffee name: {}, roaster: {} returned {} results. Result are {}".format(coffee_data['name'], coffee_data['roaster'], len(old_coffees), old_coffees))
        for key, value in coffee_data.iteritems():
            setattr(old_coffees[0], key, value)
        try: 
            old_coffees[0].put()
            coffees_updated +=1
        except AttributeError:
            # error putting the coffee into the datastore
            error_coffees.append(coffee_data['product_page'])
    else: 
        coffee=Coffee(**coffee_data)
        try:
            coffee.put()
            coffees_entered +=1
        except AttributeError:
            # error putting the coffee into the datastore
            error_coffees.append(coffee_data['product_page'])
    return [coffees_updated, coffees_entered, error_coffees]
Ejemplo n.º 11
0
def edit_coffee(payload, coffee_id):
    coffee_to_edit = Coffee.query.filter_by(id=coffee_id).first()
    body = request.get_json()
    origin = body.get('origin', None)
    roaster = body.get('roaster', None)
    brewing_method = body.get('brewing_method', None)

    if origin:
        coffee_to_edit.origin = origin

    if roaster:
        coffee_to_edit.roaster = roaster

    if brewing_method:
        coffee_to_edit.brewing_method = brewing_method

    try:
        Coffee.update(coffee_to_edit)
    except:
        abort(500)

    return jsonify(success=True, coffee=coffee_to_edit.format_long())
Ejemplo n.º 12
0
def cron_update():
    """ Checks active coffees to see if theyre inactive """
    coffees = Coffee.query(Coffee.active==True).fetch()
    logging.info('Checking for inactive coffees. Currently {} coffees are active'.format(len(coffees)))
    inactive_coffees = 0
    for coffee in coffees:
        if coffee.date_updated < datetime.datetime.now() - datetime.timedelta(days=2):
            coffee.active = False
            coffee.date_removed = datetime.datetime.now()
            coffee.put()
            logging.info('Coffee {} was marked inactive'.format(coffee.name))
            inactive_coffees += 1
    logging.info("{} coffees were newly marked inactive".format(inactive_coffees))
    return "Finished checking active coffees"
Ejemplo n.º 13
0
def cron_update():
    """ Checks active coffees to see if theyre inactive """
    coffees = Coffee.query(Coffee.active == True).fetch()
    logging.info(
        'Checking for inactive coffees. Currently {} coffees are active'.
        format(len(coffees)))
    inactive_coffees = 0
    for coffee in coffees:
        if coffee.date_updated < datetime.datetime.now() - datetime.timedelta(
                days=2):
            coffee.active = False
            coffee.date_removed = datetime.datetime.now()
            coffee.put()
            logging.info('Coffee {} was marked inactive'.format(coffee.name))
            inactive_coffees += 1
    logging.info(
        "{} coffees were newly marked inactive".format(inactive_coffees))
    return "Finished checking active coffees"
Ejemplo n.º 14
0
 def setup(self):
     self.sirocco = Brand('Sirocco')
     self.lasemeuse = Brand('La Semeuse')
     self.brands = [self.sirocco, self.lasemeuse]
     self.coffee = Coffee(name='Mocca', brands=self.brands, quantity=5)