This is my Python code:
from flask import Flask, render_template
app = Flask(__name__)
#app.route("/profile/<name>")
def profile(name):
return render_template("index.html", name=name)
if __name__ == "__main__":
app.run()
and HTML code:
<!DOCTYPE html>
<html>
<head>
</head>
<body>
Hello {{ name }}
</body>
</html>
And when I run the Python code, it shows on the browser that:
Internal Server Error
The server encountered an internal error and was unable to complete your request. Either the server is overloaded or there is an error in the application.
I looked for the solution on Google as well as Youtube, but still can't fix it. Can someone help me with this? Thank you
Edit: so all I need to do is to fix this one line:
app = Flask(__name__, template_folder="template")
Whenever we receive 500 internal server error on a Python wsgi application we can log it using 'logging'
First import from logging import FileHandler,WARNING
then after app = Flask(__name__, template_folder = 'template')
add
file_handler = FileHandler('errorlog.txt')
file_handler.setLevel(WARNING)
Then you can run the application and when you receive a 500 Internal server error, cat/nano your errortext.txt file to read it, which will show you what the error was caused by.
You must not had an empty line beetween
#app.route("/profile/<name>") and def profile(name):
You have to set the html file in a folder called templates.
You have to set the templates folder and run.py in the same folder
You can try this below by adding the type string in your #app.route :
#app.route("/profile/<string:name>")
def profile(name):
return render_template("test.html", name=name)
Related
Recently, I have started working on a new project : a web app which will take a name as an input from a user and as result outputs the database rows related to the user input. The database is created using PostgreSQL and in order to complete the task I am using Python as a programming language, followed by Flask (I am new to it) and HTML. I have created 2 source codes, 1 in Python as below :
import os
import psycopg2 as pg
import pandas as pd
import flask
app = flask.Flask(__name__)
#app.route('/')
def home():
return "<a href='/search'>Input a query</a>"
#app.route('/search')
def search():
term = flask.request.args.get('query')
db = pg.connect(
host="***",
database="***",
user ="***",
password="***")
db_cursor = db.cursor()
q = ('SELECT * FROM table1')
possibilities = [i for [i] in db_cursor.execute(q) if term.lower() in i.lower()]
return flask.jsonify({'html':'<p>No results found</p>' if not possibilities else '<ul>\n{}</ul>'.format('\n'.join('<li>{}</li>'.format(i) for i in possibilities))})
if __name__ == '__main__':
app.run()
and HTML code :
<html>
<head>
<script src = "https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
</head>
<body>
<input type='text' name ='query' id='query'>
<button type='button' id='search'>Search</button>
<div id='results'></div>
</body>
<script>
$(document).ready(function(){
$('#search').click(function(){
var text = $('#query').val();
$.ajax({
url: "/search",
type: "get",
data: {query: text},
success: function(response) {
$("#results").html(response.html);
},
error: function(xhr) {
//Do Something to handle error
}
});
});
});
</script>
</html>
For these scripts I read the discussion here.
These scripts are giving me troubles and I have two main questions :
First : How are these two source codes connected to each other? whenever I run the python script or the html, they look completly disconnected and are not functioning.Moreover, when I run the Python script it gives me this error message on the webpage :
Internal Server Error
The server encountered an internal error and was unable to complete your request. Either the server is overloaded or there is an error in the application.
and this message on terminal :
Serving Flask app 'userInferface' (lazy loading)
Environment: production
WARNING: This is a development server. Do not use it in a production deployment.
Use a production WSGI server instead.
Debug mode: off
Running on....
Can someone please help me by showing how can these 2 scripts connect and why am I getting such errors. Thank you.
You need to use render_template to connect Flask and your HTML code. For example:
from flask import render_template
#app.route("/", methods=['GET'])
def index():
return render_template('index.html')
I have a Flask App that runs 2 shell scripts and renders an HTML template index.html.
import subprocess
from flask import Flask, request, render_template
app = Flask(__name__)
#app.route('/result', methods =["POST"])
def process_html_input():
if request.method == "POST":
git_url = request.form.get("giturl")
subprocess.call(['sh', 'installer_script1.sh'])
subprocess.call(['sh', 'installer_script2.sh'])
return render_template("index.html")
if __name__=='__main__':
app.run()
I want to print the content of the Python console as and when it appears (while the script is executing) to the same HTML template index.html -
<html lang="en">
<body>
</body>
</html>
I'm unable to write it, can someone help me with the python and HTML code ?
I have tried this but unable to make it work.
Check the following code that runs one command, try it, and if it worked you can put other commands as well.
Notes:
Yield is a generator function, it helps you to get the result of the subprocess.
Using -u switch when you want to run the shell in order to prevent output buffering.
import subprocess
from flask import Flask, request, render_template
app = Flask(__name__)
#app.route('/result', methods =["POST"])
def process_html_input():
def inner():
git_url = request.form.get("giturl")
command = ['sh', '-u installer_script1.sh'] # -u: avoid buffering the output
proc = subprocess.Popen(
cmd,
stdout=subprocess.PIPE,
)
for line in proc.stdout:
yield highlight(line, BashLexer(), HtmlFormatter())
env = Environment(loader=FileSystemLoader('app/templates'))
tmpl = env.get_template('index.html')
return Response(tmpl.generate(result=inner()))
if __name__=='__main__':
app.run()
Also, you can check and use the proposed solution of the following link:
HTTP streaming of command output in Python Flask
I am using below Python Flask code for reading remote user name in the web page.
and name = Request.remote_user.name is printing me REMOTE_USER as output can some one really tell me which particular configuration in web server i need to look at ? or how to get the real remote_user name into the web page.
from flask import Flask
from flask import Flask, render_template, Request, jsonify
app = Flask(__name__)
import flask
import os
import getpass
#app.route("/")
def hello():
return render_template('hello.html',name=name)
name =flask.Request.remote_user.name
if __name__ == "__main__":
app.run('localhost',8000)
and hello.html
<!doctype html>
<html>
<body>
<h1>Hello- {{ name }} </h1>
</body>
</html>
You can use
print(request.headers)
this will give you list of all session variables.
for getting a remote user
print(request.headers[X-Remote-User])
I guess we can use below code snippet initially to identify all headers and then the required one i.e. remote user
Identify all the Headers & values passed in the request
print("Headers: ", vars(request.headers))
for header in request.headers.items():
print(header)
then remote_user is available via key name X-Remote-User in the header.
remote_user = request.headers.get("X-Remote-User")
print("Remote User: ", remote_user)
This question already has answers here:
How to debug a Flask app
(14 answers)
Comments not working in jinja2
(1 answer)
Closed 4 years ago.
I am trying to use Flask to render an HTML template. I had it working great and now each time I get a 500 Internal Server Error. If I replace the render_template function just a string, things work fine. What am I doing wrong?
init.py :
from flask import Flask, render_template
app = Flask(__name__)
#app.route('/')
def homepage():
return render_template("main.html")
if __name__ == "__main__":
app.run()
main.html in /templates/
<!DOCTYPE html>
<html lang="en">
<p>test</p>
</html>
The template_folder has to be defined where the static files are located.
If the main.html file is in the same folder as the init.py, then include the following code:
import os
project_root = os.path.dirname(__file__)
template_path = os.path.join(project_root, './')
app = Flask(__name__, template_folder=template_path)
Hopefully it works now.
Your sample actually works on my end.
What version of flask are you running?
are you sure that you are accessing the URL at port 5000 (the default) and not an application on port 80?
Are old instances of the server still running, that may be colliding with attempts to re-launch the server?
Trying to use AJAX to POST to my Python script testing.py. Whenever I try the POST, I receive the following error.
POST http://localhost:5000/testing.py 404 (NOT FOUND)
I'm using Flask to serve up my website. Why is this a 404 error, and how do I get localhost to serve my python script?
somewhere you should have a file called app.py,(but you can call it testing.py if you want) inside should be at least:
from flask import Flask, request
app = Flask(__name__)
#app.route('/testing') # you can probably even put testing.py here
def testing():
vars = request.args
return ','.join(map(str,vars))
if __name__ == "__main__":
app.run()
then
python app.py # or testing.py
then you can send your POST to http://localhost:5000/testing
and it will print any posted parameters to the browser