<!DOCTYPE html>
<html lang="en">
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Page</title>
<link rel="stylesheet" href="{{ url_for('static', filename='styles.css') }}">
</head>
<body>
<div class = "tela">
<h1>Login</h1>
<form action="/" method = "post">
<input class = "inf" type="text" placeholder="Email">
<br><br>
<input class = "inf" type="password" placeholder="Senha">
<br><br>
<button class = "main-btt">Log in</button>
</form>
<form action="/criarconta" method="post">
<button class = "criar">Criar conta</button>
</form>
</div>
</body>
</html>
from flask import Flask, request, render_template, redirect
app = Flask("__name__")
#app.route("/")
def index():
return render_template("login.html")
#app.route("/criarconta", methods=["POST"])
def create():
return render_template("criarconta.html")
I'm working on a Login page, with flask, html and css, but always that I run flask the link that shows up is a html page without css, even when I link css in the html file. I want to resolve tis, and finds out how to open the page and the css is there. OBS: When I open the file alone, without flask, it works.
I tried using href="styles.css" but it didn't work so I changed for url_for, but its still not working.
I think the problem is in the html but I putted the python if you need.
Related
I would like to send image with Flask app when I click to predict button in my html code.
Code is supposed to get prompt and run ML model and generate image based on input prompt. I can generate the picture but somehow I can not send it to html or html doesn't show the image.
Anyone can check my flask and html code where the problem is ? My flask image send method is wrong or html part is wrong ? How to show the image in html ?
import os
import io
import base64
from PIL import Image
import torch
from torch import autocast
from diffusers import StableDiffusionPipeline, LMSDiscreteScheduler
import transformers
from flask import Flask, render_template, request
app = Flask(__name__)
lms = LMSDiscreteScheduler(
beta_start=0.00085,
beta_end=0.012,
beta_schedule="scaled_linear"
)
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
pipe = StableDiffusionPipeline.from_pretrained(
"CompVis/stable-diffusion-v1-4",
scheduler=lms,
use_auth_token=True,
cache_dir=os.getenv("cache_dir", "./models")
).to("cuda")
#app.route('/', methods=['GET'])
def page_template():
return render_template('index.html')
#app.route('/', methods=['POST'])
def predict():
prompt_text = request.form['word']
with autocast("cuda"):
image = pipe(prompt_text)["sample"][0]
data = io.BytesIO()
image.save(data, "JPEG")
encoded_img_data = base64.b64encode(data.getvalue())
return render_template("index.html", img_data=encoded_img_data.decode('utf-8'))
if __name__ == '__main__':
app.run()
<!DOCTYPE html>
<html>
<head>
<title>Tutorial</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">
</head>
<body>
<h1 class="text-center">Stable Diffusion</h1>
<form class="p-3 text-center" action='/', method="post" enctype="multipart/form-data" >
<label for="promptfield" class="form-label">StableDiffusionPrompt</label>
<input type="text" class="form-control" id="promptfield" name="word" placeholder="Please enter your prompt" />
<input class="form-control" type="file" name="imagefile" >
<input class="btn btn-primary mt-3" type="submit" value="Predict Image" >
</form>
{% if prediction %}
<img id="picture" src="data:image/jpeg;base64,{{ img_data }}">
<p> img id="picture" src="data:image/jpeg;base64,{{ img_data }}"</p>
{% endif %}
</body>
</html>
here is the output of encoded_img_data.decode('utf-8').
I have the following app.py code
from flask import Flask, render_template, request, jsonify
import numpy as np
from joblib import load
import pandas as pd
app = Flask(__name__)
#app.route("/")
def home():
return render_template("index.html")
#app.route('/predict', methods=['POST'])
def predict():
t = request.form['reviewfield']
text = [t]
pipeline = load("ModelSVMNew.joblib")
pred = pipeline.predict(text)
return render_template('after.html', data=pred)
if __name__ == "__main__":
app.run(port=3000, debug=True)
and i want a form to submit the text from chrome extension to predict function and render the html in place of the popup.html (as in manifest.json). now this works with a normal web page on local host but gives an error that the file is not accessible when doing the same on chrome extension.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Fake Review Detection</title>
</head>
<body>
<center>
<h1>Fake Review Detection</h1>
<form action="{{url_for('predict')}}" method="post">
<b> Enter Review: <input type="text" name="reviewfield" /></b> <br />
<br />
<input type="submit" value="Predict" />
</form>
</center>
</body>
</html>
I've been very confused, i am using .json file as a Database for my HTML Contents (<p>example</p>)
When i am trying to put the JSON Value from main.json to my HTML Document index2.html using Flask (Python), but it doesn't seem to work, and just returning <p>Here begins the chat</p> on my website.
Here are the codes
main.json
{
"posts": {
"divs": "<p>Here begins the chat!</p>"
}
}
index2.html
<html>
<head>
<title>Hit-Git | Social Media Platform</title>
<link rel="shortcut icon" href="{{ url_for('static', filename='michellelogo.ico') }}">
<link rel= "stylesheet" type= "text/css" href= "{{url_for('static', filename='styles/style.css') }}">
<meta name="viewport" content="width=device-width, initial-scale=1">
<ul>
<button type="button" class="topbutton" onclick="window.location.href='/'">Home</button>
<button type="button" class="topbutton active" onclick="window.location.href='/login'">News Feed</button>
<button style="float:right" type="button" class="books" onclick="window.location.href='/'">Hit-Git</button>
</ul>
</head>
<body>
<div style="text-align: center;">
<h3>News Feed is Under Construction!</h3>
<p>News Feed is currently on under testing and building, trial and errors are still happening, but rest assured, soon you will be able to use most of Hit-Git! Thank you for your patience.</p>
</div>
{{posts}}
</body>
</html>
and the main.py
#app.route("/posts", methods=['GET', 'POST'])
def posts():
allpost = data1()
daposts = allpost['posts']['divs']
daposts = str(daposts)
return render_template('posts.html', posts=daposts)
Sorry for my bad english
I have a Flask program like this that is supposed to have two side by side div tags, one for entering python code, and another one for the output:
from flask import Flask, render_template, request
import os
app = Flask(__name__)
#app.route("/python")
def python():
v = os.listdir(r"...")
return render_template("python.html", v=v)
#app.route("/run", methods=["GET", "POST"])
def run():
the_form = request.form
x = the_form.get("enter-text")
if x:
return render_template("python.html", v=x)
else:
return render_template("python.html",)
app.run(debug=True)
Here is python.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Python</title>
</head>
<body>
<p>Welcome to the WPP!</p>
<form action="/run" method="post">
<div>
<div style="float: left;" name="enter-text">
<textarea rows="20" cols="50"></textarea>
</div>
<div>
<textarea rows="20" cols="40" style="margin-left: 6%;">{{v}}</textarea>
</div>
</div>
<div name="submit">
<button type="submit">Execute</button>
</div>
</form>
<p>{{v}}</p>
</body>
</html>
When I enter print("Hello World!"), the URL is changed to /run as expected, but nothing is displayed in the output textarea tag. When I tried printing out x in the run() function, it gives me None
The name attribute must be applied to the textarea form element. Otherwise the value will not be in the POST request.
<div style="float: left;">
<textarea name="enter-text" rows="20" cols="50"></textarea>
</div>
Problem: My Bokeh plot, implemented with Flask, is not showing in my browser. When I run the app, the Bokeh frame (with the tools), as well as the x-axis label show up, but no data is plotted inside.
Already tried: I've made sure that the Bokeh version mentioned in the HTML files is as others have suggested. I'm pretty sure I've exhausted the SO solutions presented already. I've used print statements throughout the program and determined that the data is actually collected, cleaned, and processed with the components module and passed to 'script'. So therefore, as far as I can tell, the code seems to be stuck at the 'last render_template line?
from flask import Flask, render_template, request, redirect, session
import pandas as pd
import quandl
from bokeh.plotting import figure, output_file, save
from bokeh.embed import components
from bokeh.io import show
app = Flask(__name__) #create an instance of the flask class (named 'app') in the current file
app.vars={}
#app.route('/')
def main():
return redirect('/index')
#app.route('/index', methods=['GET'])
def index():
return render_template('index.html')
#app.route('/plot', methods=['POST'])
def plot():
app.vars['current_symbol'] = request.form['current_symbol']
quandl.ApiConfig.api_key = 'CD38JS9JqAdmdeio9JPW'
req_data = quandl.get_table('WIKI/PRICES', ticker=app.vars['current_symbol'], qopts = {'columns':['ticker', 'date', 'adj_close']}, date = {'gte': '2017-11-01', 'lte': '2017-12-01'}, paginate = True)
req_data.adj_close = round(req_data.adj_close, 2)
req_data = req_data.set_index('date')
cleaned_data = req_data.pivot(columns = 'ticker')
# Plot the data
p = figure(x_axis_type='datetime', x_axis_label='Date', y_minor_ticks=2, plot_width = 800, plot_height = 600)
p.line(x = cleaned_data.index, y = cleaned_data.adj_close, line_width = 2)
script, div = components(p)
return render_template('plot.html', script=script, div=div)
if __name__ == "__main__":
app.run(debug=True)
Here are the accompanying HTML files.
index.html
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Stock Plotter</title>
<link href="https://cdn.bokeh.org/bokeh/release/bokeh-1.2.0.min.css" rel="stylesheet" type="text/css">
<script src="https://cdn.bokeh.org/bokeh/release/bokeh-1.2.0.min.js"></script>
<!-- <link rel="icon" href="favicon.ico"> -->
<title>Stock Plotter</title>
<!-- Bootstrap core CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
</head>
<body>
<div class=metanav>
<h1>Stock Plotter</h1>
<div>
<form id="tickerform" action="/plot" method="POST">
Ticker Symbol: <input type="text" name="current_symbol" placeholder="ticker symbol"></input> <!--Create a dropdown list with the following options=-->
<div>
<input type="submit" value="Submit"></input> <!--Create the submit button-->
</div>
</form>
</div>
{{ script|safe }} <!--Marks the js scrips as safe for the web-->
{{ div|safe }}
<!-- Bootstrap core JavaScript
================================================== -->
<!-- Placed at the end of the document so the pages load faster -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</body>
</html>
plot.html
<html lang="en">
<head>
<meta charset="UTF-8">
<link href="https://cdn.bokeh.org/bokeh/release/bokeh-1.2.0.min.css" rel="stylesheet" type="text/css">
<script src="https://cdn.bokeh**strong text**.org/bokeh/release/bokeh-1.2.0.min.js"></script>
<title>Stock Plotter</title>
</head>
<body>
<div class=page>
<h1>Stock Plotter</h1>
{{ script|safe }}
{{ div|safe }}
</div>
</body>
</html>
I expect the plot to be visible, but it's not.
No error messages are shown in the console.
Check this post:
Embedding multiple bokeh HTML plots into flask
It has a great example as to how to display bokeh figures in flask apps.
For anyone looking for an answer, the problem with this code is that the plot definition (p.line...) has some problem with my defining the x and y values explicitly. Once I used the source argument, the plot appears as desired.