Created
June 5, 2020 13:17
-
-
Save roganjoshp/91938c00ca22a6dea7cd7d76b2b56d45 to your computer and use it in GitHub Desktop.
Confirming that tuple can be used in LIKE query for postgres
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from flask import Flask, render_template_string | |
from flask_sqlalchemy import SQLAlchemy | |
app = Flask('__name__') | |
app.config['SQLALCHEMY_DATABASE_URI'] = 'postgresql+psycopg2://postgres:######@127.0.0.1/so_test' | |
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False | |
app.config['SESSION_TYPE'] = 'sqlalchemy' | |
db = SQLAlchemy() | |
db.init_app(app) | |
class TestTable(db.Model): | |
id = db.Column(db.Integer, primary_key=True) | |
data_1 = db.Column(db.Integer) | |
data_2 = db.Column(db.String) | |
HOME_STR = """ | |
<form method="post" action="{{ url_for('create_data') }}" class="test_form"> | |
<input type="submit" value="Create Data"> | |
</form> | |
<form method="post" action="{{ url_for('query_data') }}" class="test_form"> | |
<input type="submit" value="Query Data"> | |
</form> | |
<div id="res"></div> | |
<script src='https://code.jquery.com/jquery-3.5.1.min.js'></script> | |
<script> | |
$(".test_form").submit(function(e) { | |
e.preventDefault(); | |
var form = $(this); | |
var url = form.attr('action'); | |
$.ajax({ | |
type: "POST", | |
url: url, | |
data: form.serialize(), | |
context: form, | |
success: function(resp) { | |
$("#res").html(resp); | |
} | |
}); | |
}); | |
</script> | |
""" | |
@app.route('/', methods=['GET']) | |
def home(): | |
db.create_all() | |
return render_template_string(HOME_STR) | |
@app.route('/create', methods=['POST']) | |
def create_data(): | |
for x in range(5): | |
if x == 3: | |
entry = TestTable(data_1=x, | |
data_2='hello_test') | |
else: | |
entry = TestTable(data_1=x, | |
data_2=str(x)) | |
db.session.add(entry) | |
db.session.commit() | |
return "Data created" | |
@app.route('/query', methods=['POST']) | |
def query_data(): | |
search = 'hello' | |
data = db.engine.execute("SELECT * FROM test_table WHERE data_2 LIKE %s", | |
('%' + search + '%',)).fetchall() | |
return str(data) | |
if __name__ == '__main__': | |
app.run() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment