This question already has answers here:
Flask raises TemplateNotFound error even though template file exists
(13 answers)
Closed 18 days ago.
python file pass value to html with flask
error
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.`
import mysql.connector
# from mysql import connector
import webbrowser
import time
import pymysql
from flask import Flask,render_template
app = Flask(__name__)
mydb = mysql.connector.connect(
host="196.168.101.141",
user="root",
password="password123",
database="cool_db",
auth_plugin='mysql_native_password'
)
mycursor = mydb.cursor()
mycursor.execute("SELECT P_TITLE,P_DESC FROM webpage WHERE P_ID = 'en_1-01'")
myresult = mycursor.fetchall()
print(myresult) # does get the result I want
# but below function not send "myresult" to html successfully
#app.route('/')
def index():
return render_template("index.html", myresult = myresult)
if __name__ == "__main__":
app.run()
index.html
<!DOCTYPE html>
<html>
<body>
<p> this is {{myresult}}</p>
</body>
</html>
I already read through the discussion how to pass data to html page using flask? and also other tutorial but not see how to solve, therefore I need a hand thanks
error:jinja2.exceptions.TemplateNotFound: index.html
You are getting this error because there is no index.html file present in the templates folder. In flask, you need to create a folder named templates in the same location where your app.py file is located. Inside that templates folder, you need to create the index.html file.
So, your directory structure should look like:
|- firstflaskapp.py
|- templates/
| |- index.html
I am sure this will resolve your error.
The full directory structure followed used in flask is:
|- app.py
|- templates/
| |- index.html
| |- login.html
| |- ...
|- static/
| |- css/
| | |- main.css
| |- images/
| | |- logo.png
| |- ...
|- requirements.txt
app.py is the main Flask application file
templates/ directory contains HTML templates for the application
static/ directory contains static files like CSS, JS, images, etc.
requirements.txt is a text file containing the list of python libraries by the application.
import mysql.connector
import webbrowser
import time
import pymysql
from flask import Flask,render_template, request
app = Flask(__name__)
mydb = mysql.connector.connect(
host="196.168.101.141",
user="root",
password="password123",
database="cool_db",
auth_plugin='mysql_native_password'
)
mycursor = mydb.cursor()
# send result to index.html
#app.route('/')
def index():
mycursor.execute("SELECT P_TITLE,P_PRICE FROM webpage WHERE P_ID = '%s'",(request.args.get("ProductID"),))
myresult = mycursor.fetchall()
return render_template("Myshop.html", myresult = myresult)
if __name__ == "__main__":
app.run(debug=True)
you dont enter the Myshop.html in the url if your using flask. You go to the / route and it will render the Myshop.html.
If you want to pass data from the get request like in your example
http://192.168.0.206:8080/?ProductID=001
You can access that data via the request
#app.route('/')
def index():
# if key doesn't exist, returns None
myresult = request.args.get('ProductID')
return render_template("Myshop.html", myresult = myresult)
This tutorial explains it in more detail: https://www.digitalocean.com/community/tutorials/processing-incoming-request-data-in-flask
Related
I am trying to structure a flask API application to separate routes and create tests for each of these routes in the same application. Ultimately, my objective is to have a gitlab runner file automate this eventually. This is currently what the structure looks like:
my-flask-application:
- venv:
- gitlab-ci.yml
- requirements.txt
- app:
|- app.py
|- routes
|- home.py
|- square.py
|- ...
- test:
|- test_home.py
|- test_square.py
|- ...
Here are the files:
(1) app.py
#app.py
from flask import Flask
from app.routes.home import home_bp
from app.routes.square import square_bp
app = Flask(__name__)
API_PREFIX = "/api/v1"
app.register_blueprint(home_bp, url_prefix=API_PREFIX)
app.register_blueprint(square_bp, url_prefix=API_PREFIX)
if __name__ == '__main__':
app.run(debug=True)
(2) home.py
#home.py
from flask import Blueprint, jsonify
home_bp = Blueprint('home', __name__)
#home_bp.route('/home')
def home():
return jsonify({'message': 'Welcome to the home page!'}), 200
(3) test_home.py
import unittest
from flask import Flask, jsonify
# Need help importing the app or routes
class TestCase(unittest.TestCase):
test_app = Flask(app)
# Need help with an example of a unit test
if __name__ == '__main__':
unittest.main()
Ultimately, I need help (1) figuring out how to import the application into the test file, and (2) learn how to structure the test files effectively so that I can ultimately run it automatically using a runner file (this can come later).
Thanks!
I am trying to delete two files from my flask application. But it does not work
html
<button href="/remove/wellness" id="remove" class="btn btn-success mr-2">Remove</button>
Here is my delete function:
#app.route('/remove/<file_id>')
def remove(file_id):
filename_jsonl = f"{file_id}.jsonl"
filename_csv = f"{file_id}.csv"
return os.remove(filename_jsonl, filename_csv)
Any and all help is appreciated. Thanks!
I solved the issue with the following directory structure:
.
├── app.py
├── templates
│ └── delete_files.html
├── wellness.csv
└── wellness.jsonl
As you can see I have two files called wellness.csv and wellness.jsonl in the directory where I have placed my app.py file. The name wellness will be passed from the template and these two files will be deleted from the directory.
app.py:
import os
from flask import Flask, render_template
app = Flask(__name__)
#app.route('/')
def search():
return render_template('delete_files.html')
#app.route('/remove/<file_id>')
def remove(file_id):
filename_jsonl = f"{file_id}.jsonl"
filename_csv = f"{file_id}.csv"
try:
os.remove(filename_jsonl)
os.remove(filename_csv)
return "Files are deleted successfully"
except Exception as e:
return f"Error in deleting files: {e}"
delete_files.html:
<html>
<head>
<title>Delete files using button click in Flask</title>
</head>
<body>
Remove
</body>
</html>
Output:
After clicking the delete button I see the message Files are deleted successfully.
The folder structure after deletion of the files:
.
├── app.py
└── templates
└── delete_files.html
Update
If you want to redirect to root url after successful deletion you can use redirect method like below:
import os
from flask import Flask, render_template, redirect, url_for
app = Flask(__name__)
#app.route('/')
def search():
return render_template('delete_files.html')
#app.route('/remove/<file_id>')
def remove(file_id):
filename_jsonl = f"{file_id}.jsonl"
filename_csv = f"{file_id}.csv"
try:
os.remove(filename_jsonl)
os.remove(filename_csv)
return redirect(url_for('search'))
except Exception as e:
return f"Error in deleting files: {e}"
I have been trying to move from using sqlite to sqlalchemy for a project. This has caused me to move many files and I appear to ruined my app routing and I can not explain how. See below for code and file structure. In short the only route I can now get back and working is the Swagger UI I have built and that probably only works because flask does not handle its route to my knowledge. Any help would be much appreciated. Keep in mind I am new to flask so if this is a very stupid issue forgive me, other answers on stackoverflow had eventually led to me creating the create_app function and while that does get the flask site running I imagine the #app.route's are not being called at all.
My file structure is like so:
Project
|--- project.py (Runs the project)
|--- Config.py (Holds the class config)
|--- web
| |--- __init__.py (See below)
| |--- routes.py (Hols the routes)
| |--- api (Swagger ui and other scripts)
| | |--- __init__.py
| | |--- swagger.yaml
My project.py:
from web import create_app
import db
import os
app = create_app()
if __name__ == "__main__":
app.run()
else:
if not os.path.exists("./Project.db"):
print(" * Building Database")
db.build_db()
print(" * Database built")
print(" * Database exists")
My web/init.py:
from flask_sqlalchemy import SQLAlchemy
from flask_migrate import Migrate
from config import Config
import connexion
db = SQLAlchemy()
def create_app():
app = connexion.FlaskApp(__name__, specification_dir="./api")
app.add_api("swagger.yaml")
app = app.app
app.config.from_object(Config)
db.init_app(app)
return app
#migrate = Migrate(app, db)
from web import routes, models
My web/routes.py: (Snipped for brevity)
#! python3
from web import create_app, routes
from web.forms import LoginForm
import web.api
import flask
app = create_app()
#############
# Home URLs #
#############
#app.route('/login', methods=['GET', 'POST'])
def login():
form = LoginForm()
if form.validate_on_submit():
return flask.redirect(flask.url_for('home'))
return flask.render_template('login.html', title='Sign In', form=form)
#app.route("/web")
def home():
devices = web.api.devices.get()
for device in devices:
device.update({"model": web.api.models.get_devices_model(device["alias"])["model"]})
return flask.render_template("home.html", devices=devices)
I Have a Flask webapp im working on. Im using ZODB with Flask-ZODB extension.
I have a small script to initialize some default objects on my database, such as users and the "indexes" that ill be using to store some data the users will submit.
structure looks like:
myproject/
|- myproject/
| |- __init__.py
| |- models.py
| |- views.py
| |- database/
| |- static/
| |- templates/
|
|- run.py
|- setup.py
the setup script looks like this:
[setup.py]
from myproject.models import Usuario
from ZODB.DB import DB
from ZODB.FileStorage import FileStorage
from flask.ext.zodb import BTree
import transaction
# add admin users
superU = Usuario("somemail#gmail.com", "xxx")
admin = Usuario("admin#gmail.com", "yyy")
#create indexes
storage = FileStorage('myproject/database/db.fs')
conn = DB(storage)
db = conn.open().root()
for idx in ['usuarios', 'proyectos', 'informes', 'actividades', 'objetivos', 'usuarios']:
if not idx in db.keys():
db[idx] = BTree()
db['usuarios'][superU.id] = superU
db['usuarios'][admin.id] = admin
for usuario in db['usuarios'].values():
print "Usuario '", usuario.email, "' added..."
transaction.commit();
conn.close();
And the models file
The init file
[_init_.py]
from flask import Flask
from models import Usuario
# configuration
DEBUG = True
SECRET_KEY = 'development key'
USERNAME = 'admin'
PASSWORD = 'default'
app = Flask(__name__)
app.config.from_object(__name__)
from basedatos import Coleccion, Catalogo
coleccion = Coleccion(app)
catalogo = Catalogo()
import myproject.views
[models.py]
from flask import current_app as app
from flask.ext.zodb import Object, List, Dict
from flask_login import UserMixin
from itsdangerous import URLSafeSerializer
from hashlib import sha256
class Usuario(UserMixin):
"""
Usuarios de la aplicacion
"""
def __init__(self, email, password):
self.email = email
self.passwordHash = sha256(password).hexdigest()
self.id = email
def get_auth_token(self):
return URLSafeSerializer(app.secret_key, salt='id salt').dumps(self.id+self.passwordHash)
So the thing is that when I want to run my setup, i get this import error:
Traceback (most recent call last): File "setup.py", line 3, in
from myproject.models import Usuario File "S:\Fuentes\workspace\Python\flaskapps\myproject-app\myproject__init__.py",
line 1, in
from flask import Flask ImportError: No module named flask
When i run the app everything works just fine, i only have this issue when running the script from the console. (im on Windows)
Im closing this one, it was a virtualenv issue. It happens that if you exceute only setup.py or c:\Python27\python.exe setup.py it doesnt look in the sitePackages folder of the active venv. Solution is to call it just > python.exe setup.py
I implementing simple site with couple of applications (like blog, code, account, etc). I decided to split one python file to apps due to large size. I do not using blueprints or something else except basic functionality of Flask - I'd like to keep it as simple as it possible.
Unfortunately, flask still looking for templates in the
/site
|-> main.py
from flask import Flask
app = Flask(__name__)
app.config.from_pyfile('config.py')
# Import all views
from errors.views import * # Errors hasn't its specific prefix
from blog.views import *
from account.views import *
from mysite.views import *
if __name__ == "__main__":
app.run(debug=True)
|-> templates
...................
|->blog
|-> template
|-> _layout.html
|-> index.html
|-> post.html
|-> __init__.py
from main import app
import blog.views
|-> views
from blog import app
from flask import render_template
#app.route("/blog/", defaults={'post_id': None})
#app.route("/blog/<int:post_id>")
def blog_view(post_id):
if post_id:
return "Someday beautiful post will be here with id=%s" % post_id
else:
return "Someday beautiful blog will be here"
#app.route("/blog/tags/")
def tags_view():
pass
..........................
Lets say you have 2 blueprints blog and account. You can divide up your individual apps(blueprints) of blog and account as follows:
myproject/
__init__.py
templates/
base.html
404.html
blog/
template.html
index.html
post.html
account/
index.html
account1.html
blog/
__init__.py
views.py
account/
__init__.py
views.py
In your blog/views.py, you can render templates like:
#blog.route('/')
def blog_index():
return render_template('blog/index.html')
#account.route('/')
def account_index():
return render_template('account/index.html')
..and so on
Add template_folder='templates' to each app Blueprint declaration:
account = Blueprint('account', __name__, template_folder='templates')
Details: https://flask.palletsprojects.com/en/2.0.x/blueprints/#templates