I am trying to deploy my flask app so that it is available on any computers in my LAN. However, when I execute it I get the following error in the apache2 error.log file :
The architecture of my app is the following:
This is for __init__.py (python3) :
from flask import Flask, redirect, url_for, render_template,request
app = Flask('__name__')
#app.route("/", methods=["POST", "GET"])
def home():
if request.method == "POST":
return render_template("index.html")
else:
return render_template("index2.html")
if __name__ == "__main__":
app.run()
And my code index.html is :
<!DOCTYPE html>
<html>
<head></head>
<body>
<h1>Home Page</h1>
<form action="#" method="post">
<input type="submit" name="submit">
</form>
</body>
</html>
For index2.html it is the same code as index.html only that the tag h1 has a different content.
When I executed this in locally (http://127.0.0.1:5000/) it was working fine.
I am following this tutorial : https://www.youtube.com/watch?v=YFBRVJPhDGY
Any idea on what I might be doing wrong?
Instead of
app = Flask('__name__')
do
app = Flask(__name__)
Flask uses the package/module name to locate the templates folder.
Double check your deployment structure on the server. It's possible that your templates folder is in the wrong location. Like how you have it structured locally, the templates folder should be under your project root folder.
Related
Attempting to upload a document through Dropbox's API through a Submit button on Flask application. The HTML loads on localhost, but whenever I upload the document and hit Sumbit, there is a 404 error and the document does not post to the Dropbox API. Any ideas on where I'm going wrong?
Python
from flask import Flask, render_template, request
import dropbox
# Function Definition
def uploader(token, file):
target = '/temp'
targetFile = target + 'test.docx'
connection = dropbox.Dropbox(token)
meta = connection.files_upload(file, targetFile, mode=dropbox.files.WriteMode("overwrite"))
# Flask App
app = Flask(__name__)
#app.route('/', methods=['POST', 'GET'])
def upload_document():
if request.method == "POST":
uploader(token, request.files['file'])
return render_template('index.html')
if __name__ == "__main__":
app.run()
HTML
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<form method = "post" action = "/home" enctype = "multipart/form-data">
<p>
<input type="file" name="file" autocomplete="off" required>
</p>
<p>
<input type="submit" value="Submit">
</p>
</form>
</body>
</html>
It looks like the issue stemmed from the script not reading the file when being passed through the function via the Dropbox connection. When using this, add file.read() within the connection.
# Function Definition
def uploader(token, file):
target = '/temp'
targetFile = target + 'test.docx'
connection = dropbox.Dropbox(token)
meta = connection.files_upload(file.read(), targetFile, mode=dropbox.files.WriteMode("overwrite"))
I've been following multiple Flask tutorials (but mostly this one) on creating a web app that I can use to read an image into a FastAi model. At some point, I was even able to get the images to upload into a folder, but I could never get them to display on the webpage itself no matter what I tried to do (refactor the function, move the folder to 'static', explicitly declare paths, etc.). I assume I'm probably missing something incredibly basic but I don't know enough about Flask and how web apps work to know what that is.
Edit: I keep getting 400 Bad Request pages every time I attempt to upload an image through the "index.html" page and the image doesn't appear in the folder when I inspect it with Windows Explorer.
file structure:
main.py
app
--> __init__.py
--> routes.py
main.py:
from app import app
main.py:
from flask import Flask
app = Flask(__name__)
from app import routes
routes.py:
from app import app
import os
from fastai.vision.widgets import *
from flask import Flask, render_template, request
#app.route('/', methods=['GET','POST'])
def index():
return render_template('index.html')
def get_predictions(img_path):
global learner_inf
learner_inf = load_learner('app/static/model/export.pkl')
return learn_inf.predict(img_path)
#app.route('/predict', methods=['GET','POST'])
def predict():
if request.method == 'POST':
file = request.files['file']
filename = file.filename
file_path = os.path.join('app/static/uploads', filename)
file.save(file_path)
result = get_predictions(file_path)
return render_template('predict.html', result = str(result), user_image = file_path)
index.html
<!doctype html>
<html>
<head>
<title>Grocery Classifier</title>
</head>
<body>
<h1>Grocery Classifier</h1>
<form method="POST" action="/predict" enctype="multipart/form-data">
<p><input type="file" name="file /"></p>
<p><input type="submit" value="Submit"></p>
</form>
</body>
</html>
predict.html
<!doctype html>
<html>
<head>
<title>Grocery Classifier</title>
</head>
<body>
<h1>Grocery Classifier</h1>
<img src="{{ user_image }}" alt="Selected Image" class="img-thumbnail">
<h2>{{ result }}</h2>
</body>
</html>
When referencing static items such as images and files, use the static folder to hold them.
app = Flask(__name__, static_folder="static")
After that, include it in CSS/HTML. This is not the direct application of inserting images in your situation, but it serves as a good example.
background-image: url("bg.gif");
The url to reference the image can be literally anything, just be sure to remember it for later reference. The reference "bg.gif" seen in the CSS automatically does GET request to "yoururl.com/bg.gif" to obtain the image.
Now link that url to the site path.
#app.route('/bg.gif', methods=['GET'])
def bghome():
return send_from_directory("static", "bg.gif")
The route MUST be correct and exact and the file MUST exist. If you use a kwarg to get the image url, be sure to keep that url consistent to what you define in your flask backend pathing.
I want to build a simple web application based on Flask and Python for displaying and editing a text file in my directory path that I have created before on the web page. I have written the codes and can be run, but the results are not as expected. Everyone who can give me solutions is really appreciated.
from flask import Flask, request, render_template, redirect, url_for
from pathlib import Path
from os import listdir
app = Flask(__name__)
#app.route('/')
def my_form():
return render_template('index.html')
#app.route('/', methods=['GET,POST'])
def my_form_post():
path=Path('/users/Devie Andriyani/EditFlask/days.txt') # set the path to your file here
if not path.exists():path.touch()
input_days = request.form['text_box']
if request.method == 'POST':
with open('/users/Devie Andriyani/EditFlask/days.txt', 'w') as f:
f.write(request.form.get('text_box',None))
return redirect(url_for('my_form_post'))
if __name__ == '__main__':
app.debug = True
app.run()
<!DOCTYPE html>
<head>
<title>Hello</title>
</head>
<body>
<form action="" method="POST">
<input name="text_box" value={{days}}>
<input type="submit">
</form>
</body>
</html>
And here's the result. I don't get the result as I expected. It should edit a text file
from flask import Flask, request, render_template
from os import listdir
app = Flask(__name__)
#app.route('/')
def my_form():
return render_template('index.html')
#app.route('/', methods=['GET,POST'])
def my_form_post():
input_days = ''
if request.method == 'POST':
input_days = request.form['text_box']
with open('/users/Devie Andriyani/EditFlask/days.txt', 'w') as f:
f.write(str(input_days))
return render_template('index.html', days=input_days)
if __name__ == '__main__':
app.debug = True
app.run()
<!DOCTYPE html>
<head>
<title>Hello</title>
</head>
<body>
<form action="" method="POST">
<input name="text_box" value="{{ days }}">
<input type="submit">
</form>
</body>
</html>
I don't understand clearly what is your question but I have found some Erorrs in your code:
This is wrong
#app.route('/', methods=['GET,POST'])
you should write like this #app.route('/', methods=['GET','POST'])
also you didn't specify any element to display the days so then why you didn't see the output .
you should give some element like <p>{{days}}</p>
I am getting an Internal Server error, and I'm not sure what the issue is. index.html is in the same directory as the Python file.
from flask import Flask, render_template
app = Flask(__name__)
#app.route('/')
def hello_world():
author = "Rick"
name = "1st flask app"
return render_template('index.html', author=author, name=name)
if __name__ == "__main__":
app.run()
<!DOCTYPE html>
<html>
<head>
<title>{{ author }}'s app</title>
</head>
<body>
<h2>Hello {{ name }}!</h2>
<p>Please show up on the page</p>
</body>
</html>
Why am I getting a 500 error rather than my rendered template?
Create a directory called templates and put index.html in it.
You can get more information about errors by running in debug mode:
app.run(debug=True)
When you create your app
app = Flask(__name__)
you can also include the template_folder parameter to specify the folder that contains your templates. If you don't, render_template will look for them in the default folder called templates. If such folder doesn´t exist, or if your template can't be found inside it, you will get an internal server error 500 rather than your rendered template.
from flask import *
from twilio import twiml
from twilio.rest import TwilioRestClient
from flask import render_template
import os
#Pull in configuration from system environment variables
TWILIO_ACCOUNT_SID = os.environ.get('Axxxxxx')
TWILIO_AUTH_TOKEN = os.environ.get('Sxxxxxxxxx')
TWILIO_NUMBER = os.environ.get('xxxxxxx')
# create an authenticated client that can make requests to Twilio for your
# account.
#client = TwilioRestClient(account='Axxxxx', token'sxxxxxxxx')
#create a flask web app
app = Flask(__name__)
client = TwilioRestClient(account='Axxxxx', token='Sxxxxx')
#app.route('/')
def homepage():
return render_template('index.html')
#Handling a post request to send text messages.
#app.route('/message', methods=['POST', 'GET'])
def message():
# Send a text message to the number provided
if request.method == 'POST':
message = client.sms.messages.create(to=request.form['Phone_number'],
from_=TWILIO_NUMBER,
body=request.form['body'])
return render_template('message.html')
if __name__ == '__main__':
# Note that in production, you would want to disable debugging
app.run(debug=True)
I am using flask. When i input the number and the text message it gives me this error
Method Not Allowed
The method is not allowed for the requested URL.
You're posting to the wrong endpoint. Your form should look like this:
<!DOCTYPE html>
<html lang="en">
<head>
<title>Send an SMS</title>
</head>
<body>
<form action="/message" method="POST">
Cell phone number: <input name="phone_number" type="text" />
Text in here: <input name="body" type="text" />
<button type="submit">Send Text</button>
</form>
</script>
</body>
</html>
(Above, action was changed from / to /message.)
Note: if this is a template run through flask.render_template, you should change
<form action="/message" method="POST">
to
<form action="{{ url_for('message') }}" method="POST">
This is a more sustainable way to use urls in flask, and it will reduce your overhead if you ever need to change the value.