My template is as follows:
<!-- template1.html -->
<html>
<head>
<title>Item Details</title>
</head>
<body>
<p>{{ req }}</p>
</body>
</html>
To render the template I am using the following code:
from fastapi import FastAPI
from fastapi.templating import Jinja2Templates
app = FastAPI()
template = Jinja2Templates(directory="templates")
#app.get("/list_items")
def home(request: Request):
return template.TemplateResponse('template1.html',{"req": req})
#app.get("/", response_class=HTMLResponse)
async def read_items():
return """
<html>
<head>
<title></title>
</head>
<body>
<form action="/list_items">
<input type="text" placeholder="Search.." name="search">
<button type="submit">Search</button>
</form>
</body>
</html>
"""
But I do not want to use a separate folder with files for a simple template. How do I pass the html text instead of the function TemplateResponse
You can use HTMLResponse. Pass HTMLResponse as the parameter response_class of your route.
from fastapi import FastAPI
from fastapi.responses import HTMLResponse
app = FastAPI()
#app.get("/items", response_class=HTMLResponse)
def read_items():
return """
<html>
<head>
<title>Some HTML in here</title>
</head>
<body>
<h1>Look ma! HTML!</h1>
</body>
</html>
"""
You can also override the response directly in your endpoint, by returning it.
from fastapi import FastAPI
from fastapi.responses import HTMLResponse
app = FastAPI()
#app.get("/items")
def read_items():
html_content = """
<html>
<head>
<title>Some HTML in here</title>
</head>
<body>
<h1>Look ma! HTML!</h1>
</body>
</html>
"""
return HTMLResponse(content=html_content, status_code=200)
Update
Jinja2Templates.TemplateResponse expects as name parameter a filename that is pointing to the template your would like to return, and which lies in the Jinja2Templates directory you defined (e.g., Jinja2Templates(directory="templates") ). You can't pass the template contents to its place. Jinja2Templates will attempt to retrieve the file you passed using the directory you defined earlier, see here -> here -> here. Hence, what you are asking, it doesn't seem to be natively possible (but, with some hackish stuff maybe doable); however, there is nothing wrong with having a templates directory, even for small template files.
Related
I need to get the param of the url inside a html file, but I need to know if is possible in a tag, or how can I get the url params using Class-based views?
My urls.py file
from django.urls import path
from .views import UsersView
urlpatterns = [
path('list/<int:pk>/', UsersView.as_view(), name='user_list'),
]
My html file:
<!DOCTYPE html>
<html lang="en">
<head>
<title>Users</title>
</head>
<body>
{{ request.GET.pk }}
</body>
</html>
You can use
self.kwargs['pk']
Inside a CBV to get the URL parameter, since there is a <int:pk>
I am trying to make a webpage using flask and html with
render_template()
but I cant see any text from my html document. I see the <title> appear, but nothing from the paragraphs is showing up.
Here is my code:
from flask import Flask, render_template
from threading import Thread
app = Flask('', template_folder='/home/runner/Alix')
#app.route('/')
def main():
return render_template('home.html')
def run():
app.run(host="0.0.0.0", port=8080)
def keep_alive():
server = Thread(target=run)
server.start()
I am using the keep_alive() function in a separate file, with a discord bot.
Here is my html:
<html>
<head>
<title>[ALIX FLASK SERVER]<title>
<style>
body{
background_color: black;
}
</style>
<head>
<body>
<p>
This text wont show
</p>
</body>
</html>
You have not closed the head tag, the second one should be </head>
I'm new to html, i have researched a lot, but cannot solve this issue. I'm sure for you it is trivial, but I stuck.
So
I have a flask webserver. that is the code:
it is so simple, just loading the home.html and I guess the issue will be here somewhere, but I cannot find it.
all html docs are in the same folder, in the templates. the home.html loading nicely, but nothing other. I mean if I change in the return render_template the html it will be loaded, but not throug the webpage by clicking.
from flask import Flask, render_template
app = Flask(__name__, template_folder='templates')
#app.route('/')
def home():
template_table = {
'title': "Home Control System"
}
return render_template('home.html', **template_table)
#app.route('/')
def lakas():
return render_template('lakas.html')
if __name__=='__main__':
app.run(debug=True, host='0.0.0.0')
this is the home.html code:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>{{ title }}</title>
<link rel="stylesheet" type="text/css" href="../static/css/style.css?version=15">
<script type="text/javascript" src="../static/js/scripts.js?version=2"></script>
</head>
<body onload="renderTime()">
<div class="wrapper">
<div style="font-size: 1.5em", style="font-weight: bold">Menü</div>
<div class="nested_1">
<div align="right">Home Control System</div>
<div id="clockDisplay" align="right"></div>
</div>
<div class="nested_2">
Főoldal
Lakás
Garázs
</div>
<iframe src="overview.html" name="targetframe" allowTransparency="true" scrolling="no" frameborder="0"></iframe>
</div>
</body>
</html>
the folder structure is:
main
static
templates
home.html
lakas.html
garazs.html
and if I simple open the home.html everything works perfectly, I can click on the buttons(Főoldal, Lakás, Garázs)
but, when I run the flask app and I reach that through the IP I have the home page, but 404 for the rest of them. I attach picture about the ok screen and the 404.
Not found screen
OK screen
What should I change? Could you help me please?
Both your routes are the same? I'm assuming lakas should be its own page so you should change #app.route('/') to #app.route('/lakas')
#app.route('/')
def home():
template_table = {
'title': "Home Control System"
}
return render_template('home.html', **template_table)
#app.route('/')
def lakas():
return render_template('lakas.html')
Change the url in home.html to Lakás
I think you might be having trouble understanding routes. An understanding of MVC might help.
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.
hi i am trying to implement a chat type module. My front end in a HTML page from which i GET a data. The obtained data is passed to python flask. And finally the processed data must be posted back to the same HTML page.
I am able to GET the data. But unable to post it back to the same HTML page.
the following is the HTML code
<html>
<head>
<meta charset="UTF-8">
<script type="text/javascript" src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
<script>
function ajaxcall(){
var p_name = $('#p_name').val();
var p_email = $('#p_email').val();
$.post("http://127.0.0.1:5000/getdata?chatbox="+p_name);
}
</script>
</head>
<form action="" method="POST" name='chat'>
<div>
{{text_typed}}
</div>
Enter Chat: <textarea id="p_name" name="chatbox" rows="4" cols="50"></textarea>
<input type="button" onclick="ajaxcall()" value="submit me!" />
<label name='get_test' id='get_test'></label>
</form>
</html>
the value entered in the text area must be posted in {{text_typed}}. i am unable to get this
this is my python flask coding [i am performing this in a local environment]
from flask import Flask, jsonify, request, render_template, flash, url_for, redirect #import objects from the Flask model
app = Flask(__name__) #define app using Flask
#app.route('/')
def hello():
print("hello")
return "Welcome to mychat.in"
#app.route('/chat', methods=['GET', 'POST'])
def chat():
return render_template("getpost.html")
#app.route('/getdata', methods=['GET', 'POST'])
def getdata():
print('hi')
text_typed = request.args.get('chatbox')
print(text_typed)
return render_template("getpost.html", text_typed = text_typed)# this is the line i am trying to post back in html
if __name__ == '__main__':
app.run()
Thanks in advance.
Update your JS code:
$.post("http://127.0.0.1:5000/getdata?chatbox="+p_name);
According to the jQuery documentation you should put it as
$.post("http://127.0.0.1:5000/getdata?chatbox="+p_name, null, function(data) {
Put your code to insert returned _data_ into the form here.
});