Measuring open the road to one hundred thirty-five: implement the login authentication

 

 

New table, the user information is inserted

create table UserInfo(
UserName TEXT,
Emali TEXT,
Password
);

insert into UserInfo values ('Admin', '[email protected]', '123456');
insert into UserInfo values ('Jerry', '[email protected]', '654321');

select * from UserInfo;

 

login.html

 

 

Look at the results

 

 

Login logic

 

 

Error Log

 

 

 

 

Log correct

 

 

 

 

view

Coding #:. 8 UTF- 
Import the sqlite3
from datetime datetime Import
from the Flask Flask Import, Request, the render_template, the redirect, the url_for, G

App = the Flask (__ name__)

DATABASE R & lt = '\ DB \ feedbach.db.'

'================ ================== package sql helper ============================ = '


DEF make_dicts (cursor, Row):
"" "the cursor Tuple acquired list into database dict" ""
return dict ((in cursor.description [IDX] [0], value) for IDX, value in the enumerate ( Row))


DEF get_db ():
"" "Get (CV database links)
G: Flask built-in variables: G = LocalProxy (partial (_lookup_app_object," G "))
" ""
DB = getattr (G, '_database', none)
IF not db:
db = G._database = sqlite3.connect(DATABASE)
= make_dicts db.row_factory
return DB


DEF execute_sql (sql, the params = ()):
"" "sql statement execution does not return the data results INSERT, Update, Delete" ""
. get_db C = () Cursor ()
c.execute (sql , params)
c.connection.commit ()


DEF query_sql (SQL, params = (), one = False):
"" "one = False data query returned more than one time" ""
c = get_db () the Cursor ().
= c.execute Result (SQL, the params) .fetchall ()
c.close ()
return (Result [0] None the else Result IF) IF the else Result One


@ # app.teardown_appcontext destroyed during the current execution context app
def close_connection (exeption ):
"" "Close database" ""
DB = getattr (G, '_database',None)
if db is not None:
db.close()


'========================================================================'


@app.route("/")
def index():
return render_template('base.html')


@app.route('/login/', methods=['GET', 'POST'])
def login():
""" 登录 """
if request.method == 'POST':
username = request.form.get('username')
password = request.form.get('password')
sql = 'select count(*) as [Count] from UserInfo where username = ? and password = ?'
result = query_sql(sql, (username, password), True)
if int(result.get('Count')) > 0:
return redirect(url_for('list')) return render_template ( 'login.html')
Return 'user name or password is incorrect'



# 模板继承
@app.route("/feedback/")
def feedback():
return render_template('post.html')


@app.route("/post_feedback/", methods=["POST"])
def post_feedback():
""" 提交视图 """
if request.method == 'POST': # 如果是post请求就获取表单值
subject = request.form.get('subject', None)
categoryid = request.form.get('category', 1)
username = request.form.get('username')
email = request.form.get('email')
body = request.form.get('body')
release_time = str(datetime.now())
state = 0
print(subject, categoryid, username, email, body, state, release_time)
conn = sqlite3.connect(DATABASE)
conn.cursor = c ()
# prevent sql injection with? Instead of the value of
SQL = "INSERT INTO Feedback (Subjeck, CategoryID, UserName, Email, Body, State, ReleaseTime) values (?,?,?,?,?,?,?)"
C.execute (SQL, (Subject, CategoryID , username, Email, body, State, release_time))
conn.commit ()
conn.Close ()
# to prevent Caton caused by repeated submission after submission Jump to fill the page
return redirect (url_for ( 'Feedback'))


@ app.route ( "/ List /")
DEF List ():
"" "show all issues" ""
SQL = "the SELECT the ROWID, * Feedback from the Order by the ROWID DESC"
# = query_sql the FEEDBACKS (SQL)
# Print (the FEEDBACKS)
key = request.args.get ( 'key', '')
sql = 'select f.ROWID,f.*,c.CategoryName from feedback f INNER JOIN category c on c.ROWID = f.CategoryID where f.Subjeck like ? order by f.ROWID'
feedbacks = query_sql(sql, (f'%{key}%',))
return render_template('feedback-list.html', items=feedbacks)


@app.route('/del/<id>/')
def delete_feedback(id=0):
""" 删除问题 ,前端传id"""
conn = sqlite3.connect(DATABASE)
c = conn.cursor()
sql = "delete from feedback where ROWID = ?"
c.execute(sql, (id,))
conn.commit()
conn.close()
return redirect(url_for('list'))


# 编辑功能
@app.route("/edit/<id>/")
def edit(id=None): # bound to get drop-down list
"" "Back to edit the front-end HTML pass over the above mentioned id" ""

= SQL "the SELECT the ROWID, the CategoryName from category"
the Categories = query_sql (SQL)
# id get current information, and bind to form a form to prepare modify
SQL = "the SELECT the ROWID, the WHERE * Feedback from the ROWID =?"
curren_feedback = query_sql (SQL, (ID,), True)
# return STR (curren_feedback) # view sequence data check out, rendering html to facilitate sorting
return the render_template ( 'edit.html', the Categories = the Categories, Item = curren_feedback)


@ app.route ( "/ save_edit /", Methods = [ 'the POST'])
DEF save_edit ():
"" "save edit" ""
IF request.method == 'the POST':
ID = request.form.get ( 'ROWID', None )
Reply = request.form.get ( 'Reply')
State = request.form.get. 1 IF ( 'State',0) == 'on' else 0
sql = 'update feedback set Reply=?, State=? where rowid=?'
conn = sqlite3.connect(DATABASE)
c = conn.cursor()
c.execute(sql, (reply, state, id))
conn.commit()
conn.close()
return redirect(url_for('list'))


if __name__ == '__main__':
app.run(
debug=True
)

 

html

{% extends 'base.html' %}

{% block main_content %}

<!--登录界面-->
<div class="row">
<div class="col-md-6 col-md-offset-3">
<div class="panel panel-default">
<div class="panel-heading">
<h4>登录</h4>
</div>
<div class="panel-body">
<form action="#" class="form-horizontal" method="post">
<div class="form-group">
<label for="username">用户名:</label>
<input type="text" class="form-control" name="username" id="username">
</div>
<div class="form-group">
<label for="password">密码:</label>
<input type="text" class="form-control" name="password" id="password">
</div>
<div class="form-group">
<input type="submit" class="btn btn-primary" value="登录">
</div>
</form>
</div>
<div class="footer">
&copy;版权所有
</div>
</div>
</div>
</div>








{% endblock %}

 

Guess you like

Origin www.cnblogs.com/zhongyehai/p/11461904.html