Is there a way to pass HTML code as a string in python/flask rather than render template HTML file in a directory?
for example
from flask import Flask, render_template
app = Flask(__name__)
#app.route('/')
def home():
return render_template('index.html') # Instead of giving file path I want to pass HTML code directly
if __name__ == '__main__':
app.run()
I guess you mean something like this:
from flask import Flask
app = Flask(__name__)
HTML_AS_TEXT = """<p>hello world</p>"""
#app.route('/')
def home():
return HTML_AS_TEXT
if __name__ == '__main__':
app.run()
Related
I want to access headers for a certain API calls outside of its api route. I tried using the app_context and test_request_context but it doesn't seem to work.
from flask import Flask, request
app = Flask("app")
def access_header_for_something():
with app.test_request_context():
with app.app_context():
print(request.headers.get("Authorization"), request.host, request.path)
#app.route('/')
def index():
access_header_for_something()
return 'hello'
if __name__=="__main__":
app.run(debug=True)
Any suggestions would be really helpful
The above code snippet work with slight tweak:
from flask import Flask, request
app = Flask("app")
def access_header_for_something():
with app.app_context():
print(request.headers.get("Authorization"), request.host, request.path)
#app.route('/')
def index():
access_header_for_something()
return 'hello'
if __name__=="__main__":
app.run(debug=True)
I have a template (.html file) that I want to render to a string instead of sending the rendered result to a browser.
I expected something like this to work, where the rendered html code is assigned to output as a string:
from flask import Flask, render_template
app = Flask(__name__)
#app.route("/")
def index():
output = render_template("template.html")
if __name__ == "__main__":
app.run()
print(output)
Templates/template.html
<h1>some random text</h1>
manually push the required context might have solved the problem for me:
app = Flask(__name__)
with app.app_context():
template = render_template("template.html")
returning the string
If you are trying to escape the HTML tag and display the content in templete.html as a string on a browser you can use escape as shown below:
from flask import Flask, render_template
from markupsafe import escape, Markup
app = Flask(__name__)
#app.route("/")
def index():
output = render_template("template.html")
return escape(output)
if __name__ == "__main__":
app.run(debug=True)
I am fairly new to Flask and am currently working on a project whose goal is to transcribe mp3 files into JSON. I decided to attempt to use Flask, but it's been more challenging than I thought.
As of right now, I am able to display a example JSON file in one of my html pages, but I have not been able to format it. I looked at some previous answers that told me to use jsonify, but it hasn't worked apparently. If you guys could give me a hand, any kind of comment would be really apreciated. Here is my code:
from flask import Flask, render_template, url_for, request, redirect, json, jsonify
import json
import os
from pathlib import Path
app = Flask(__name__)
#app.route('/')
def index():
return render_template('index.html')
#app.route('/upload', methods=['POST'])
def upload():
file = request.files['inputFile']
if Path(file.filename).suffix == '.mp3':
filename = os.path.join(app.static_folder, 'data', 'json_test.json')
with open(filename) as json_test:
data = json.load(json_test)
return render_template('index2.html', data=data)
else:
return render_template('erro.html')
if __name__ == "__main__":
app.run(debug=True)
I have been working on a project in flask and I am stuck on one part where I need to figure out how to yield one flask template over another.
To illustrate what I mean, for example, I have a program like this.
main.py
from flask import Flask, stream_with_context, Response, render_template
app = Flask('app')
#app.route('/')
def hello_world():
def generate():
yield render_template('index.html')
yield render_template('index2.html')
return Response(stream_with_context(generate()))
app.run(host='0.0.0.0', port=8080)
index.html
<h3>Hi</h3>
index2.html
<h3>Bye</h3>
Running main.py returns:
Hi
Bye
Even though this makes sense, my goal is to make it result in just Bye which should replace Hi. I tried other paths like returning both but none of them worked. Any ideas on how I can do this?
It's not your case, but if you'd like to stream a template with static content, here's a way to do it. I'll be using the sleep() method to suspend the execution for 1 second.
from flask import Flask, stream_with_context, request, Response, flash
import time
from time import sleep
app = Flask(__name__)
def stream_template(template_name, **context):
app.update_template_context(context)
t = app.jinja_env.get_template(template_name)
rv = t.stream(context)
rv.disable_buffering()
return rv
data = ['Hi', 'Bye']
def generate():
for item in data:
yield str(item)
sleep(1)
#app.route('/')
def stream_view():
rows = generate()
return Response(stream_with_context(stream_template('index.html', rows=rows)))
if __name__ == "__main__":
app.run()
where templates/index.html:
{% for item in rows %}
<h1>{{ item }}</h1>
{% endfor %}
See streaming from templates in the documentation.
You would have to do you function different to use a generator like this.
from flask import Flask, stream_with_context, Response, render_template
app = Flask('app')
def page_generator():
yield render_template('index.html')
yield render_template('index2.html')
generator_obj = None
#app.route('/')
def hello_world():
global generator_obj
generator_obj = generator_obj or page_generator()
return Response(stream_with_context(next(generator_obj)))
app.run(host='0.0.0.0', port=8080)
I don't know for sure if this will work in flask.
Note that after you call hello_world twice this will fail unless you reset generator_obj to None on StopIteration.
I'm calling db dev to insert data into its collection. But it's creating a new collection and inserting data into admin db.
from app import app
from flask import Flask
from flask import jsonify
from flask import request
from flask_pymongo import PyMongo
#app.route('/')
#app.route('/index')
def index():
return "Hello, World!"
app.config['MONGO_DBNAME'] = 'dev'
app.config['MONGO_AUTH_SOURCE'] = 'admin'
app.config['MONGO_URI'] = 'mongodb://<user>:<password>#<url>:27017/admin'
mongo = PyMongo(app)
#app.route('/mongo', methods=['GET'])
def get_all_docs():
doc = mongo.db.abcd.insert({'abcd':'abcd'})
return "Inserted"
if __name__ == '__main__':
app.run(debug=True)
Am I missing something here?
PS: I tried replacing admin with dev. It gave pymongo.errors.OperationFailure: Authentication failed. I guess thats because the authentication data is in admin db.
app.config['MONGO_URI'] = 'mongodb://<user>:<password>#<url>:27017'
This, also, didn't work.
Replacing admin with dev in MONGO_URI causes Authentication Error.
Adding authSource will authenticate with admin db.
To do this, replace admin with dev?authSource=admin
from app import app
from flask import Flask
from flask import jsonify
from flask import request
from flask_pymongo import PyMongo
#app.route('/')
#app.route('/index')
def index():
return "Hello, World!"
app.config['MONGO_URI'] = 'mongodb://<user>:<password>#<url>:27017/dev?authSource=admin'
mongo = PyMongo(app)
#app.route('/mongo', methods=['GET'])
def get_all_docs():
doc = mongo.db.abcd.insert({'abcd':'abcd'})
return "Inserted"
if __name__ == '__main__':
app.run(debug=True)