[英]How can you use flask to make the text of your website blue?
怎么用flask把網站的文字變成藍色? 我只知道如何在您的網站上顯示文字。 我的代碼:
from flask import Flask
app = Flask(__name__)
@app.route('/')
def hello_world():
return '''Hello world'''
這是一個 CSS 問題,而不是 Flask。
return '<span style="color: #00ccff;">Hello world</span>'
盡管來自其他用戶的負面反饋,但這並不是一個糟糕的問題,除了@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 應用程序中使用它的實例很多,其中之一是:
我假設您的意思是從網絡上拍攝圖像。 是的,你可以,但這絕對是一個與 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 中。
在類 FileContent(db.Model) 中:
data = file.read() 它將文件的二進制版本保存在數據庫中 -render_file = render_picture(data)。 它保存解碼版本,以便您可以在網頁中看到它以呈現它。
# 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:解碼文件,以便您可以檢索它和網頁中的渲染
#Render the pics,這個Function把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')
<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>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.