So I asked a few days ago how to run a program from a browser on a different server and someone told me about Flask and I tought I should`ve gave it a try
And that s what I did: I wrote the program
from flask import Flask, render_template, request
app = Flask(__name__)
#app.route('/addnew', methods=['GET', 'POST'])
def send():
if request.method == 'POST':
name = request.form['name']
return render_template('see.html', name=name)
return render_template('index.html')
if __name__ == "__main__":
app.run(host='0.0.0.0')
I made up the most basic form in html so i can at least try the code
<!DOCTYPE html>
<html>
<head>
<title>Pls work</title>
</head>
<body>
<form method="POST" action="/addnew">
First name:<br>
<input type="text" name="name"><br>
</form>
</body>
</html>
I run it from the console (activating venv and all that), but when i go to 'link/addnew' it tells me the page does not exist
In the putty console tells me it runs on 0.0.0.0
I tryed to put the host on 127.0.0.1:5000 but it doesnt also doesnt work
I am really a noobie in this so I try to copy and understand as much as possible, but i dont understand where the problem stands, please help
On Ubuntu use this command to allow traffic to your server on the port 5000:
iptables -I INPUT -p tcp --dport 5000 -j ACCEPT
If that does not work please share your debug logs.
Related
I have a simple flask app that works locally but gets 500'd when testing in IIS.
Edit: I was wrong, initially thought was pandas read issue but the issue is actually coming from subprocess that tries to get the user's IP address:
from flask import Flask, request
import subprocess
app = Flask(__name__)
html = '''
<h1>Test</h1>
<h2>Report Generator</h2>
<p>
<form action="/submitted" method="post">
<label for="reports">Choose a Report:</label>
<select id="reports" name="reports">
<option value="user_test">User Test</option>
</select>
<input type="submit">
</form>
'''
#app.route("/")
def index():
return html
#app.route("/submitted", methods=['POST'])
def show():
select = request.form.get("reports")
if select == 'user_test':
name = 'XXXXXXXX.dcm.com'
result = subprocess.check_output(['nslookup', name])
else:
result = "Not Available"
return result
if __name__ == "__main__":
app.run()
This code runs fine when tested locally. If I remove the part where it runs subprocess to get user IP that works fine on IIS. The trouble is when I try to include the part that runs subprocess.check_output(['nslookup',name]) when running on IIS, which leads to 500 internal server error.
Here is picture of error:
Thanks for the help!
1.You need "import pandas as pd" at top.
2.The error doesn't happen when reading csv, but on the return process.
"df.values" cannot be returned at this situation because "df" is Dataframe type. Instead, you can use:
df = pd.read_csv("uuids.csv")
return df.to_html(header="true", table_id="table")
or
return df.to_csv()
or
return render_template("xxx.html"......)
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')
Take for example a simple php form such as ,
<html>
<body>
<form action="welcome.php" method="post">
Name: <input type="text" name="name"><br>
<input type="submit">
</form>
</body>
</html>
Is it possible to POST whatever value that a user input into a python script namely app.py which has a variable named as "name" eg:-
name = #This Variable needs to be populated with the value the user inputs to the form
print(name + " "+ "is my name")
Apologies about the vague question but I am quite new to programming and would be great if someone can at least point me in the right direction if this is possible. Another doubt here is on clicking the submit button how can I trigger the python script.
Your form is already sending a POST request, so it makes more sense to post it directly to your Python application, if it's running on a web server. If for whatever reason you want to pass an HTTP request on to another web application, you can use PHP CURL extension. Take a look at this PHP + curl, HTTP POST sample code? and this https://www.php.net/manual/en/curl.examples-basic.php
If the Python app is not running on a web server, you can call it as a command line script from your PHP application. It would look something like this:
<?php
// welcome.php
$name = $_POST['name'];
$pythonScriptCall = 'python3 app.py name=' . $name;
$pythonScriptResult = '';
exec($pythonScriptCall, $pythonScriptResult);
echo $pythonScriptResult;
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)
I am writing a home workout program that gives me audio cues for when to switch exercises, which exercises to do, etc... I have this working on my laptop using a small python program to play some short pre-recorded audio files (aiff format) at specified intervals.
However, I'd like to be able to run this program from my iPhone. I attempted to do this by setting up a Flask server on my computer. I can get the program to run via a web browser on the same machine hosting the server, but when I use a different computer or my iPhone, the audio still plays on the host computer's speakers, not the client as desired. The computer hosting the Flask server is running OS X 10.11.6. Here is a basic version of the program:
Flask Python:
app = Flask(__name__)
#app.route('/')
def index():
return render_template('rockrings_stackoverflow.html')
#app.route('/click', methods=['POST'])
def start_workout():
return workout.workout()
if __name__ == '__main__':
app.run(host='0.0.0.0',debug=True)
workout.py:
def workout():
for minute in range(10):
audio_file = homedir + '/audio_files/easy_workout_minute%i.aiff' % minute
print audio_file
os.system('afplay %s' % audio_file)
index.html:
<!DOCTYPE html>
<html>
<body>
<h1>Welcome to the Hangboard Webtool! </h1>
Click the button below to start the easy workout
<br/><br/>
<form action="/click" method="post">
<button type="submit" value="Easy workout">
</form>
</body>
</html>
What is a proper implementation (if there is one) with Flask?