• Проблемы с кодировкой при конвертации из xls в json?

    @iiantonii Автор вопроса
    Вопрос решил сам. Вот исходник
    # -*- coding: utf-8 -*-
    import xlrd
    from collections import OrderedDict
    import simplejson as json
    import codecs
    # Open the workbook and select the first worksheet
    wb = xlrd.open_workbook('4.xlsx', encoding_override='utf-8')
    sh = wb.sheet_by_index(0)
    # List to hold dictionaries
    cars_list = []
    # Iterate through each row in worksheet and fetch values into dict
    for rownum in range(1, sh.nrows):
        kadastr = OrderedDict()
        row_values = sh.row_values(rownum)
        kadastr['kat-id'] = row_values[0]
        kadastr['vid_iz'] = row_values[1]
        kadastr['pl'] = row_values[2]
        kadastr['adres'] = row_values[3]
        kadastr['name_is'] = row_values[4]
        kadastr['pr_rez'] = row_values[5]
        cars_list.append(kadastr)
    # Serialize the list of dicts to JSON
    # j = json.dumps(cars_list, ensure_ascii=False).encode('utf8')
    # j = json.dumps(cars_list, encoding='utf-8')
    print(cars_list)
    
    # Write to file
    
    
    with codecs.open('data.json', 'w', encoding='utf-8') as f:
        json.dump(cars_list, f, ensure_ascii=False)
    Ответ написан
  • Как передать данные из 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>


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