Flask Python and css variable



我目前正在尝试用python和flask构建一个在线随机颜色生成器。我已经创建了我的函数,它生成一个随机十六进制颜色代码,我很难将其传递到 css 背景颜色中。

def random_color():
def r():
    return random.randint(0, 255)
return ('#%02X%02X%02X' % (r(), r(), r()))

BR

爱德华

您可以尝试在代码示例中生成随机十六进制值(或我所做的方式,只需使用 random.sample 和 range 稍微改进代码(,并将该值传递到模板上下文中,在那里您可以将其放在<style>标签中的某个位置。这将呈现模板并在每次访问页面时替换动态值。

# app.py
import random
from flask import Flask, render_template
app = Flask(__name__)

@app.route('/')
def home():
    hex = '#{:02x}{:02x}{:02x}'.format(*random.sample(range(256), 3))
    return render_template('index.html', hex=hex)
if __name__ == '__main__':
    app.run(debug=True)
# templates/index.html
<!DOCTYPE html>
<html>
<head>
    <title>Home Page</title>
    <meta charset="UTF-8">
    <style>
        body {
            background-color: {{ hex }};
        }
    </style>
</head>
<body>
    <h1>Home Page</h1>
</body>
</html>

最新更新