Lucas Lucas - 28 days ago 6
HTML Question

Python/Flask/HTML and random random length variables output

Python/Flask/HTML

Code I have below does two things I wanted to achieve:

1)Produces random lenght output from randomly choosen, previously defined list of variables and shows it in html.

for instance (output):

apple orange

apple

apple orange orange

I do not want however for fruits to repeat in produced output, keeping everything else as it is.

So I want to prohibit

"apple orange orange"

from happening

How can it be achieved?

Code below:

app.py

from flask import Flask, render_template
import os
import random

app = Flask(__name__)

@app.route('/')

def main():
z=randint(1, 4)
Hash1="apple"
Hash2="orange"
Hash3="banana"
Hash4="watermelon"
fruits = [Hash1, Hash2,Hash3, Hash4]
a=[choice(fruits) for x in range(z)]
a=a

return render_template ('show.html', a=a)

if __name__ == '__main__':

app.run(host=os.getenv('IP', '0.0.0.0'),port=int(os.getenv('PORT', 8080)))


show.html

<html>

<title>App</title>

</head>


<body>

<h2>your fruits are {{ a }} </h2>


</body>


</html>

Answer

random.choice can return an item that has already been selected before. To return unique samples, use random.sample:

...
z = random.randint(1, len(fruits))
a = random.sample(fruits, z)
return render_template('show.html', a=a)