This question already has answers here:
Strange SQLAlchemy error message: TypeError: 'dict' object does not support indexing
(8 answers)
Closed 4 years ago.
I'm trying to make a web app that has a search button that searches a postgres table.
I'm getting the error:
TypeError: 'dict' object does not support indexing
My code is as follows:
app.py
from flask import Flask, render_template, request
from sqlalchemy import create_engine
app = Flask(__name__)
db_string = "postgres://xi:x#x:5432/xx"
db = create_engine(db_string)
#app.route('/', methods=['GET', 'POST'])
def homepage():
if request.method == 'POST':
jn = request.form['jobnumber']
result_set = db.execute("SELECT cost FROM public.options where optionno = (f'%jn%')").fetchall()
return render_template('main.html', test=result_set, jn=jn)
else:
return render_template('main.html')
if __name__ == "__main__":
app.run(debug=True)
and my HTML is:
main.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>xxx</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link href="{{ url_for('static', filename='css/bootstrap.min.css') }}" rel="stylesheet">
<link rel="shortcut icon" href="{{ url_for('static', filename='favicon.ico') }}">
</head>
<body>
<p>xxx</p>
<form method="POST" id="jobnumber">
<input name="jobnumber" type="textbox" placeholder="jobnumber">
</form>
<table>
<td>
{{test}}
</td>
</table>
</body>
</html>
Any help will be hugely appreciated.
SQLAlchemy has a text function for converting string to sqlalchemy text object which appears to correctly escape the SQL for you.
You need to import
`from sqlalchemy import text'
And you need to remove f from the query and also change = to like or ilike
i.e.
res = db.execute(text("SELECT cost FROM public.options where optionno like ('%jn%')")).fetchall()
Related
I'm testing a little code to work, but I can't get it to work, this is the flask/python part:
#from weasyprint import HTML
import flask
import os
##
##html = HTML('text.html')
##html.write_pdf('invoice.pdf')
app = flask.Flask(__name__)
#app.route('/')
def hello_world():
today = datetime.today().strftime("%B %-d, %Y")
navigation = [1,2,3]
return flask.render_template('text.html',navigation = navigation,fecha = today)
if __name__ == '__main__':
port = int(os.environ.get("PORT", 5000))
app.run(host='0.0.0.0', port=port)
this is the test html, that im trying to work on:
<!doctype html>
<html>
<head>
welcome {{fecha}}
</head>
<body>
{% for item in navigation %}
this is a test, and hello {{item}}world!!!
{% endfor %}
</body>
</html>
but the output is this :
welcome {{fecha}} {% for item in navigation %}this is a test, and hello {{item}}world!!!
{% endfor %}""" (brs a let out intetionally)
this is the current folder structure:
what am I missing to make this work as intended?
from flask import Flask, render_template
app = Flask(__name__)
#app.route('/')
def index():
fruits = ['๐', '๐', '๐', '๐', '๐', '๐', '๐', '๐ฅญ', '๐', '๐', '๐', '๐']
return render_template('index.html', fruits = fruits)
if __name__ == '__main__':
app.run(debug = True)
Your .html files should be in templates folder otherwise it will not work. (CASE SENSITIVE)
<!DOCTYPE html>
<html dir="ltr" lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Flask App</title>
</head>
<body>
{% for fruit in fruits %}
<li>{{ fruit }}</li>
{% endfor %}
</body>
</html>
Folder Structure
Output Image
How can you use flask to make the text of your website blue? I only know how to display text on your website. My code :
from flask import Flask
app = Flask(__name__)
#app.route('/')
def hello_world():
return '''Hello world'''
Despite the negative feedback from other user, this is not that bad of a question, besides apart of #go2nirvana no one answered your question.
Note
Despite this is more a Front-end question related to CSS or Javascript and not HTML (yes you can embed CSS inline within HTML but is not recommended) what you asked can be achieved in Flask in many ways.
Example 1 -Hard coding, not recommended buy you can do it-
from flask import Flask
app = Flask(__name__)
#app.route('/')
def hello_world():
my_html = '''
<body style="background-color: #e1eb34;">
<h1 style="color: #002aff;">Hello World</h1>
</body>
'''
return my_html
if __name__ == '__main__':
app.run(debug=True)
or
from flask import Flask
app = Flask(__name__)
#app.route('/')
def hello_world():
return '''
<body style="background-color: #e1eb34;">
<h1 style="color: #002aff;">Hello World</h1>
</body>
'''
if __name__ == '__main__':
Example 2 -Using Jinja2 DOCS##
from flask import Flask, render_template
app = Flask(__name__)
#app.route('/')
def hello_world():
color = {
'blue': '002aff',
'yellow': 'e1eb34',
'green': '28fc03',
'red': 'fc1703',
'purple': 'b503fc'}
return render_template('index.html', color=color)
if __name__ == '__main__':
app.run(debug=True)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body style="background-color: #{{color['yellow']}};">
{% for hue in color.values() if hue != 'e1eb34'%}
<h1 style="color: #{{hue}};">Hello World</h1>
{% endfor %}
<h1></h1>
</body>
</html>
Example 3 -Adding request, session, redirect, url_for and more fun
from flask import Flask, render_template, redirect, url_for, request, session
import random
app = Flask(__name__)
app.config['SECRET_KEY'] = 'dev'
color = {
'blue': '002aff',
'yellow': 'e1eb34',
'green': '28fc03',
'red': 'fc1703',
'purple': 'b503fc',
'orange': 'FF9733 ',
'black' : 'FFFFFF',
'light-blue': '0AE5E3',
'pink': 'FF95AE',
'blue-green' : '95FFCA'}
#app.route('/', methods=['GET', 'POST'])
def index():
error = None
if 'color' not in session:
session['color'] = None
session['background'] = None
if request.method == 'POST':
choice = request.form['color'].lower()
if choice not in color:
error = 'Color not in list'
return render_template('index.html', color=session['color'], background=session['background'], error=error )
else:
session['color'] = color.get(choice)
session['background'] = random.choice(list(color.values()))
return redirect(url_for('index'))
return render_template('index.html', color=session['color'], background=session['background'], error=error )
if __name__ == '__main__':
app.run(debug=True)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
{% if color%}
<style>
body {
color: #{{color}};
background-color: #{{background}};
}
</style>
{% endif %}
</head>
<body>
<h1>Hello World</h1>
{% if error%}
{{error}}
{% endif %}
<form action="{{url_for('index')}}" method="POST">
<label for="color">Choose a color</label>
<input type="text" name="color">
<input type="submit" value="PRESSS" name="i_talk-with_flask">
</form>
</body>
</html>
Variation with a Macro DOC
{% macro color_mix(color)%}
{% if color%}
<style>
body {color: #{{color}};}
body {background-color: #{{background_}};}
</style>
{% endif %}
{% endmacro%}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
{{color_mix(color)}}
</head>
<body>
<h1>Hello World</h1>
{% if error%}
{{error}}
{% endif %}
<form action="{{url_for('index')}}" method="POST">
<label for="color">Choose a color</label>
<input type="text" name="color">
<input type="submit" value="PRESSS" name="i_talk-with_flask">
</form>
</body>
</html>
Honestly this is only the tip of the iceberg of the option you can have. Now is this reccomended ? Probably not, because this it should be handle with CSS or then handle it with JavaScript.
However there may be planty of instances where you may want to use it from a Flask App, one of there are:
Testing Purposes.
Debugging.
Something related to a Database.
Fun
That's a CSS question, not Flask.
return '<span style="color: #00ccff;">Hello world</span>'
Answer to Question 2
I'm assuming that you mean taking an image from the web. Yes you can, but this is definitely a CSS/HTML related question. However following the same principle of my previous answer:
Picures taken from Unsplash
from flask import Flask, render_template
app = Flask(__name__)
#app.route('/')
def index():
my_pic = 'https://images.unsplash.com/photo-1469980098053-382eb10ba017?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=1050&q=80'
return render_template('index.html', my_pic=my_pic)
if __name__ == '__main__':
app.run(debug=True)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body style="background-image: url(https://images.unsplash.com/photo-1600187734183-707cf1c0fd5a?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=1304&q=80);"
>
< <div>
<h1 style="color: white;">Picture from HTML</h1>
<img src="https://images.unsplash.com/photo-1600298881979-9b0c50d7abdf?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=400&q=60" alt="opps">
</div>
<div style="color: white;">
<h1>Picture from Flask</h1>
<img src="{{my_pic}}" alt="oops">
</div>
</body>
</html>
I suggest you to learn it from HTML and CSS related topic rather than Flask (first learn some CSS and HTML basic):
CSS
HTML
That been said I have a more interesting a USEFUL answer that however requires basic knowledge of the use of a Database, I assume you are a beginner and you may have not yet this knowledge but soon or later you will. So even if you dont understand completely the following keep it in mind and come back later.
I prepared a mini app that using flask, flask_sqlalchemy (with sqlite3), html and Bootstrap.
This app does the following and will teach you these principle:
.1 Upload a picture into a Database.
.2 How to download a picture from the Database.
.3 Render the picture from the Database into the WebBroser.
FULL CODE FROM GITHUB
Some Code from this mini app
Initiate the database, configs and Picture table for the databse
In class FileContent(db.Model):
data = file.read() It saves in database the Binary version of thefile
-render_file = render_picture(data). It saves the decode version, so that you can you see it for render it in the webpages.
# Built-in Imports
import os
from datetime import datetime
from base64 import b64encode
import base64
from io import BytesIO #Converts data from Database into bytes
# Flask
from flask import Flask, render_template, request, flash, redirect, url_for, send_file # Converst bytes into a file for downloads
# FLask SQLAlchemy, Database
from flask_sqlalchemy import SQLAlchemy
basedir = 'sqlite:///' + os.path.join(os.path.abspath(os.path.dirname(__file__)), 'data.sqlite')
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = basedir
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
app.config['SECRET_KEY'] = 'dev'
db = SQLAlchemy(app)
# Picture table. By default the table name is filecontent
class FileContent(db.Model):
"""
The first time the app runs you need to create the table. In Python
terminal import db, Then run db.create_all()
"""
""" ___tablename__ = 'yourchoice' """ # You can override the default table name
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(128), nullable=False)
data = db.Column(db.LargeBinary, nullable=False) #Actual data, needed for Download
rendered_data = db.Column(db.Text, nullable=False)#Data to render the pic in browser
text = db.Column(db.Text)
location = db.Column(db.String(64))
pic_date = db.Column(db.DateTime, nullable=False, default=datetime.utcnow)
def __repr__(self):
return f'Pic Name: {self.name} Data: {self.data} text: {self.text} created on: {self.pic_date} location: {self.location}'
Upload route, here is where the picture its sent to databse and processed with correct data
So here is what is going on in the app route:
def render_picture(data) --> Takes the bites raw version of the pic and return the decode version, so that it can be used to be display on the web.
data = file.read() : This is the raw data.This can be used for downloading the pic from database
render_file: decoded file so you can retrieve it and the render in the web page
#Render the pics, this Function converts the data from
request.files['inputFile'] so that in can be displayed
def render_picture(data):
render_pic = base64.b64encode(data).decode('ascii')
return render_pic
#app.route('/upload', methods=['POST'])
def upload():
file = request.files['inputFile']
data = file.read()
render_file = render_picture(data)
text = request.form['text']
location = request.form['location']
newFile = FileContent(name=file.filename, data=data,
rendered_data=render_file, text=text, location=location)
db.session.add(newFile)
db.session.commit()
flash(f'Pic {newFile.name} uploaded Text: {newFile.text} Location:
{newFile.location}')
return render_template('upload.html')
INDEX Route
# Index It routes to index.html where the upload forms is
#app.route('/index', methods=['GET', 'POST'])
#app.route('/')
def index():
return render_template('index.html')
INDEX HTML with the Form
<form method="POST" action="/upload" enctype="multipart/form-data">
<!-- File Upload-->
<div class="form-group">
<label for="inputFile">File input</label>
<input class="form-control-file" type="file" name="inputFile">
</div>
<!-- Location -->
<div class="form-group">
<label for="location">Location</label>
<input class="form-control" type="text" name="location">
</div>
<!-- Text -->
<div class="form-group">
<label for="text">Write Text</label>
<textarea class="form-control" name="text" id="text" rows="5" placeholder="Add a Description"></textarea>
</div>
<!-- Submit -->
<button type="submit" class="btn btn-primary">Submit</button>
</form>
I work with the Python flask, HTML, and local JSON file to display the JSON data from a local JSON file in the HTML. Once the flask reads a local JSON file, it is sent to index.html with jsonify. After then, using that data I want to display the information.
I can the JSON data in the flask side, but have struggled with displaying it in the HTML. Could you let me know what I missed?
flask code
import os
from flask import Flask, render_template, abort, url_for, json, jsonify
import json
import html
app = Flask(__name__)
# read file
with open('./data/file.json', 'r') as myfile:
data = myfile.read()
#app.route("/")
def index():
return render_template('index.html', title="page", jsonfile=jsonify(data))
app.run(host='localhost', debug=True)
index.html
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1" />
<meta charset="UTF-8" />
<title>House</title>
<link
rel="stylesheet"
href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css"
integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7"
crossorigin="anonymous"
/>
<script>
var jsonfile ={{jsonfile}};
</script>
</head>
<body>
<div class="container">
{{jsonfile}}
</div>
</body>
</html>
Your issue is the use of the jsonify method. If you read the documentation of jsonify it returns a Response object and not a string. So you will get something like this for jsonify(data)
<Response 2347 bytes [200 OK]>
You could remove jsonify and use json.dumps instead, as follows:
#app.route("/")
def index():
return render_template('index.html', title="page", jsonfile=json.dumps(data))
This works for me.
What Rahul P is correct and the reason you are getting unexpected results is because you are using jsonify when you should be using json.dumps(data).
If you want you want to use the json inside of the script tag can I suggest making the following changes?
app.py
import os
from flask import Flask, render_template, abort, url_for
import json
import html
app = Flask(__name__)
# read file
with open('./data/file.json', 'r') as myfile:
data = myfile.read()
#app.route("/")
def index():
return render_template('index.html', title="page", jsonfile=json.dumps(data))
if __name__ == '__main__':
app.run(host='localhost', debug=True)
index.html
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1" />
<meta charset="UTF-8" />
<title>House</title>
<link
rel="stylesheet"
href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css"
integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7"
crossorigin="anonymous"
/>
</head>
<body>
<div class="container"></div>
<script>
const jsonfile = JSON.parse({{jsonfile|tojson}});
console.log(jsonfile);
document.querySelector(".container").innerHTML = JSON.stringify(jsonfile, null, 2);
</script>
</body>
</html>
from flask import Flask, render_template, url_for, jsonify, request
from translate import Translator
en_ge = Translator("geo")
ge_en = Translator("en","geo")
app = Flask("Translator")
#app.route("/send",methods=["GET","POST"])
def send():
if request.method == "POST":
word = request.form["word"]
return render_template("translator.html",word=en_ge.translate(f"{word}"))
return render_template("index.html")
app.run()
I am trying to make translator with flask, but unfortunately I start learning it 10 minutes ago :). I am just trying to win a bet and make it as fast as I can. Googled but I keep receiving server internal error. How to fix it, please help
<!DOCTYPE html>
<html lang="en">
<head>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk" crossorigin="anonymous">
<meta charset="UTF-8">
<title>Translator</title>
</head>
<body>
<h1>แจแแแงแแแแ แกแแขแงแแ</h1>
<form method="POST" action="/send">
<div class="form-group">
<input type="text" name="word">
</div>
<input class="btn btn-primary" type="submit" value="Translate">
</form>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk" crossorigin="anonymous">
<meta charset="UTF-8">
<title>Index</title>
</head>
<body>
<h1>{{word}}</h1>
</body>
</html>
I think u miss template_folder param in Flask object creation, something like
app = Flask("Translator", template_folder="full_path_fo_a_folder_where_your_html_is_stored")
This question already has answers here:
Link to Flask static files with url_for
(2 answers)
Closed 6 years ago.
I reduced the code for this to, I think, minimum while trying to get it to work:
The python:
#!/usr/bin/env python
from functools import wraps
from flask import Flask, render_template, session, request, redirect, url_for
from flask_socketio import SocketIO, emit, join_room, leave_room, \
close_room, rooms, disconnect
async_mode = None
app = Flask(__name__)
app.config['SECRET_KEY'] = 'secret!'
socketio = SocketIO(app, async_mode=async_mode)
#app.route('/')
def index():
return render_template('index_test.html')
if __name__ == '__main__':
socketio.run(app, debug=True)
The html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<img src="{{ url_for('index') }}bulboff.gif"/>
<p>"{{ url_for('index') }}" <p>
</body>
</html>
The image is in the static folder.
And it gives this error:
"GET /bulboff.gif HTTP/1.1" 404
when the page is accessed.
I've tried several things like setting the Flask default paths, without the url_for, etc, but, still no image.
What am I missing?
According to the flask document:
To generate URLs for static files, use the special static endpoint
name:
url_for('static', filename='style.css')
The file has to be stored on the filesystem as static/style.css.
In your case, use <img src="{{ url_for('static', filename='bulboff.gif') }}">
If You put image in the static folder, You should use something like this:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<img src="{{ url_for('index') }}static/bulboff.gif"/>
<p>"{{ url_for('index') }}" <p>
</body>
</html>
Alternatively, You could change application's code and add following:
#app.route('/bulboff.gif')
def bulboff():
return open('static/bulboff.gif').read()
<img src="{{url_for('static', filename='bulboff.gif')}}" />
Try that. Your filename could be a path from the static folder. So like if you have filename = \some\path\img.png it will look for the img in static\some\ath\img