How to render Flask output to a string instead of browser - python

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)

Related

How to access Flask Request header outside route method

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)

Is there a way to pass HTML code in flask as string?

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()

Having trouble with jsonify in Flask

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)

Flask Pymongo Insert

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)

Flask redirect url with anchor

I have some problem with redirecting with anchors from python code.
My code:
func():
...
redirect(url_for('my_view', param=param, _anchor='my_anchor'))
This redirect didn't redirect me to #my_anchor.
In template link like:
works good... May be problem in flask function "redirect".
How I can use redirect with anchors in Flask?
Flask version 0.10.x
if your goal is to be redirected to a page with an anchor preselected in the url I think the problem may be connected to the function you have passed in the 'url_for'. Below is my attempt to do what you described.
views.py
from flask import Flask
from flask import redirect, url_for
app = Flask(__name__)
#app.route('/')
def hello_world():
return 'Hello World!'
#app.route('/myredirect')
def my_redirect():
return redirect(url_for('hello_world',_anchor='my_anchor'))
if __name__ == '__main__':
app.run()
This does not need a template, as as soon as you hit /myredirect you are redirected to / with anchor #my_anchor
After you get your views started with $ python views.py and navigate to http://127.0.0.1:5000/myredirect you end up on http://127.0.0.1:5000/#my_anchor
A short and simple way of doing this is
return redirect(url_for('hello_world') + '#my_anchor')
instead of
return redirect(url_for('hello_world',_anchor='my_anchor'))
which works because url_for returns a string for the endpoint.

Categories