Сериализованные выходные данные JSON SQLAlchemy не отображаются в таблице HTML

#javascript #python #ajax #flask

Вопрос:

Я добавил этот код python в свою колбу, чтобы обновить таблицу базы данных SQLAlchemy без обновления всей страницы, но мне нужно было сериализовать вывод JSON, поэтому я также дополнил код:

 @portfolioPath.route('/wallet_refresh', methods=['GET'])
def wallet_refresh():
    if request.method == "GET":
        data_query = HoldingsTable.query.all()
        
        print('n--- Encode Object into JSON formatted Data using jsonpickle ---')
        TableJSON = jsonpickle.encode(data_query, unpicklable=False)
        print(TableJSON)

        print('n--- Writing JSON Encode data into Python String ---')
        TableJSONData = json.dumps(TableJSON, indent=4)
        print(TableJSONData)

        print('n--- Decode JSON formatted Data using jsonpickle ---')
        TableJSON = jsonpickle.decode(TableJSONData)
        print(HoldingsTable)

        # Let's load it using the load method to check if we can decode it or not.
        print('n--- Load JSON using loads() method ---')
        TableJSON = json.loads(TableJSON)
        print(TableJSON)

        return json.dumps({"data":TableJSON})
    return render_template("portfolio.html")
 

и я добавил jQuery, который будет обрабатывать выполнение кнопки:

 <script type=text/javascript>
$('#wallet_refresh_id').bind('click', function() {
  $.getJSON('/wallet_refresh', function(all_crypto_data) {
     for (var i of TableJSON.data ){ // using .data, we will return json in flask 
     $("#data_holder").append(
       `
       <td>${i.crypto_id}</td>
       <td>${i.crypto_date_purchase}</td>
       <td>${i.crypto_name}</td>
       <td>${i.crypto_ticker}</td>
       <td>${i.crypto_shares}</td>
       <td>${i.crypto_price_purchase}</td>  
       <td>${i.crypto_cost_total}</td>      
       `       
       )
     } 
  });
});
</script>
 

кнопка обновления JS находится здесь:

 <h3>REFRESH THE DATABASE</h3>
  <button id="wallet_refresh_id" class='btn btn-default'>Refresh</button>
 

кнопка обновления колбы, которая перезагружает всю страницу, работает нормально:

 <form action="{{url_for('core.crypto_portfolio')}}" method="POST">
  <div class="form-group">
    <div class="col-md-2 col align-self-end">
          <button class="btn btn-primary float-end" type="submit" style="margin:5px;">1. Find It!</button>             
    </div>
  </div>   
</form>
 

with the portfolio table:

 <!-- Equity Holdings Overview Table -->
<table class="table table-hover table-striped table-sm">
  <tr>
    <th>ID</th>
    <th>Trade Date</th>
    <th>Name</th>
    <th>Symbol</th>
    <th>Shares</th>
    <th>Purchase Price</th>
    <th>Total Cost</th>
    <th style="text-align:right">Action</th>
  </tr>
  {% for row in all_crypto_data_html %}
  <tr id="data_holder">
    <td>{{row.crypto_id}}</td>
    <td>{{row.crypto_date_purchase}}</td>      
    <td>{{row.crypto_name}}</td>
    <td>{{row.crypto_ticker}}</td>
    <td>{{row.crypto_shares}}</td>
    <td> amp;#x24; {{row.crypto_price_purchase}}</td>
    <td> amp;#x24; {{row.crypto_cost_total}}</td>
  </tr>
 

The back-end output renders in the terminal:

— Load JSON using loads() method — [{‘sa_instance_state’: {‘instance’: None, ‘committed_state’: {}, ‘key’: [{‘py/type’:
‘advisely.models.models.CryptoTable’}, [1], None], ‘load_options’: [],
‘class
‘: {‘py/type’: ‘advisely.models.models.CryptoTable’},
‘expired_attributes’: [], ‘load_path’: [[{‘py/type’:
‘advisely.models.models.CryptoTable’}, None]], ‘manager’: {‘class_’:
{‘py/type’: ‘advisely.models.models.CryptoTable’}}},
‘crypto_date_purchase’: ‘2021-06-18’, ‘crypto_ticker’: ‘mp’,
‘crypto_cost_total’: ‘151.722’, ‘crypto_date_price_current’: ‘0’,
‘crypto_total_gain’: ‘0’, ‘crypto_shares’: ‘0.151722’, ‘crypto_name’:
‘mantra-dao’, ‘crypto_id’: 1, ‘crypto_price_purchase’: ‘1000’,
‘crypto_price_current’: ‘0’, ‘crypto_price_gain’: ‘0’},
{‘sa_instance_state’: {‘instance’: None, ‘committed_state’: {},
‘key’: [{‘py/type’: ‘advisely.models.models.CryptoTable’}, [2], None],
‘load_options’: [], ‘class
‘: {‘py/type’:
‘advisely.models.models.CryptoTable’}, ‘expired_attributes’: [],
‘load_path’: [[{‘py/type’: ‘advisely.models.models.CryptoTable’},
None]], ‘manager’: {‘class_’: {‘py/type’:
‘advisely.models.models.CryptoTable’}}}, ‘crypto_date_purchase’:
‘2021-06-22’, ‘crypto_ticker’: ‘abc’, ‘crypto_cost_total’: ‘0’,
‘crypto_date_price_current’: ‘0’, ‘crypto_total_gain’: ‘0’,
‘crypto_shares’: ‘34709’, ‘crypto_name’: ‘bitcoin’, ‘crypto_id’: 2,
‘crypto_price_purchase’: ‘0’, ‘crypto_price_current’: ‘0’,
‘crypto_price_gain’: ‘0’}, {‘sa_instance_state’: {‘instance’: None,
‘committed_state’: {}, ‘key’: [{‘py/type’:
‘advisely.models.models.CryptoTable’}, [3], None], ‘load_options’: [],
‘class
‘: {‘py/type’: ‘advisely.models.models.CryptoTable’},
‘expired_attributes’: [], ‘load_path’: [[{‘py/type’:
‘advisely.models.models.CryptoTable’}, None]], ‘manager’: {‘class_’:
{‘py/type’: ‘advisely.models.models.CryptoTable’}}},
‘crypto_date_purchase’: ‘2021-06-22’, ‘crypto_ticker’: ‘abc’,
‘crypto_cost_total’: ‘2’, ‘crypto_date_price_current’: ‘4’,
‘crypto_total_gain’: ‘6’, ‘crypto_shares’: ‘1972.67’, ‘crypto_name’:
‘ethereum’, ‘crypto_id’: 3, ‘crypto_price_purchase’: ‘1’,
‘crypto_price_current’: ‘3’, ‘crypto_price_gain’: ‘5’},
{‘sa_instance_state’: {‘instance’: None, ‘committed_state’: {},
‘key’: [{‘py/type’: ‘advisely.models.models.CryptoTable’}, [4], None],
‘load_options’: [], ‘class
‘: {‘py/type’:
‘advisely.models.models.CryptoTable’}, ‘expired_attributes’: [],
‘load_path’: [[{‘py/type’: ‘advisely.models.models.CryptoTable’},
None]], ‘manager’: {‘class_’: {‘py/type’:
‘advisely.models.models.CryptoTable’}}}, ‘crypto_date_purchase’:
‘2021-06-22’, ‘crypto_ticker’: ‘abc’, ‘crypto_cost_total’: ‘0.198239’,
‘crypto_date_price_current’: ‘4’, ‘crypto_total_gain’: ‘6’,
‘crypto_shares’: ‘0.198239’, ‘crypto_name’: ‘dogecoin’, ‘crypto_id’:
4, ‘crypto_price_purchase’: ‘1’, ‘crypto_price_current’: ‘3’,
‘crypto_price_gain’: ‘5’}]

and the code terminal log is:

2021-07-11 23:25:44 561 ИНФОРМАЦИЯ sqlalchemy.engine.ОТКАТ двигателя

127.0.0.1 — — [11/Июль/2021 23:25:44] «GET /wallet_refresh HTTP/1.1» 200 —

Но моя проблема в том, что таблица не обновляется, и вся страница перезагружается… Таким образом, очевидно, что здесь происходит исключение, которое переходит к перезагрузке страницы, а не только к перезагрузке таблицы.