im working with Flask and Sqlite3.and i've written a code which inserts 3 value into a sqlite3 database.
from flask import Flask, render_template, g, request, redirect, url_for, flash, session
from functools import wraps
from flask_bootstrap import Bootstrap
from wtforms import Form, StringField, PasswordField, DateTimeField
from wtforms.validators import InputRequired
import os
import sqlite3
from datetime import datetime
app = Flask(__name__)
Bootstrap(app)
app.secret_key = os.urandom(24)
app.config.from_object(__name__)
D_candata = '/var/www/FlaskApp/py/static/database/CANData.db'
D_acc = '/var/www/FlaskApp/py/static/database/acc.db'
D_appo ='/var/www/FlaskApp/py/static/database/appo.db'
class LoginForm(Form):
username = StringField(validators=[InputRequired(message='Username ist noch leer')])
password = PasswordField(validators=[InputRequired(message='Password ist noch leer')])
class DateForm(Form):
bdt = DateTimeField(validators=[InputRequired(message='Bitte eingeben')], format = '%d-%m-%Y %H:%M' )
edt = DateTimeField(validators=[InputRequired(message='Bitte eingeben')], format = '%d-%m-%Y %H:%M' )
def connect_db(db):
return sqlite3.connect(db)
def loggin_required(funct):
#wraps(funct)
def wrap(*args, **kwds):
if 'logged_in' in session:
return funct(*args, **kwds)
else:
flash('log in!!')
return redirect(url_for('login'))
return wrap
#app.route('/')
#loggin_required
def index():
g.db = connect_db(D_candata)
cur = g.db.execute('SELECT * FROM CANData LIMIT 1;')
data = [dict(Timestamp=row[0], BatteryVoltage=row[1], BatteryAmperage=row[2], BatteryLoad=row[3], Range=row[4], Speed=row[5], Mileage=row[6]) for row in cur.fetchall()]
g.db.close()
return render_template ("/html/index.html", data=data)
#app.route('/reservierung/', methods = ["GET","POST"])
#loggin_required
def reservie():
form = DateForm(request.form)
b_date = ""
e_date = ""
if request.method == "POST" and form.validate() :
b_date = form.bdt.data
e_date = form.edt.data
if b_date > e_date :
flash('Bitte den Zeitraum korrigieren ')
else:
account = 'admin'
try:
con = connect_db(D_appo)
cur = con.cursor()
flash('ok1')
cur.execute("INSERT INTO appo_info (account, b_date, e_date) VALUES (?, ?, ?)",(account, b_date, e_date)) #???
flash('ok')
con.commit()
con.close()
except:
flash('500')
con.rollback()
return render_template('/html/reservie.html', form=form)
if __name__ == "__main__":
app.run(debug=True)
i think the problem start with
def reservie():
...
cur.execute("INSERT INTO appo_info (account, b_date, e_date) VALUES (?, ?, ?)",(account, b_date, e_date))
because i've use flash and try to show where it goes wrong.
and it just show ('ok1')and ('500') when i use chrome at computer(server is raspberry).
but it did show ('ok') when i tested it at raspberry. and the datas shows in database.
At raspberry pi I can read and write. But at computer i can only read
Im sure is it not the problem from Authentication. The databases and others is already '777'
i cant use debug mode, because it is not local. so did anyone have an idea?
thx a lot
Related
I am currently struggling to get my program working. What I am doing is connecting my database, which is a MySQL database on the workbench, and connecting it to my python. I am trying to store the user inputs as parameters in the stored procedure in my workbench. So when I hit submit the program will take the user input as parameters using the stored procedure. But I am running into several errors. The recurring one being this specific type of error.
Error Message : TypeError: The view function for 'signIn' did not return a valid response. The function either returned None or ended without a return statement.
Python Imports/Code:
from flask import Flask, app, render_template, url_for, request, redirect
import MySQL.connector, CGI
form = cgi.FieldStorage()
app = Flask(__name__)
#app.route('/')
def home():
return "<a href='/login'> login </a><br> <a href='/sign-up'> sign-up </a>"
#app.route('/sign-up', methods=["POST", "GET"])
def signIn():
condition = 0
mydb = mysql.connector.connect(host='localhost', database='signlogpy', user='root', password='thereaper1999',
port="3306")
cursor = mydb.cursor()
if request.method == "POST":
email = request.form["email"]
password = request.form["password"]
name = request.form["name"]
displayName = request.form["displayName"]
DOB = request.form["dateOfBirth"]
args = [email, password, name, displayName, DOB]
else:
return print("Could not reveice user input")
if condition == 0:
condition = 1
elif condition == 1:
results = cursor.callproc('signInInformation', args)
cursor.execute('select * from signin')
cursor.fetchall()
else:
return render_template("SignUp.html")
signInInformationProc = cursor.callproc('signInInformation', args)
results = cursor.fetchall()
print(results)
if results == True:
print("works")
redirect(url_for('login'))
else:
render_template("SignUp.html")
return redirect(url_for(login))
#app.route('/login')
def login():
return render_template('Login.html')
if __name__ == '__main__':
app.run(debug=True)
Workbench MySql code:
use signlogpy;
DELIMITER $$
create procedure signInInformation
(
in
p_userEmail varchar(45),
p_userPassword varchar(45),
p_name varchar(45),
p_displayName varchar(45),
p_dob date
)
begin
insert into signin (userEmail, userPassword, name, displayName, dob)
values (p_userEmail, p_userPassword, p_name, p_displayName, p_dob);
end $$
DELIMITER ;
Any help would be greatly appreciated. If anybody does reply I do thank you immensely and appreciate your help. Thanks in advance!
It looks like the declaration of args is inside
if request.method == "POST":
which means that args doesn't have any meaning outside and after that if statement. Try putting
args = []
at the beginning of signIn() which will let it be accessible by the whole function.
I am following the CS50 of Harvard and I don't want to use CS50 library that they use for lecture purposes, but I could not figure out how to make this code work. A little help would be greatly appreciated
import sqlite3
from flask import Flask, redirect, render_template, request, session
from flask_session import Session
# Configure app
app = Flask(__name__)
# Connect to database
db = sqlite3.connect("store.db",check_same_thread=False)
c = db.cursor()
# Configure sessions
app.config["SESSION_PERMANENT"] = False
app.config["SESSION_TYPE"] = "filesystem"
Session(app)
#app.route("/")
def index():
books = db.execute("SELECT * FROM books")
list =[dict(id=book[0], title=book[1]) for book in books.fetchall() ]
return render_template("books.html", books=list)
#app.route("/cart", methods=["GET", "POST"])
def cart():
# Ensure cart exists
if "cart" not in session:
session["cart"] = []
# POST
if request.method == "POST":
id = request.form.get("id")
if id:
session["cart"].append(id)
return redirect("/cart")
# GET
books = db.execute("SELECT * FROM books WHERE id IN (?)", [session("cart")])
list =[dict(id=book[0], title=book[1]) for book in books.fetchall()]
return render_template("cart.html", books=list)
The error is at the books=db.execute... line.
Error is :
sqlite3.ProgrammingError: Incorrect number of bindings supplied. The current statement uses 1, and there are 9 supplied
I pressed the cart button 9 times, it is incrementing. Tried other solutions, could not still figure out.
books = db.execute("SELECT * FROM books WHERE id IN (?)", [session("cart")])
should be
query = f"SELECT * FROM books WHERE id IN ({','.join(['?'] * len(session['cart']))})"
books = db.execute(query,session['cart'])))
Python code: (the main_
...
from flask import Flask, render_template, url_for,request,flash,redirect
from formzxc import Amount
from flask_sqlalchemy import SQLAlchemy
app = Flask(__name__)
app.config['SECRET_KEY'] = '8ed085d7c0aefb62c65e9d2154c3f377'
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///testing.db'
app.config['SQLALCHEMY_ECHO'] = True
db = SQLAlchemy(app)
class Category(db.Model):
id = db.Column(db.Integer,primary_key = True)
desc = db.Column(db.String(25),unique = True,nullable =False)
amt = db.Column(db.Integer,nullable =False)
def __repr__(self):
return f"Category('{self.desc}'.'{self.amt}')"
#app.route('/',methods = ['GET','POST']) #need to research more on the methods
#app.route('/main',methods = ['GET','POST'])
def home():
form = Amount() #this is the amount FlaskForm imported
if form.validate_on_submit(): #validation is true
flash(f'Done liao','success') #a message to put; put at homepage or prev page
newpost = Category(desc = Amount.purpose.data,amt =Amount.amount.data ) ##
db.session.add(newpost)
db.session.commit()
return redirect(url_for('home')) #function
else:
flash('Shit!','danger')
return render_template(f'test.html',form = form)
if __name__ == '__main__':
app.run(debug=True)
....
Python code(for formzxc)
from flask_wtf import FlaskForm
from wtforms import StringField, PasswordField, SubmitField, BooleanField,IntegerField
from wtforms.validators import DataRequired, Length, Email, EqualTo
class Amount(FlaskForm):
purpose = StringField('Type:',
validators = [DataRequired(),Length(max =25)])
amount = IntegerField('Amount:',
validators = [DataRequired()])
submit = SubmitField('Submit!')
fix bellow error
newpost = Category(desc = Amount.purpose.data,amt =Amount.amount.data )
change to
newpost = Category(desc = form.purpose.data,amt =form.amount.data )
because ur are passing FlaskForm object to Amount class when creating it Amount class inherited the object form from it.So u have to use that object to get the data.
I'm completely new to flask and web development in general. And what I need is to login to a website using steam id. I'm doing it as it said here, but get the following error:
OperationalError: (sqlite3.OperationalError) no such table: user
It seems to open up steam website correctly but it breaks when I press Log In. So, what's my mistake ? Any help is appreciated.
The code:
from flask import Flask, render_template, redirect, session, json, g
from flask_bootstrap import Bootstrap
from flask.ext.sqlalchemy import SQLAlchemy
from flask.ext.openid import OpenID
import urllib
import re
app = Flask(__name__)
app.secret_key = '123'
Bootstrap(app)
app.config.from_pyfile('settings.cfg')
db = SQLAlchemy(app)
oid = OpenID(app)
class User(db.Model):
id = db.Column(db.Integer, primary_key=True)
steam_id = db.Column(db.String(40))
nickname = db.String(80)
#staticmethod
def get_or_create(steam_id):
rv = User.query.filter_by(steam_id=steam_id).first()
if rv is None:
rv = User()
rv.steam_id = steam_id
db.session.add(rv)
return rv
def get_steam_userinfo(steam_id):
options = {
'key': app.config['STEAM_API_KEY'],
'steamids': steam_id
}
url = 'http://api.steampowered.com/ISteamUser/' \
'GetPlayerSummaries/v0001/?%s' % urllib.urlencode(options)
rv = json.load(urllib.urlopen(url))
return rv['response']['players']['player'][0] or {}
_steam_id_re = re.compile('steamcommunity.com/openid/id/(.*?)$')
#app.route('/login')
#oid.loginhandler
def login():
if g.user is not None:
return redirect(oid.get_next_url())
return oid.try_login('http://steamcommunity.com/openid')
#oid.after_login
def create_or_login(resp):
match = _steam_id_re.search(resp.identity_url)
g.user = User.get_or_create(match.group(1))
steamdata = get_steam_userinfo(g.user.steam_id)
g.user.nickname = steamdata['personaname']
db.session.commit()
session['user_id'] = g.user.id
flash('You are logged in as %s' % g.user.nickname)
return redirect(oid.get_next_url())
#app.before_request
def before_request():
g.user = None
if 'user_id' in session:
g.user = User.query.get(session['user_id'])
#app.route('/')
def homepage():
return render_template('mainpage.html')
#app.route('/logout')
def logout():
session.pop('user_id', None)
return redirect(oid.get_next_url())
if __name__ == '__main__':
app.run(debug=True)
You need to run a db.create_all() before running your app.
This will create all the tables described by your model in the database.
If you are new to flask you can follow the quickstart quide here
Given both FACEBOOK_APP_ID and FACEBOOK_APP_SECRET, what sound I change in the following code (or even on the FB control panel) so as to be able to read email, public_profile and user_friends of a user (me)?
from flask import Flask, redirect, url_for, session, request
from flask_oauth import OAuth
SECRET_KEY = ''
DEBUG = True
FACEBOOK_APP_ID = ''
FACEBOOK_APP_SECRET = ''
app = Flask(__name__)
app.debug = DEBUG
app.secret_key = SECRET_KEY
oauth = OAuth()
facebook = oauth.remote_app('facebook',
base_url='https://graph.facebook.com/',
request_token_url=None,
access_token_url='/oauth/access_token',
authorize_url='https://www.facebook.com/dialog/oauth',
consumer_key=FACEBOOK_APP_ID,
consumer_secret=FACEBOOK_APP_SECRET,
request_token_params={'scope': ["email", "public_profile", "user_friends"]}
)
#app.route('/')
def index():
return redirect(url_for('login'))
#app.route('/login')
def login():
return facebook.authorize(callback=url_for('facebook_authorized',
next=request.args.get('next') or request.referrer or None,
_external=True))
#app.route('/login/authorized')
#facebook.authorized_handler
def facebook_authorized(resp):
if resp is None:
return 'Access denied: reason=%s error=%s' % (
request.args['error_reason'],
request.args['error_description']
)
session['oauth_token'] = (resp['access_token'], '')
me = facebook.get('/me')
return 'type %s, data %s, headers %s, raw_data %s, status %s' % (type(me), str(me.data), str(me.headers), str(me.raw_data), str(me.status))
#facebook.tokengetter
def get_facebook_oauth_token():
return session.get('oauth_token')
if __name__ == '__main__':
app.run()
EDIT:
request_token_params={'scope': 'public_profile,user_friends,email'}
me = facebook.get('/me?fields=id,name,first_name,last_name,age_range,link,gender,locale,timezone,updated_time,verified,friends,email')
If you're using v2.4 of the Graph API, you'll need to specify all the fields you want returned at
me = facebook.get('/me?fields=id,name,gender,email,friends')
etc. It's all in the docs.
https://developers.facebook.com/docs/apps/changelog#v2_4
https://developers.facebook.com/docs/graph-api/using-graph-api/v2.4#fields