示例#1
0
def product(product_id=None):
    '''
    Product view.
    CREATE TABLE products (
        product_id INTEGER PRIMARY KEY AUTOINCREMENT,
        name TEXT UNIQUE NOT NULL,
        price REAL NOT NULL,
        description TEXT NOT NULL,
        image TEXT,
        stock INTEGER DEFAULT 0
    );
    '''

    command = f'SELECT * FROM products WHERE product_id = {product_id}'
    prod = db.get_from_db(command)
    prod = prod.fetchall()[0]

    command = f'SELECT * FROM reviews WHERE product_id = {product_id}'
    reviews = db.get_from_db(command)
    reviews = reviews.fetchall()

    resp = make_response(
        render_template('product.html',
                        product_id=prod["product_id"],
                        name=prod["name"],
                        price=prod["price"],
                        description=prod["description"],
                        image=prod["image"],
                        stock=prod["stock"],
                        reviews=reviews))
    return resp
示例#2
0
def secrets(secret_key: str, code_phrase: str) -> dict:
    """It takes two parameters (secret_key, code_phrase) and returns the decoded secret

    Parameters
    ----------
    secret_key: str
        the unique identifier of the secret
    code_phrase: str
        code phrase for accessing a secret (max_length=200)

    Returns
    -------
    dict
        a dict like {"secret": returned_secret}
    """
    data_from_database = get_from_db(secret_key)
    if "error" in data_from_database.keys():
        return data_from_database

    decoded_code_phrase = str_decode(data_from_database["code_phrase"])
    if decoded_code_phrase == code_phrase:
        delete_from_db(secret_key)
        decoded_secret = str_decode(data_from_database["secret"])
        return {"secret": decoded_secret}
    else:
        return {"error": "code phrase isn't correct"}
示例#3
0
文件: login.py 项目: mmalmi1/piWASTE
def login():
    """
    Login returns three cookies:
        logged_in: True/False string
        user_id: user id integer as string
    """
    error = None
    logged_in = 'False'
    user_id = '0'
    resp = make_response(render_template('login.html'))
    if request.method == 'POST':
        username = request.form['username']
        password = request.form['password']
        command = f'SELECT user_id, access_level FROM users WHERE username="******" AND password="******"'

        # If multiple results are returned by the db query, will pick the first one.
        user = db.get_from_db(command).fetchone()
        if user is None:
            error = 'Invalid Credentials. Please try again.'
            resp = make_response(render_template('login.html', error=error))
        else:
            logged_in = 'True'
            user_id = str(user["user_id"])
            resp = make_response(redirect(url_for('index')))
    resp.set_cookie('logged_in', logged_in)
    resp.set_cookie('user_id', user_id)
    return resp
示例#4
0
def edit():
    """
    Edit the user profile
    """
    user_id = eval(request.cookies.get('user_id'))
    if request.method == 'GET':
        command = f'SELECT name, phone, address, password FROM users WHERE user_id = {user_id}'
        profile = db.get_from_db(command).fetchall()
        if len(profile) > 0:
            profile = profile[0]
            return make_response(
                render_template('edit_profile.html',
                                name=profile['name'],
                                phone=profile['phone'],
                                address=profile['address'],
                                password=profile['password']))
        return Response("Need to log in to access profile information", 401)
    if request.method == 'POST':
        name = request.form['name']
        address = request.form['address']
        phone = request.form['phone']
        password = request.form['password']
        if name:
            command = f'UPDATE users SET name = "{name}" WHERE user_id = {user_id}'
            db.push_into_db(command)
        if address:
            command = f'UPDATE users SET address = "{address}" WHERE user_id = {user_id}'
            db.push_into_db(command)
        if phone:
            command = f'UPDATE users SET phone = "{phone}" WHERE user_id = {user_id}'
            db.push_into_db(command)
        if password:
            command = f'UPDATE users SET password = "******" WHERE user_id = {user_id}'
            db.push_into_db(command)
        return make_response(redirect(url_for('profile.profile')))
示例#5
0
def test_push_into_db(app):
    with app.app_context():
        name = "test"
        price = 10
        description = "description"
        image = "imagestring"
        stock = 10
        command = f'INSERT INTO products (name, price, description, image, stock) VALUES ("{name}", "{price}", "{description}", "{image}", "{stock}")'
        assert push_into_db(command)
        assert bool(get_from_db(f'SELECT * FROM products WHERE name = "{name}" AND price = {price} AND description = "{description}" AND image = "{image}" AND stock = {stock}'))
示例#6
0
def search(name=None):
    if name == None:
        command = f'SELECT product_id, name, price, description, image, stock FROM products WHERE visible = 1'
    else:    
        command = f'SELECT product_id, name, price, description, image, stock FROM products WHERE name LIKE "%{name}%" AND visible = 1'
    entrys = db.get_from_db(command)
    payload = []

    for i in entrys:
        payload.append({'product_id': i[0], 'name': i[1], 'price': i[2], 'description': i[3], 'image': i[4], 'stock': i[5]})
    return jsonify(payload)
示例#7
0
def test_get_from_db(app):
    with app.app_context():
        case = {
            "name": "Teddy",
            "price": 10.15,
            "description": "Little broken teddy trying to find new home. Might need some" + \
                           " additional cleaning. Otherwise in perfect condition.",
            "image": 'assets/broken_teddy1.png',
            "stock": 10
        }
        rows = get_from_db("SELECT * FROM products")
        row = rows.fetchone()
        for key, value in case.items():
            assert row[key] == value
示例#8
0
def get_from_db(userId=None):
    """
    Get user's purchase history by id, return json.
    """
    command = f'SELECT * FROM purchase_history WHERE user_id = {userId}'
    entrys = db.get_from_db(command)
    payload = []

    for i in entrys:
        payload.append({
            'user_id': i[0],
            'shopping_cart': i[1],
            'timestamp': i[2]
        })
    return jsonify(payload)
示例#9
0
def profile():
    """
    User profile view
    """

    user_id = eval(request.cookies.get('user_id'))
    command = f'SELECT username, name, email, phone, address FROM users WHERE user_id = {user_id}'
    profile = db.get_from_db(command).fetchall()
    if len(profile) > 0:
        profile = profile[0]
        return make_response(
            render_template('profile.html',
                            user_id=user_id,
                            username=profile['username'],
                            name=profile['name'],
                            email=profile['email'],
                            phone=profile['phone'],
                            address=profile['address']))
    return make_response(redirect(url_for('login.login')))
示例#10
0
def shopping_cart():
    """ 
    Shopping cart view
    """

    if request.method == 'GET':
        return render_template('cart.html')

    if request.method == 'POST':
        if request.cookies.get('logged_in') == "True":
            product_ids = eval(request.cookies.get(
                'shopping_cart',
                '{}'))  #list of product ids, get product ids from cookie
            shopping_cart = dict()
            user_id = request.cookies.get('user_id')

            cart = {}
            for pid, amount in product_ids.items():
                # Ignore items that have 0 amount
                if amount != 0:
                    command = f'SELECT * FROM products WHERE product_id = {pid}'
                    prod = db.get_from_db(command)
                    prod = prod.fetchall()[0]
                    cart[prod["name"]] = [
                        amount, round(prod["price"] * amount, 2)
                    ]
            cart = str(cart)
            t = time.asctime()
            command = f'INSERT INTO purchase_history (user_id, shopping_cart, timestamp) VALUES ("{ user_id }", "{ cart }", "{ t }")'
            print(command)
            if db.push_into_db(command):
                resp = make_response(
                    redirect(url_for('shopping_cart.shopping_cart')))
                # Reset shopping cart
                resp.delete_cookie('shopping_cart')
            else:
                resp = make_response("Cannot make purchase!")

        else:
            resp = make_response("Please login to make a purchase")

        return resp
示例#11
0
def get_shopping_cart():
    """ 
    Get shopping cart
    TODO: Add remove product from cart
    """
    product_ids = eval(request.cookies.get(
        'shopping_cart',
        '{}'))  #list of product ids, get product ids from cookie
    shopping_cart = dict()
    for pid, amount in product_ids.items():
        command = f'SELECT * FROM products WHERE product_id = {pid}'
        data = db.get_from_db(command).fetchone()
        shopping_cart[pid] = {
            'name': data['name'],
            'price': data['price'],
            'description': data['description'],
            'amount': amount,
            'image': data['image']
        }
    print("shopping cart:", shopping_cart)
    return make_response(shopping_cart)
示例#12
0
def create_product():
    """
    Creates a new product. Currently not possible to set product image, uses assets/placeholder.png
    Name, price, description and stock need to be provided
    Visible is optional (defaults to 1)
    example: /admin/create_product?name=<name>&price=<price>&description=<description>&stock=<stock>

    """
    vals = request.args

    # Check access level from database
    user_id = eval(request.cookies.get('user_id'))
    command = f'SELECT access_level FROM users WHERE user_id="{user_id}"'
    user = db.get_from_db(command).fetchone()
    access_level = user["access_level"]

    if access_level < 2:
        return Response("Unauthorized", 403)
    command = f'INSERT INTO products (name, price, description, stock, image, visible) VALUES ("{vals.get("name")}", "{vals.get("price")}", "{vals.get("description")}", "{vals.get("stock")}", "assets/placeholder.png", "{vals.get("visible", 1)}")'
    if db.push_into_db(command):
        return "Created product"
    return "Failed to create product"
示例#13
0
def create_product_yaml():
    """
    Eat a yaml, and create product from the data.
    Example curl command. Only admin (user id 0) has the required access level to use this:
    curl --cookie 'user_id=1' -X POST '127.0.0.1:5000/admin/create_product_yaml' --data-binary @prod_list.yml

    Sample of prod_list.yml:
    ------------------------------------------------------
    products:
    - name: test
      price: 1
      description: testdesc
      stock: 4
      image: test
      visible: 1
    - name: another_test
      price: 20
      description: Very cool
      stock: 20
      image: another_test
      visible: 0
    ------------------------------------------------------

    """
    # Check access level from database
    user_id = eval(request.cookies.get('user_id'))
    command = f'SELECT access_level FROM users WHERE user_id="{user_id}"'
    user = db.get_from_db(command).fetchone()
    access_level = user["access_level"]
    if access_level < 2:
        return Response("Unauthorized", 403)

    product_yaml = full_load(request.get_data())
    products = product_yaml.get("products", [])
    for p in products:
        command = f'INSERT INTO products (name, price, description, stock, image, visible) VALUES ("{p.get("name")}", "{p.get("price")}", "{p.get("description")}", "{p.get("stock")}", "assets/placeholder.png", "{p.get("visible", 1)}")'
        if not db.push_into_db(command):
            return f"Failed to create product {p}"
    return f"Created {len(products)} products."
示例#14
0
def submit_review(product_id=None):
    '''
    Post a review for a product
    '''
    if request.cookies.get('logged_in') == "True":
        message = request.form['message']
        user_id = request.cookies.get('user_id')

        command = f'SELECT username FROM users WHERE user_id = {user_id}'
        username = db.get_from_db(command)
        username = username.fetchall()[0]
        username = username["username"]

        command = f'INSERT INTO reviews (text, username, product_id) VALUES ("{message}", "{username}", "{product_id}")'
        if db.push_into_db(command):
            resp = make_response(product(product_id))
        else:
            resp = make_response(
                "You have already posted a review for this product!")
    else:
        resp = make_response("Please login to leave review!")

    return resp