【问题标题】:How can you use flask to make the text of your website blue?如何使用烧瓶使您的网站文本变成蓝色?
【发布时间】:2021-01-03 09:46:29
【问题描述】:

如何使用flask 使您网站的文本变成蓝色?我只知道如何在您的网站上显示文字。我的代码:

from flask import Flask

app = Flask(__name__)

@app.route('/')
def hello_world():
    return '''Hello world'''

【问题讨论】:

  • 这不是 Flask 问题;这是一个 HTML 问题,很容易研究
  • 但是为什么要导入flask呢?
  • 因为 Flask 是返回站点模板的框架,或者在这种情况下,只是返回字符串。重要的是字符串的主体,更改文本颜色将独立于返回响应的框架
  • Ayush Gudipati 学生 我很快就会回答你。请给我一些时间。你的问题很好。

标签: python html flask


【解决方案1】:

这是一个 CSS 问题,而不是 Flask。

return '<span style="color: #00ccff;">Hello world</span>'

【讨论】:

  • 对不起,我问这个问题时是 HTML、flask、CSS、js 的初学者,但现在我明白了。
【解决方案2】:

尽管来自其他用户的负面反馈,但这并不是一个糟糕的问题,除了@go2nirvana 没有人回答你的问题。

注意

尽管这更多是与 CSS 或 Javascript 而不是 HTML 相关的前端问题(是的,您可以在 HTML 中内嵌 CSS,但不推荐)您提出的问题可以通过多种方式在 Flask 中实现。

示例1-硬编码,不推荐买就行-

from flask import Flask

app = Flask(__name__)

@app.route('/')
def hello_world():

    my_html =  '''
    
    <body style="background-color: #e1eb34;">

    
        <h1 style="color:  #002aff;">Hello World</h1>
    
    </body>
    
    ''' 
    return my_html

if __name__ == '__main__':
    app.run(debug=True)

from flask import Flask

app = Flask(__name__)

@app.route('/')
def hello_world():
    return '''
    
    <body style="background-color: #e1eb34;">

    
        <h1 style="color:  #002aff;">Hello World</h1>
    
    </body>
    
    '''

if __name__ == '__main__':

示例 2 - 使用 Jinja2 DOCS##

from flask import Flask, render_template

app = Flask(__name__)

@app.route('/')
def hello_world():

    color = {
        'blue': '002aff',
        'yellow': 'e1eb34',
        'green': '28fc03',
        'red': 'fc1703', 
        'purple': 'b503fc'}

    return render_template('index.html', color=color)



if __name__ == '__main__':
    app.run(debug=True)

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Document</title>
    </head>
    <body style="background-color: #{{color['yellow']}};">

        {% for hue in color.values() if hue != 'e1eb34'%}
        
            <h1 style="color: #{{hue}};">Hello World</h1>
        {% endfor %}
        <h1></h1>
        
    </body>
</html>

示例 3 - 添加请求、会话、重定向、url_for 等更多乐趣

from flask import Flask, render_template, redirect, url_for, request, session
import random

app = Flask(__name__)

app.config['SECRET_KEY'] = 'dev'

color = {
        'blue': '002aff',
        'yellow': 'e1eb34',
        'green': '28fc03',
        'red': 'fc1703', 
        'purple': 'b503fc', 
        'orange': 'FF9733 ',
        'black' : 'FFFFFF',
        'light-blue': '0AE5E3', 
        'pink': 'FF95AE',
        'blue-green' : '95FFCA'}

@app.route('/', methods=['GET', 'POST'])
def index():

    error = None
    if 'color' not in session:
        session['color'] = None
        session['background'] = None

    if request.method == 'POST':        
        choice = request.form['color'].lower()
        
        if choice not in color: 
            error = 'Color not in list'
            return render_template('index.html', color=session['color'], background=session['background'], error=error )
        else:
            session['color'] = color.get(choice)
           
            session['background'] = random.choice(list(color.values()))
        return redirect(url_for('index'))

    return render_template('index.html', color=session['color'], background=session['background'], error=error )

if __name__ == '__main__':
    app.run(debug=True)

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Document</title>
        
        {% if color%}
            <style>
                body {
                    color: #{{color}};
                    background-color: #{{background}};
            
            }
            </style>
        {% endif %}
        
    </head>
    <body>

        <h1>Hello World</h1>
        {% if error%}
            {{error}}
        {% endif %}
        <form action="{{url_for('index')}}" method="POST">
            <label for="color">Choose a color</label>
            <input type="text" name="color">
            <input type="submit" value="PRESSS" name="i_talk-with_flask">
        </form>
       
        
        
    </body>
</html>

DOC的变化

{% macro color_mix(color)%}
    {% if color%}
        <style>
            body {color: #{{color}};}
            body {background-color: #{{background_}};}
        </style>
    {% endif %}

{% endmacro%}


<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Document</title>
        
        {{color_mix(color)}}
    </head>
    <body>

        <h1>Hello World</h1>
        {% if error%}
            {{error}}
        {% endif %}
        <form action="{{url_for('index')}}" method="POST">
            <label for="color">Choose a color</label>
            <input type="text" name="color">
            <input type="submit" value="PRESSS" name="i_talk-with_flask">
        </form>
       
        
        
    </body>
</html>

老实说,这只是您可以选择的冰山一角。现在这是推荐的吗?可能不会,因为这应该用 CSS 处理,或者用 JavaScript 处理。

但是,您可能希望从 Flask 应用程序中使用它,其中之一是:

  • 测试目的。
  • 调试中。
  • 与数据库相关的东西。
  • 有趣

【讨论】:

  • 谢谢,它有帮助。现在我有一个新问题,你可以使用图像作为背景吗?如果可能的话,您可以在不下载图像的情况下使用图像作为背景吗?
  • 我做了一个单独的回答。这又是一个 HTML 和 CSS 问题,但这是一个小例子,说明你可以用 Flask 中的图片做什么
【解决方案3】:

问题 2 的答案

我假设您的意思是从网络上获取图像。是的,你可以,但这绝对是一个与 CSS/HTML 相关的问题。但是遵循我之前回答的相同原则:

图片取自Unsplash

from flask import Flask, render_template


app = Flask(__name__)


@app.route('/')
def index():

    my_pic = 'https://images.unsplash.com/photo-1469980098053-382eb10ba017?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=1050&q=80'
    return render_template('index.html', my_pic=my_pic)


if __name__ == '__main__':
    app.run(debug=True)

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body style="background-image: url(https://images.unsplash.com/photo-1600187734183-707cf1c0fd5a?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=1304&q=80);"
> 
   
    <  <div>

            <h1 style="color: white;">Picture from HTML</h1>
            <img src="https://images.unsplash.com/photo-1600298881979-9b0c50d7abdf?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=400&q=60" alt="opps">
        </div>


    <div style="color: white;">
        <h1>Picture from Flask</h1>
        <img src="{{my_pic}}" alt="oops">
    </div>
</body>
</html>

我建议你从 HTML 和 CSS 相关主题而不是 Flask 学习它(首先学习一些 CSS 和 HTML 基础):

据说我有一个更有趣的有用的答案,但是需要使用数据库的基本知识,我假设您是初学者,您可能还没有这方面的知识,但迟早您会的。因此,即使您不完全理解以下内容,请记住并稍后再回来。

我准备了一个使用flask、flask_sqlalchemy(带有sqlite3)、html和Bootstrap的迷你应用程序。

此应用程序执行以下操作并将教您这些原则:

.1 将图片上传到数据库。 .2 如何从数据库中下载图片。 .3 将图片从数据库渲染到WebBroser。

FULL CODE FROM GITHUB


这个小程序的一些代码


为数据库初始化数据库、配置和图片表

在类 FileContent(db.Model) 中:

  • data = file.read() 它将文件的二进制版本保存在数据库中 -render_file = 渲染图片(数据)。它保存解码版本,以便您可以在网页中看到它以进行渲染。

      # Built-in Imports
      import os
      from datetime import datetime
      from base64 import b64encode
      import base64
      from io import BytesIO #Converts data from Database into bytes
    
      # Flask
      from flask import Flask, render_template, request, flash, redirect, url_for, send_file # Converst bytes into a file for downloads
    
      # FLask SQLAlchemy, Database
      from flask_sqlalchemy import SQLAlchemy
    
    
      basedir = 'sqlite:///' + os.path.join(os.path.abspath(os.path.dirname(__file__)), 'data.sqlite')
    
      app = Flask(__name__)
      app.config['SQLALCHEMY_DATABASE_URI'] = basedir
      app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
      app.config['SECRET_KEY'] = 'dev'
      db = SQLAlchemy(app)
    
      # Picture table. By default the table name is filecontent
      class FileContent(db.Model):
    
          """ 
          The first time the app runs you need to create the table. In Python
          terminal import db, Then run db.create_all()
          """
          """ ___tablename__ = 'yourchoice' """ # You can override the default table name
    
          id = db.Column(db.Integer,  primary_key=True)
          name = db.Column(db.String(128), nullable=False)
          data = db.Column(db.LargeBinary, nullable=False) #Actual data, needed for Download
          rendered_data = db.Column(db.Text, nullable=False)#Data to render the pic in browser
          text = db.Column(db.Text)
          location = db.Column(db.String(64))
          pic_date = db.Column(db.DateTime, nullable=False, default=datetime.utcnow)
          def __repr__(self):
              return f'Pic Name: {self.name} Data: {self.data} text: {self.text} created on: {self.pic_date} location: {self.location}'
    

上传路径,这里是图片发送到数据库并使用正确数据处理的地方

这就是应用程序路由中发生的事情:

  • def render_picture(data) --> 获取图片的原始版本并返回解码版本,以便在网络上显示。

  • data = file.read() : 这是原始数据,可用于从数据库中下载图片

  • render_file:解码文件,以便您可以检索它并在网页中呈现

    #渲染图片,这个函数将数据从 request.files['inputFile'] 以便 in 可以显示

    def render_picture(data):
    
        render_pic = base64.b64encode(data).decode('ascii') 
        return render_pic
    
    
    @app.route('/upload', methods=['POST'])
    def upload():
    
       file = request.files['inputFile']
       data = file.read()
       render_file = render_picture(data)
       text = request.form['text']
       location = request.form['location']
    
       newFile = FileContent(name=file.filename, data=data, 
       rendered_data=render_file, text=text, location=location)
       db.session.add(newFile)
       db.session.commit() 
       flash(f'Pic {newFile.name} uploaded Text: {newFile.text} Location: 
       {newFile.location}')
    
       return render_template('upload.html')
    

索引路线

# Index It routes to index.html where the upload forms is 
@app.route('/index', methods=['GET', 'POST'])
@app.route('/')
def index():

    return render_template('index.html')

使用表单索引 HTML

<form method="POST" action="/upload" enctype="multipart/form-data">
        <!-- File Upload-->
        <div class="form-group">
            <label for="inputFile">File input</label>
            <input class="form-control-file" type="file" name="inputFile">
        </div>

        <!-- Location -->
        <div class="form-group">
            <label for="location">Location</label>
            <input class="form-control" type="text" name="location">
        </div>

        <!-- Text -->
        <div class="form-group">
            <label for="text">Write Text</label>
            <textarea class="form-control" name="text" id="text" rows="5" placeholder="Add a Description"></textarea>
        </div>

        <!-- Submit -->        
        <button type="submit" class="btn btn-primary">Submit</button>
    </form>

【讨论】:

    猜你喜欢
    • 2012-06-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-06-25
    • 1970-01-01
    • 2017-03-30
    • 1970-01-01
    相关资源
    最近更新 更多