Measuring open the road to one hundred thirty-four: implements the specified search function

 

Implements the specified search function

And a common list view function, modify sql

@app.route("/list/")
def list():
""" 展示所有问题 """
sql = "select ROWID,* from feedback order by ROWID DESC"
# feedbacks = query_sql(sql)
# print(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)

 

 

feedback-list.html, before rendering the same logic, a new panel

 

Search look

 

When unconditional search, the default display all content

 

 

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("/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')
STR = release_time (DateTime.Now ())
State = 0
Print (Subject, CategoryID, username, In Email, body, State, release_time)
Conn = sqlite3.connect (DATABASE)
C = conn.cursor ()
# 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 = "select ROWID,* from feedback order by ROWID DESC"
# feedbacks = query_sql(sql)
# print(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()
the redirect return (the url_for ( 'List'))


# editing
@ app.route ( "/ Edit / <ID> /")
DEF Edit (ID = None):
"" "The front end of the edit return pass over id html" ""
# get the drop-down list bound
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 = "select rowid, * from the ROWID = the WHERE Feedback? "
curren_feedback = query_sql (SQL, (the above mentioned id,), True)
# return str (curren_feedback) # View data sequence to check out, easy html rendering ordering
return render_template ( 'edit.html', categories = categories, = curren_feedback Item)


@ app.route ( "/ save_edit /", Methods = [ 'the POST'])
DEF save_edit ():
"" "Save the edited "" "
IF request.method == 'POST':
id = request.form.get('rowid', None)
reply = request.form.get('reply')
state = 1 if request.form.get('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="panel panel-default">
<div class="panel-heading">
<form action="#" class="form-inline">
<input type="text" class="form-control" name="key" id="key">
<input type="submit" class="btn btn-default" value="点击搜索">
</form>
</div>
<!--把之前的表格移到panel-body里面-->
<div class="panel-body">
<table class="table table-hover">
<tr>
<th>ID</th>
<th>主题</th>
<th> Category </ th>
<th> user </ th>
<th> mailbox </ th>
<th> processing status </ th>
<th> Submitted </ th>
<th> operation </ th>
</ TR>
{%}% for items in Item
<TR>
<TD> loop.index {{}} </ TD> <-! ID traversal function jinja provided template ->
<TD> {{Item. Subjeck}} </ td> < -! jinja dictionary feature values supplied template ->
<TD> {{item.get ( 'the CategoryID', 0)}} </ TD> <-! comes Python dictionary function value ->
<TD> {{Item [ 'UserName']}} </ TD> <-! Python comes dictionary function value ->
<td>{{ item['Email'] }}</td>
<td><span class="label label-{{ 'danger' if item['State'] ==0 else 'success' }}">{{ "未处理" if item['State'] ==0 else "已处理" }}</span></td>
<td>{{ item['ReleaseTime'] }}</td>
<td>
<a href="#" class="btn btn-success">查看</a>
<a href="{{ url_for('edit', id=item['rowid']) }}" class="btn btn-default">编辑</a>
<a href="{{ url_for('delete_feedback', id=item['rowid']) }}" class="btn btn-danger">删除</a>
</td>
</tr>
{% endfor %}
</table>
</div>
</div>
</div>

{% endblock %}

 

Guess you like

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