I just copied an application from my local dev env to prod env, and my data is not loading for my flask app instead its showing no blog posts right now...
I've verified the following:
db user has permission to table.
mysql is running
verified query again (works fine)
tried messing with MYSQL_DATABASE_HOST set to localhost and xx.xxx.xxx.xxx to no avail.
verified my import (from flask_mysqldb import MySQL is working fine for mysql) - it is
app.py:
from flask_mysqldb import MySQL
app = Flask(__name__)
app.secret_key = 'mysecret'
# mail server config
app.config['MAIL_SERVER'] = 'mailserver.net'
app.config['MAIL_PORT'] = 465
app.config['MAIL_USE_SSL'] = True
app.config['MAIL_USERNAME'] = 'contact#mysite.com'
app.config['MAIL_PASSWORD'] = 'mypass'
# mysql config
app.config['MYSQL_HOST'] = 'localhost'
app.config['MYSQL_PORT'] = '3306'
app.config['MYSQL_DB'] = 'mydb'
app.config['MYSQL_USER'] = 'myusr'
app.config['MYSQL_PASSWORD'] = 'mypass'
mysql = MySQL()
mysql.init_app(app)
c = mysql.connect().cursor()
#app.route('/', methods=('GET', 'POST'))
def email():
form = EmailForm()
c.execute("SELECT post_title, post_name, YEAR(post_date) as YEAR, MONTH(post_date) as MONTH FROM mydb.wp_posts WHERE post_status='publish' ORDER BY RAND() LIMIT 3")
blogposts = c.fetchall()
print(blogposts)
if request.method == 'POST':
if form.validate() == False:
return 'Please fill in all fields <p>Try Again</p>'
else:
msg = Message("Message from your visitor",
sender='contact#mysite.com',
recipients=['contact#mysite.com'])
msg.body = """
From: %s
""" % (form.email.data)
mail.send(msg)
return render_template('email_submit_thankyou.html')
elif request.method == 'GET':
return render_template('index.html', form=form, blogposts=blogposts)
if __name__ == '__main__':
app.run()
templates/index.html contains:
<ul>
{% for blogpost in blogposts %}
<li>{{blogpost[0]}}</li>
{% else %}
<li>no blog posts right now...</li>
{% endfor %}
<div class="clearL"> </div>
</ul>
I found a "slow" query in /var/log/mysql/mysql-slow.log:
# Time: 170101 16:34:32
# User#Host: myuser[myuser] # localhost [127.0.0.1]
# Query_time: 0.004649 Lock_time: 0.001712 Rows_sent: 3 Rows_examined: 53
SET timestamp=1483306472;
SELECT
post_title, post_name, YEAR(post_date) as YEAR, MONTH(post_date) as MONTH
FROM mydb.wp_posts WHERE post_status='publish' ORDER BY RAND() LIMIT 3;
Thus, What is going wrong here?
Related
I want to add into a sqlalchemy database an image where a user uploads one. I tried to do it with this StackOverFlow [post].(Serve image stored in SQLAlchemy LargeBinary column)
Here is the flask code:
from flask import Flask,render_template,request
from flask_sqlalchemy import SQLAlchemy
from base64 import b64encode
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///users1.db'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
db = SQLAlchemy(app)
class Images(db.Model):
id = db.Column(db.Integer,primary_key=True)
name = db.Column(db.String(200))
img = db.Column(db.LargeBinary)
db.create_all()
mylist = []
#app.route('/',methods=['POST','GET'])
def home():
if request.method == 'POST':
img1 = request.files['ab']
imager = Images(name='abc',img=img1)
db.session.add(imager)
db.session.commit()
return render_template('other.html')
#app.route('/allimg',methods=['POST','GET'])
def home1():
mylist1 = Images.query.filter_by(name='abc').all()
event = Images.query.get_or_404(id)
image = b64encode(event.img)
return render_template('new.html',posts=image)
if __name__ == '__main__':
app.run(debug=True)
Other.html
<form action='' method='post' enctype="multipart/form-data">
<button><input type='file' name='ab' id='file-input' multiple></button>
</form>
New.html
<html>
<body>
{%for i in posts%}
<img src="data:;base64,{{ logo }}"/>
{%endfor%}
</body>
</html>
When I go to allimg (The page that I show all images) I get
sqlalchemy.exc.InterfaceError
sqlalchemy.exc.InterfaceError: (sqlite3.InterfaceError) Error binding parameter 0 - probably unsupported type.
[SQL: SELECT images.id AS images_id, images.name AS images_name, images.img AS images_img
FROM images
WHERE images.id = ?]
[parameters: (<built-in function id>,)]
(Background on this error at: https://sqlalche.me/e/14/rvf5)
Please answer.
Thanks.
Serve image stored in SQLAlchemy LargeBinary
column
#app.route('/event/<int:id>/logo')
def event_logo(id):
event = Event.query.get_or_404(id)
image = b64encode(event.logo)
return render_template('event.html', event=event, logo=image)
id in this context is comming in as an int parameter
your passing in id as (<built-in function id>,)
from here https://docs.python.org/3/library/functions.html#id
I am new in build python api. I want to get the data depend on date.
https://programminghistorian.org/en/lessons/creating-apis-with-python-and-flask#what-is-an-api
I am following this link to code my api but I don't know what can I do in execute.
This is my python code:
# -*- coding: utf-8 -*-
from flask import Flask, render_template, request
from flask_mysqldb import MySQL
app = Flask(__name__)
app.config["DEBUG"] = True
app.config['MYSQL_HOST'] = 'localhost'
app.config['MYSQL_USER'] = 'root'
app.config['MYSQL_PASSWORD'] = 'root'
app.config['MYSQL_DB'] = 'MyDB'
app.config['MYSQL_charset'] ='utf8'
mysql = MySQL(app)
#app.route('/',methods = ['GET','POST'])
def index():
if request.method == "POST":
details = request.form
firstday = details['firstday']
lastday = details['lastday']
cur = mysql.connection.cursor()
cur.execute("select * from transaction join transaction_item on transaction.id = transaction_item.transaction_id join customer on customer.id = transaction.customer_id where transaction_datetime <= lastday and transaction_datetime >= firstday VALUES (%s, %s)", (firstday, lastday))
mysql.connection.commit()
cur.close()
return 'success'
return render_template('index.html')
if __name__ == '__main__':
app.run()
This is my HTML code:
<HTML>
<BODY bgcolor="cyan">
<form method="POST" action="">
<center>
<H1>Enter your details </H1> <br>
first_transaction_datetime <input type = "text" name= "firstday" /> <br>
last_transaction_datetime <input type = "text" name= "lastday" /> <br>
<input type = "submit">
</center>
</form>
</BODY>
</HTML>
When you are sending requests to a back-end it does not fill out the form an easy way to do it would be to add the query values in the URL
http://127.0.0.1:5000/?firstName=<firstName>&lastName=<lastName>
then your python code would look something like this.
#app.route('/',methods = ['GET','POST'])
def index():
firstName = request.args.get('firstName')
lastName = request.args.get('lastName')
if request.method == "POST":
# Do stuff here
I am getting started with Flask and trying to create a simple database web application.
It renders 2 html-templates:
show_all.html which shows the data of a database table
new.html which is a form to insert data in to the table
The show_all.html renders correctly. When I click on the submit-button on the new.html I get the following error message:
TypeError: __init__() takes 1 positional argument but 2 were given
app.py
from flask import Flask, request, flash, url_for, redirect, render_template
from flask_sqlalchemy import SQLAlchemy
import psycopg2
DB_URL = 'postgresql+psycopg2://{user}:{pw}#{url}/{db}'.format(user='*******',pw='******',url='******',db='*****')
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = DB_URL
db = SQLAlchemy(app)
class test (db.Model):
__table_args__ = {"schema":"SaubannerDB"}
id1 = db.Column('id1', db.Integer, primary_key=True)
name1 = db.Column(db.String(10))
def __init__(self, name1, id1):
self.name1 = name1
self.id1 = id1
#app.route('/')
def show_all():
return render_template ('show_all.html', tests=test.query.all())
#app.route('/new', methods=['GET','POST'])
def new():
if request.method == 'POST':
if not request.form['name1'] or not request.form['id1']:
flash ('Please enter all fields')
else:
name1 = test(request.form['name1'])
id1 = test(request.form['id1'])
entry = (name1,id1)
db.session.add(entry)
db.session.commit()
return render_template('new.html')
return render_template('new.html')
app.run(host = '0.0.0.0', port = 5050)
app.debug = True`
The new.html file looks like this:
<!DOCTYPE html>
<html>
<body>
<form method="post" action="/new">
<label for="name1"/label><br>
<input type="text" name="name1" placeholder="name"><br>
<label for="id1"/label><br>
<input type="text" name="id1" placeholder="id"><br>
<input type="submit" value="Submit"><br>
</form>
</body>
</html>`
Can anyone help?
Found it out. The following Code works, note the changes for the variable "entry":
from flask import Flask, request, flash, url_for, redirect, render_template
from flask_sqlalchemy import SQLAlchemy
import psycopg2
DB_URL = 'postgresql+psycopg2://{user}:{pw}#{url}/{db}'.format(user='*******',pw='******',url='******',db='*****')
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = DB_URL
db = SQLAlchemy(app)
class test (db.Model):
__table_args__ = {"schema":"SaubannerDB"}
id1 = db.Column('id1', db.Integer, primary_key=True)
name1 = db.Column(db.String(10))
def __init__(self, name1, id1):
self.name1 = name1
self.id1 = id1
#app.route('/')
def show_all():
return render_template ('show_all.html', tests=test.query.all())
#app.route('/new', methods=['GET','POST'])
def new():
if request.method == 'POST':
if not request.form['name1'] or not request.form['id1']:
flash ('Please enter all fields')
else:
entry = test(request.form['id1'],
request.form['name1'])
db.session.add(entry)
db.session.commit()
return render_template('new.html')
return render_template('new.html')
app.run(host = '0.0.0.0', port = 5050)
app.debug = True
If you look here it seems that the init argument is only in the pre-release version:
https://github.com/teracyhq/flask-classful/releases
If that is the case, they shouldn't have the init_argument in the documentation. It's unprofessional.
im trying to do a blog post simple app in witch you can write and than edit or delete a post.
I got so far that i can show post but i can not edit them
i did a /edit.html page on witch i would like to have a single blog post and than edit it. The problem is that the post does not appear
app.py
from flask import Flask, render_template, request
from flask_mysqldb import MySQL
import yaml
from flask_bootstrap import Bootstrap
app=Flask(__name__)
bootstrap = Bootstrap(app)
db = yaml.load(open('db.yaml'))
app.config['MYSQL_HOST'] = db['mysql_host']
app.config['MYSQL_USER'] = db['mysql_user']
app.config['MYSQL_PASSWORD'] = db['mysql_password']
app.config['MYSQL_DB'] = db['mysql_db']
mysql = MySQL(app)
#app.route('/', methods=['GET','POST'])
def index():
if request.method == 'POST':
form = request.form
user_name = form['user_name']
besedilo = form['besedilo']
cur = mysql.connection.cursor()
cur.execute("INSERT INTO post(user_name, besedilo) VALUES(%s, %s)", (user_name, besedilo))
mysql.connection.commit()
return render_template('index.html')
#app.route('/post/')
def post():
cur = mysql.connection.cursor()
result_value = cur.execute("SELECT * FROM post")
if result_value > 0:
posts = cur.fetchall()
return render_template('post.html',posts = posts)
#app.route('/edit/<int:id>/', methods=['GET','POST'])
def edit(id):
cur = mysql.connection.cursor()
result_value = cur.execute("SELECT * FROM post WHERE post_id = {}".format(id))
if result_value > 0:
post = cur.fetchone()
return render_template('edit.html', post = post)
## here i would like to single out one entry and show it on
#app.route('/delete/')
def delete():
return render_template('delete.html')
if __name__ == '__main__':
app.run(debug=True)
edit.html
{% extends 'base.html' %}
{% block sub_content %}
<h1>{{post['user_name']}}</h1>
<h1>{{post['besedilo']}}</h1>
{% if posts %}
{% for post in posts %}
<h3> {{edit['title']}}</h3>
{%endfor%}
{% endblock %}
this should show single entry
You may need to pass a properly prepared sql query not dynamic.
Try modifying your view like:
#app.route('/edit/<int:id>/', methods=['GET','POST'])
def edit(id):
cur = mysql.connection.cursor()
query = "SELECT * FROM post WHERE post_id = {}".format(id)
result_value = cur.execute(query)
if result_value > 0:
post = cur.fetchone()
return render_template('edit.html', post = post)
Alternatively;
result_value = cur.execute("SELECT * FROM post WHERE post_id = %s", (id,))
How can I iterate over the results returned by session.query from a database and print them in a flask template?
I have the following code where I am able to successfully iterate over the results returned from database and print employees name outside of my flask app.
I am just not able to figure out as how to use the following code and print out the employees name in a flask template:
def getEmployees():
engine = create_engine('mssql+pyodbc://<server name>/<DB name>?driver=SQL+Server+Native+Client+11.0')
Base = declarative_base(engine)
class Bookmarks(Base):
__tablename__ = 'table name'
Employee = Column(String(50))
__table_args__ = {'autoload':True}
def loadSession():
metadata = Base.metadata
Session = sessionmaker(bind=engine)
session = Session()
return session
if __name__ == "__main__":
session = loadSession()
results = Bookmarks.query.filter_by(Manager='Bob')
Route:
#app.route('/employeesName', methods=['GET')
def employeesName():
if request.method == 'GET':
return render_template('getEmployees.html')
Template (getEmployees.html):
<h2>Results</h2>
{% for employees in results %}
{{ employees.Employee }}
{% endfor %}
How can I print employees name filtered by Manager = 'Bob' in the flask template?
Thank you so much!
figured this out.
I was supposed to add function name while rendering the template:
#app.route('/employeesName', methods=['GET')
def employeesName():
if request.method == 'GET':
return render_template('getEmployees.html', results=getEmployees())