Results cannot be displayed in the web app created in Python (Bottle)

Asked 2 years ago, Updated 2 years ago, 134 views

I'm a Python beginner.
I would like to display the program I created in Python (simple calculation/mahjong library) in my web browser using the bottle framework.

*Partial modifications

Python 3.8 and above
bottle0.12.19
mahjong 1.1.11

project
 v views
│ inindex.html
 │ m mahjong.html
 main.py

If you press the submit displayed in oclocalhost:8080/ ", you will be moved to the oclocalhost:8080/mahjong 移動 page, but the calculation results (print_hand_result(result) running on main.py are displayed as None.

I know that print_hand_result is not displayed, because if I only see results on the browser, the results will be displayed.

I would like to be able to display (print_hand_result(result)), what should I do?
Please let me know.

Bottle v0.12.19 server starting up (using WSGIRefServer())...
Listening on http://localhost:8080/
Hit Ctrl-C to quit.


Warning (from warnings module):
  File "<frozen importlib._bootstrap>", line 914
ImportWarning: _ImportRedirect.find_spec() not found; falling back to find_module()
#-*-coding:utf-8-*-
from bottle import route, run, template, view

import mahjong
importos
import cgi
import sys
importio

@route('/')
def index():
     return template ('index.html')

# calculation
from mahjong.hand_calculating.hand import HandCalculator
# mahjong tile
from mahjong.tile import TilesConverter
# role, option rule
from mahjong.hand_calculating.hand_config import HandConfig, OptionalRules
# cry
from mahjong.meld import Meld
# Wind (Place & Self
from mahjong.constants import EAST, SOUTH, WEST, NORTH

# Generate an instance of HandCalculator
calculator=HandCalculator()

# For output results
default print_hand_result (hand_result):
     # the number of characters in an adaptation
     print(hand_result.han, hand_result.fu)
     # Score (for Tsumoagari [left: parent loss, right: child loss], for Longagari [left: gunner loss, right:0])
     print(hand_result.cost['main'], result.cost['additional'])
     # role
     print(hand_result.yaku)
     # Details of the number of characters
     for fu_item in hand_result.fu_details:
          print(fu_item)
     print('')

# Agari shape (honors = 1: east, 2: south, 3: west, 4: north, 5: white, 6: ,, 7: middle)
tiles=TilesConverter.string_to_136_array(man='677889', pin='88', sou='456', honors='222')

# Agari tile (Man's 8)
win_tile=TilesConverter.string_to_136_array(man='8')[0]

# Crying (None)
melds = None

54# Dora (Display tile, back dora)
dora_indicators = [
    TilesConverter.string_to_136_array(pin='7')[0],
    TilesConverter.string_to_136_array(sou='9')[0],
]

# Options (Reach, Self, Field)
config=HandConfig(is_riichi=True, player_wind=SOUTH, round_wind=EAST)

# calculation
result=calculator.estimate_hand_value(tiles, win_tile, melds, dora_indicators, config)

@route('/mahjong', method=["GET", "POST")
def mahjong():
     a=print_hand_result(result)
     return template ('mahjong.html', mahjong=a)
      
if__name__=="__main__":
     run(host='localhost', port=8080, debug=True)


<!DOCTYPE html>
<html lang="jp">
<html>
<head>
  <meta http-equiv="content-type" content="text/html;charset=utf-8">
 </head>
<body>
  <center>br>br>br>
  <form action="/mahjong" method="POST">
    <h1><font color="#FF7F50"> mahjong score calculation</font>/h1><br/>br/>>
   <input type="submit" value="View Results"/>
  </form>
  </center>
</body>
</html>

<!DOCTYPE html>
<html lang="jp">
<html>
<head>
  <meta http-equiv="content-type" content="text/html;charset=utf-8">
 </head>
<body>
  <center>br>br>br>
     <h1><font color="#FF7F50"> mahjong score calculation</font>/h1><br/>br/>>
   </form>
    <p>
    Results are <br/>>br/> 
    {{ mahjong}}
    </p>
  </center>
</body>
</html>

python python3 django flask bottle

2022-09-30 16:53

1 Answers

Because the print function only displays a string on the console, the variable a is empty because print_hand_result does not return a value.
Use return to return a value from the function.

Since the result variable itself retains the data it displays, it is recommended that you expand the variable directly in the template using the template engine Jinja instead of shaping the string in the function.

The sample code below is how to process and return the result variable to an output string with the get_hand_result function, and how to display it directly with mahjong.html.
You must have installed the package, for example, pipe install jinja2 to run.

sample code

python file

#-*-coding:utf-8-*-
from bottle import route, run, view
from bottle import jinja2_template as template

import mahjong
importos
import cgi
import sys
importio

@route('/')
def index():
     return template ('index.html')

# calculation
from mahjong.hand_calculating.hand import HandCalculator
# mahjong tile
from mahjong.tile import TilesConverter
# role, option rule
from mahjong.hand_calculating.hand_config import HandConfig, OptionalRules
# cry
from mahjong.meld import Meld
# Wind (Place & Self
from mahjong.constants import EAST, SOUTH, WEST, NORTH

# Generate an instance of HandCalculator
calculator=HandCalculator()

# For output results
default print_hand_result (hand_result):
     # the number of characters in an adaptation
     print(hand_result.han, hand_result.fu)
     # Score (for Tsumoagari [left: parent loss, right: child loss], for Longagari [left: gunner loss, right:0])
     print(hand_result.cost['main'], result.cost['additional'])
     # role
     print(hand_result.yaku)
     # Details of the number of characters
     for fu_item in hand_result.fu_details:
          print(fu_item)
     print('')

# return result as string
default_hand_result(hand_result):
     lines = [ ]
     # the number of characters in an adaptation
     lines.append("{} translation {}.format(hand_result.han, hand_result.fu))
     # Score (for Tsumoagari [left: parent loss, right: child loss], for Longagari [left: gunner loss, right:0])
     lines.append("Loss 1:{}Loss 2:{}".format(hand_result.cost['main', result.cost['additional']))
     # role
     yaku_names= [y.name for y in hand_result.yaku]
     lines.append ("role: {}".format(", ".join(yaku_names)))))
     # Details of the number of characters
     for fu_item in hand_result.fu_details:
          lines.append(str(fu_item))
     lines.append('')
     print(lines)
     return lines

# Agari shape (honors = 1: east, 2: south, 3: west, 4: north, 5: white, 6: ,, 7: middle)
tiles=TilesConverter.string_to_136_array(man='677889', pin='88', sou='456', honors='222')

# Agari tile (Man's 8)
win_tile=TilesConverter.string_to_136_array(man='8')[0]

# Crying (None)
melds = None

54# Dora (Display tile, back dora)
dora_indicators = [
    TilesConverter.string_to_136_array(pin='7')[0],
    TilesConverter.string_to_136_array(sou='9')[0],
]

# Options (Reach, Self, Field)
config=HandConfig(is_riichi=True, player_wind=SOUTH, round_wind=EAST)

# calculation
result=calculator.estimate_hand_value(tiles, win_tile, melds, dora_indicators, config)

@route('/mahjong', method=["GET", "POST")
def mahjong():
     a=get_hand_result(result)
     print(a)
     t = ['a', 'b' ]
     return template('mahjong.html', mj=result, is_tsumo=config.is_tsumo, lines=a)
      
if__name__=="__main__":
     run(host='localhost', port=8080, debug=True, reloader=True)

mahjong.html

<!DOCTYPE html>
<html lang="jp">
<html>
<head>
   <meta http-equiv="content-type" content="text/html;charset=utf-8">
  </head>
<body>
  <center>br>br>br>
     <h1><font color="#FF7F50"> mahjong score calculation</font>/h1><br/>br/>>
    </form>
    <p>
    If the result is a <br/> string...<br/>
    {% for line in lines%}
        {{line}}<br/>
    {% endfor%}
    </p>
    <p>
    If the result is a <br/>mahjong instance...<br/>
    {{mj.han}}Turn {{mj.fu}} Marks <br/>
    {% if is_tsumo%}
        Parent loss: {{mj.cost['main']} Child loss: {{mj.cost['additional']}}<br/>
    {% else%}
        Gunners lost points: {{mj.cost['main']}<br/>
    {% endif%} 
    Role: 
    {% for yaku in mj.yaku%}
        {{yaku.name}},
    {% endfor%}
    <br of >
    US>Mark: 
    {% for fuin mj.fu_details%}
        {{fu['fu']}} ({{fu['reason']}},
    {% endfor%}
    <br of >
    </p>
  </center>
</body>
</html>

Run Results

Run Results


2022-09-30 16:53

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.