Exemplo n.º 1
0
def add_cafe_form():
    """ GET: show add cafe form, POST: adds cafe to database"""
    if not g.user or not g.user.admin:
        return 'not authorized', 401

    form = AddOrEditCafeForm()
    form.city_code.choices = db.session.query(City.code, City.name).all()

    if form.validate_on_submit():
        name = form.name.data
        description = form.description.data
        url = form.url.data
        address = form.address.data
        city_code = form.city_code.data
        image_url = form.image_url.data

        cafe = Cafe(name=name,
                    description=description,
                    url=url,
                    address=address,
                    city_code=city_code,
                    image_url=image_url)

        db.session.add(cafe)
        db.session.commit()
        cafe.save_map()

        flash(f'{name} added')
        return redirect(f'/cafes/{cafe.id}')
    else:
        return render_template('cafe/add-form.html', form=form)
Exemplo n.º 2
0
def add_cafe():
    form = CafeForm(request.form)
    if request.method == "GET":
        return render_template("cafeform.html",
                               form=form,
                               formtype="Add",
                               current_user=current_user)
    if request.method == "POST" and form.validate_on_submit():
        # Add cafe
        cafe = Cafe()
        cafe.name = form.data["name"]
        cafe.location = form.data["location"]
        db.session.add(cafe)
        db.session.commit()
        write_to_events("created", "cafe", cafe.id)
        flash("Cafe added", "success")
        return redirect(url_for("view_cafe", cafeid=cafe.id))
    else:
        for field, errors in form.errors.items():
            flash("Error in %s: %s" % (field, "; ".join(errors)), "danger")
        return render_template("cafeform.html",
                               form=form,
                               formtype="Add",
                               current_user=current_user)
    return redirect(url_for("home"))
Exemplo n.º 3
0
def testCriarCafe():
    c1 = Cafe(nome_cafe="House")
    c2 = Cafe(nome_cafe="Mais Cafe")
    try:
        db.session.add(c1)
        db.session.add(c2)
    except:
        return "Erro"

    return c1.nome_cafe, c2.nome_cafe
Exemplo n.º 4
0
def add_cafe_form():
    """Show and process form for adding a new cafe. """

    form = CafeForm()

    # make cities dinamic
    cities = [(city.code, city.name) for city in City.query.all()]
    form.city_code.choices = cities

    if form.validate_on_submit():
        name = form.name.data
        description = form.description.data
        url = form.url.data
        address = form.address.data
        city_code = form.city_code.data
        image_url = form.image_url.data

        cafe = Cafe(name=name,
                    description=description,
                    url=url,
                    address=address,
                    city_code=city_code,
                    image_url=image_url or None)

        db.session.add(cafe)
        db.session.commit()

        flash(f'{cafe.name} added')
        return redirect(f'/cafes/{cafe.id}')

    return render_template('cafe/add-form.html', form=form)
Exemplo n.º 5
0
def add_cafe():
    """Handle add_cafe form """
    form = AddCafeForm()

    form.city_code.choices = City.get_city_codes()

    if form.validate_on_submit():
        name = form.name.data
        description = form.description.data
        url = form.url.data
        address = form.address.data
        city_code = form.city_code.data
        image_url = form.image_url.data

        if not image_url:
            image_url = None

        cafe = Cafe(name=name,
                    description=description,
                    url=url,
                    address=address,
                    city_code=city_code,
                    image_url=image_url)

        flash(f"{name} added!!")
        db.session.add(cafe)
        db.session.commit()

        return redirect(f"/cafes/{cafe.id}")

    else:
        return render_template("cafe/add-form.html", form=form)
Exemplo n.º 6
0
    def setUp(self):
        """Before each test, add sample city, user, cafe, and like"""

        City.query.delete()
        User.query.delete()
        Cafe.query.delete()
        Like.query.delete()

        city = City(**CITY_DATA)
        db.session.add(city)

        user = User.register(**TEST_USER_DATA)
        db.session.add(user)

        cafe = Cafe(**CAFE_DATA)
        db.session.add(cafe)
        db.session.commit()

        like = Like(user_id=user.id, cafe_id=cafe.id)
        db.session.add(like)
        db.session.commit()

        self.cafe_name = cafe.name
        self.cafe_id = cafe.id
        # self.cafe = cafe
        self.user = user
        self.like = like
Exemplo n.º 7
0
def criar(classe):
    resposta = jsonify({
        "status": "201",
        "result": "ok",
        "details": "Objeto criado!"
    })
    dados = request.get_json()
    try:
        if classe == "sala":
            novo = Sala(**dados)

        elif classe == "pessoa":
            numero_salas = Sala.query.count()
            numero_cafes = Cafe.query.count()
            indice = random.randrange(0, numero_salas)
            indice_cafe = random.randrange(0, numero_cafes)
            db_salas = db.session.query(Sala).all()
            db_cafes = db.session.query(Cafe).all()
            if numero_salas != 0 or numero_cafes != 0:
                novo = Pessoa(**dados,
                              sala=db_salas[indice],
                              cafe=db_cafes[indice_cafe])
            else:
                resposta = jsonify({
                    "status": "400",
                    "result": "error",
                    "details ": str(e)
                })

        elif classe == "cafe":
            numero_cafes = Cafe.query.count()
            if numero_cafes <= 1:
                novo = Cafe(**dados)
            else:
                resposta = jsonify({
                    "status": "400",
                    "result": "error",
                    "details ": str(e)
                })

        db.session.add(novo)
        db.session.commit()
    except Exception as e:
        resposta = jsonify({
            "status": "400",
            "result": "error",
            "details ": str(e)
        })
    resposta.headers.add("Access-Control-Allow-Origin", "*")
    return resposta
Exemplo n.º 8
0
def add_cafe():
    """Handle add_cafe form.
    Only logged-in admin users can add/edit cafes."""

    if not g.user or not g.user.admin:
        flash("Only admins can add cafes.", "danger")
        return redirect("/login")

    form = CafeAddEditForm()

    form.city_code.choices = City.get_city_codes()

    if form.validate_on_submit():
        cafe = Cafe(
            name=form.name.data,
            description=form.description.data,
            url=form.url.data,
            address=form.address.data,
            city_code=form.city_code.data,
            image_url=form.image_url.data or None,
        )

        db.session.add(cafe)

        # In order to run save_map, we need to make sure the cafe has been
        # given an ID, so we need the database to "flush" --- this runs the
        # SQL [so postgres gives it an id] but doesn't commit the transaction
        db.session.flush()
        cafe.save_map()

        db.session.commit()

        flash(f"{cafe.name} added!", "success")
        return redirect(f"/cafes/{cafe.id}")

    else:
        return render_template("cafe/add-form.html", form=form)
Exemplo n.º 9
0
    def setUp(self):
        """Before each test, add sample city, users, and cafes"""

        City.query.delete()
        Cafe.query.delete()

        sf = City(**CITY_DATA)
        db.session.add(sf)

        cafe = Cafe(**CAFE_DATA)
        db.session.add(cafe)

        db.session.commit()

        self.cafe_id = cafe.id
Exemplo n.º 10
0
    def setUp(self):
        """Before all tests, add sample city & users"""

        Cafe.query.delete()
        City.query.delete()

        sf = City(**CITY_DATA)
        db.session.add(sf)

        cafe = Cafe(**CAFE_DATA)
        db.session.add(cafe)

        db.session.commit()

        self.cafe = cafe
Exemplo n.º 11
0
def testCriarPessoa():
    s2 = Sala(nome_sala="Sala 02",
            lotacao=11)
    c2 = Cafe(nome_cafe="CoffePlus")
    p1 = Pessoa(nome="Cristina",
                sobrenome="de Souza", sala=s2, cafe =c2)
    p2 = Pessoa(nome="Berta",
                sobrenome="Maria", sala=s2, cafe =c2)
    try:
        db.session.add(p1)
        db.session.add(p2)
    except:
        return "Erro"

    return p1.nome, p1.sobrenome, p2.nome, p2.sobrenome
Exemplo n.º 12
0
    def setUp(self):
        """Before each test, add sample city, users, and cafes"""

        Like.query.delete()
        Cafe.query.delete()
        City.query.delete()
        User.query.delete()

        sf = City(**CITY_DATA)
        db.session.add(sf)

        user = User.register(**TEST_USER_DATA)
        db.session.add(user)

        cafe = Cafe(**CAFE_DATA)
        db.session.add(cafe)

        db.session.commit()

        self.user_id = user.id
        self.cafe_id = cafe.id
Exemplo n.º 13
0
def cafe_add():
    """ show form for adding cafe and handle form"""
    form = AddEditCafeForm()

    #get city_code choice from current cities in db
    form.city_code.choices = City.get_all_cities()

    if form.validate_on_submit():
        new_cafe = Cafe(name=form.name.data,
                        description=form.description.data,
                        url=form.url.data,
                        address=form.address.data,
                        city_code=form.city_code.data,
                        image_url=form.image_url.data or None)

        db.session.add(new_cafe)
        db.session.commit()

        flash(f'{new_cafe.name} added')
        return redirect(f"/cafes/{new_cafe.id}")

    return render_template("cafe/add-form.html", form=form)
Exemplo n.º 14
0
def add_cafe():
    """Show form for adding cafe."""

    form = AddOrEditCafe()

    cities = City.cities()
    form.city_code.choices = cities

    if form.validate_on_submit():
        cafe = Cafe(name=form.name.data,
                    description=form.description.data,
                    url=form.url.data,
                    address=form.address.data,
                    city_code=form.city_code.data,
                    image_url=form.image_url.data)

        db.session.add(cafe)
        db.session.commit()
        flash(f"{cafe.name} added!", "success")
        return redirect(f"/cafes/{cafe.id}")

    else:
        return render_template("/cafe/add-form.html", form=form)
Exemplo n.º 15
0
def add_cafe():
    """Handle add_cafe form. Only logged-in users can add/edit cafes."""

    if not g.user:
        flash("Only logged-in users can add cafes.", "danger")
        return redirect("/login")

    form = AddCafeForm()

    form.city_code.choices = City.get_city_codes()

    if form.validate_on_submit():
        name = form.name.data
        description = form.description.data
        url = form.url.data
        address = form.address.data
        city_code = form.city_code.data
        image_url = form.image_url.data

        if not image_url:
            image_url = None

        cafe = Cafe(name=name,
                    description=description,
                    url=url,
                    address=address,
                    city_code=city_code,
                    image_url=image_url)

        flash(f"{name} added!", "success")
        db.session.add(cafe)
        db.session.commit()

        return redirect(f"/cafes/{cafe.id}")

    else:
        return render_template("cafe/add-form.html", form=form)
Exemplo n.º 16
0
def newCafe():
    # check user id, only admin can create points
    user_id = getUserId(login_session['email'])
    if login_session['user_id'] != 1:
        return "<script>function myFunction() {\
                alert('Not authorized.');\
            }</script><body onload='myFunction()'>"

    # add cafe to database on POST
    if request.method == 'POST':
        newCafe = Cafe(name=request.form['name'],
                       description=request.form['description'],
                       milk=request.form['milk'],
                       lat=request.form['lat'],
                       lng=request.form['lng'],
                       user_id=user_id)
        session.add(newCafe)
        session.commit()
        # redirect to main page
        return redirect(url_for('showMainPage'))
    else:
        # show forms to create new cafe on GET
        cafes = session.query(Cafe).all()
        return render_template('newCafe.html', cafes=cafes)
Exemplo n.º 17
0
sf = City(code='sf', name='San Francisco', state='CA')
berk = City(code='berk', name='Berkeley', state='CA')
oak = City(code='oak', name='Oakland', state='CA')

db.session.add_all([sf, berk, oak])
db.session.commit()

#######################################
# add cafes

c1 = Cafe(
    name="Bernie's Cafe",
    description='Serving locals in Noe Valley. A great place to sit and write'
    ' and write Rithm exercises.',
    address="3966 24th St",
    city_code='sf',
    url='https://www.yelp.com/biz/bernies-san-francisco',
    image_url=
    'https://s3-media4.fl.yelpcdn.com/bphoto/bVCa2JefOCqxQsM6yWrC-A/o.jpg')

c2 = Cafe(
    name='Perch Coffee',
    description='Hip and sleek place to get cardamom lattés when biking'
    ' around Oakland.',
    address='440 Grand Ave',
    city_code='oak',
    url='https://perchoffee.com',
    image_url=
    'https://s3-media4.fl.yelpcdn.com/bphoto/0vhzcgkzIUIEPIyL2rF_YQ/o.jpg',
)
Exemplo n.º 18
0
sf = City(code='sf', name='San Francisco', state='CA')
berk = City(code='berk', name='Berkeley', state='CA')
oak = City(code='oak', name='Oakland', state='CA')

db.session.add_all([sf, berk, oak])
db.session.commit()


#######################################
# add cafes

c1 = Cafe(
    name="Bernie's Cafe",
    description='Serving locals in Noe Valley. A great place to sit and code'
        ' and code.',
    address="3966 24th St",
    city_code='sf',
    url='https://www.yelp.com/biz/bernies-san-francisco',
    image_url='https://s3-media4.fl.yelpcdn.com/bphoto/bVCa2JefOCqxQsM6yWrC-A/o.jpg'
)

c2 = Cafe(
    name='Perch Coffee',
    description='Hip and sleek place to get cardamom lattés when biking'
        ' around Oakland.',
    address='440 Grand Ave',
    city_code='oak',
    url='https://perchoffee.com',
    image_url='https://s3-media4.fl.yelpcdn.com/bphoto/0vhzcgkzIUIEPIyL2rF_YQ/o.jpg',
)
Exemplo n.º 19
0
import os
from models import Pessoa, Sala, Cafe
from config import db, arquivobd

# Teste das classes criadas
if __name__ == "__main__":
    if os.path.exists(arquivobd):
        os.remove(arquivobd)

    db.create_all()
    s1 = Sala(nome_sala="Sala 01", lotacao=10)
    s2 = Sala(nome_sala="Sala 02", lotacao=11)
    s3 = Sala(nome_sala="Sala 03", lotacao=10)
    s4 = Sala(nome_sala="Sala 04", lotacao=11)

    c1 = Cafe(nome_cafe="House")

    db.session.add(s1)
    db.session.add(s2)
    db.session.add(s3)
    db.session.add(s4)
    db.session.add(c1)
    db.session.commit()

    p1 = Pessoa(nome="Cristina", sobrenome="de Souza", sala=s1, cafe=c1)
    p2 = Pessoa(nome="Paulo", sobrenome="Silva", sala=s1, cafe=c1)
    p3 = Pessoa(nome="Tomas", sobrenome="Alberto", sala=s2, cafe=c1)
    p4 = Pessoa(nome="Ana", sobrenome="Clara", sala=s1, cafe=c1)

    db.session.add(p1)
    db.session.add(p2)