Ответы пользователя по тегу Flask
  • Как передать данные из localstorage во flask?

    @iiantonii Автор вопроса
    import os
    
    from flask import Flask, render_template, flash, redirect, url_for, session, request, logging
    from flask_sqlalchemy import SQLAlchemy
    import urllib.request
    from wtforms import Form, StringField, TextAreaField, PasswordField, validators
    from passlib.hash import sha256_crypt
    from functools import wraps
    import json
    from selenium import webdriver
    from selenium.webdriver.common.keys import Keys
    
    app = Flask(__name__)
    
    app.config['SQLALCHEMY_DATABASE_URI'] = 'postgresql://webadmin:OELdtt45148@136.144.31.16/postgres'
    app.secret_key = os.urandom(24)
    db = SQLAlchemy(app)
    
    class Klient (db.Model):
        id = db.Column(db.Integer, primary_key=True)
        inn = db.Column(db.String(50))
        password = db.Column(db.String(50))
    
    
    class Katalog (db.Model):
        id = db.Column(db.Integer, primary_key=True)
        name_tovar = db.Column(db.String(150))
        kat = db.Column(db.String(150))
        artikul = db.Column(db.String(150))
        ostatok = (db.Integer)
        price = (db.Float(50, 2))
        img_links = (db.String(250))
    
        def __repr__(self):
            return format(self.price)
    
    
    # User login
    @app.route('/', methods=['GET', 'POST'])
    def login():
        if request.method == 'POST':
            # Get Form Fields
            username = request.form['username']
            password_candidate = request.form['password']
    
            # Create cursor
            #cur = mysql.connection.cursor()
            result = Klient.query.filter_by(inn=username).first()
    
            # Get user by username
            #result = cur.execute("SELECT * FROM users WHERE username = %s", [username])
    
            if result:
                # Get stored hash
                #data = cur.fetchone()
                data = result.password
                password = data
                #print(password)
                #print('ii',password_candidate)
                #print('iiu', username)
    
                # Compare Passwords
                #if sha256_crypt.verify(password_candidate, password):
                if password_candidate == password:
                    # Passed
                    session['logged_in'] = True
                    session['username'] = username
    
                    flash('You are now logged in', 'success')
                    return redirect(url_for('test1'))
                else:
                    error = 'Invalid login'
                    return render_template('index.html', error=error)
                # Close connection
                #cur.close()
            else:
                error = 'Username not found'
                return render_template('index.html', error=error)
    
        return render_template('index.html')
    
    # Check if user logged in
    def is_logged_in(f):
        @wraps(f)
        def wrap(*args, **kwargs):
            if 'logged_in' in session:
                return f(*args, **kwargs)
            else:
                flash('Unauthorized, Please login', 'danger')
                return redirect(url_for('login'))
        return wrap
    
    # test login
    @app.route('/test', methods=['GET', 'POST'])
    @is_logged_in
    def test1():
        b1 = session ['username']
        incomplete = Katalog.query.filter_by(kat='s').all()
        #b3 = request.get_data()
        return render_template('test.html', b1=b1, b2=incomplete)
    
    # test login
    @app.route('/test1', methods=['GET', 'POST'])
    
    def test2():
    
        response1 = urllib.request.urlopen('/test')
        data = response1.json()
        print(data)
        return
    
    
    # Logout
    @app.route('/logout')
    @is_logged_in
    def logout():
        session.clear()
        flash('You are now logged out', 'success')
        return redirect(url_for('login'))
    
    if __name__ == '__main__':
    
        app.run(debug='True')
    Ответ написан
  • Проблема вывода значение типа float на html?

    @iiantonii Автор вопроса
    Решение нашлось само по себе. В таблице в базе присвоил данным значение string , А в выводе в шаблоне в подставил float
    <p>Цена: <span class="item_price">{{ Katalog.artikul|float}}</span> руб.</p>


    И в принципе заработало
    Ответ написан
    Комментировать