# import_local.pyimportsqlite3importpandasaspdconn=sqlite3.connect('db.db')cur=conn.cursor()ifcur.execute('select count(*) from book;').fetchone()[0]==0:df=pd.read_csv(r'books.csv')df.to_sql(name='book',con=conn,if_exists='append',index=False)cur.close()conn.close()
# -*- coding: UTF-8 -*-# application.pyimportosimportrequestsfromflaskimportFlask,flash,jsonify,render_template,request, \
redirect,session,url_forfromjinja2importMarkupfromflask_sessionimportSessionfromsqlalchemyimportcreate_enginefromsqlalchemy.ormimportscoped_session,sessionmakerapp=Flask(__name__,static_folder='static')# Check for environment variableifnotos.getenv("DATABASE_URL"):raiseRuntimeError("DATABASE_URL is not set")# Configure session to use filesystemapp.config["SESSION_PERMANENT"]=Falseapp.config["SESSION_TYPE"]="filesystem"Session(app)# Set up databaseengine=create_engine(os.getenv("DATABASE_URL"))db=scoped_session(sessionmaker(bind=engine))sess=db()@app.teardown_requestdefremove_session(ex=None):db.remove()
# application.py@app.route("/login",methods=['GET','POST'])defsign_in():"""Sign in
"""ifrequest.method=='GET':ifsession.get('act_user')isNone:returnrender_template("login.html",act_user=session.get("act_user"))else:returnrender_template("index.html",act_user=session.get("act_user"))elifrequest.method=='POST':username=request.form.get('username')pwd=request.form.get('password')mbrinfo=sess.execute("""SELECT id, username FROM mbr WHERE username = :username
AND pwd = :pwd;""",{"username":username,"pwd":pwd}).fetchone()ifmbrinfoisNone:flash(Markup("""<i class='fa fa-2x fa-exclamation-circle'></i>
User not exist or wrong password."""),'danger')else:session['act_user']={'id':mbrinfo[0],'username':mbrinfo[1]}returnhome()
# application.py@app.route('/logout',methods=['GET'])defsign_off():session.pop('act_user',None)flash(Markup("""<i class='fa fa-2x fa-check-square-o'></i>
You have logged out."""),'success')returnhome()
# application.py@app.route("/signup",methods=['GET','POST'])defsign_up():"""Sign up
"""ifrequest.method=='GET':returnrender_template("register.html",act_user=None)elifrequest.method=='POST':username=request.form.get('username')pwd=request.form.get('password')repwd=request.form.get('repassword')mbrinfo=sess.execute("""SELECT id, username FROM mbr WHERE username = :username;""",{"username":username}).fetchone()ifmbrinfoisnotNone:flash(Markup("""<i class='fa fa-2x fa-check-square-o'></i>
The username has been registered. Please change one."""),'warning')returnredirect(url_for('sign_up'))else:ifpwd==repwd:sess.execute('INSERT INTO mbr (username, pwd) VALUES (:username, :pwd);',{'username':username,'pwd':pwd})sess.commit()flash(Markup("""<i class='fa fa-2x fa-check-square-o'></i>
You have successfully created a new account. Now sign in."""),'success')returnredirect(url_for("sign_in"))else:flash(Markup("""<i class='fa fa-2x fa-exclamation-circle'></i>
You did not input the same password."""),'danger')returnredirect(url_for('sign_up'))
假如isbn=‘123’,title=‘war’,author=‘rider’,那么["%s LIKE '%%%s%%'" % (x, y) for x, y in (('isbn', isbn), ('title', title), ('author', author)) if y is not None and y != '']的结果就是这么一个列表:
1
["isbn LIKE '%123%'","title LIKE '%war%'","author LIKE '%rider%'"]
# application.pydefsubset_rec(rec,offset=0,per_page=20):returnrec[offset:offset+per_page]@app.route('/index',methods=['GET','POST'])defindex():ifrequest.method=='GET':books=sess.execute('SELECT id, isbn, title, author, year FROM book;').fetchall()elifrequest.method=='POST':# run the queryisbn=request.form.get('isbn')title=request.form.get('title')author=request.form.get('author')qry=["%s LIKE '%%%s%%'"%(x,y)forx,yin(('isbn',isbn),('title',title),('author',author))ifyisnotNoneandy!='']iflen(qry)==0:books=sess.execute('SELECT id, isbn, title, author, year FROM book;').fetchall()else:books=sess.execute('SELECT id, isbn, title, author, year FROM book WHERE '+' AND '.join(qry)+';').fetchall()page,_,offset=get_page_args(page_parameter='page',per_page_parameter='per_page')page_books=subset_rec(books,offset=offset,per_page=20)pagination=Pagination(page=page,total=len(books),bs_version=3,per_page=20)returnrender_template('index.html',act_user=session.get('act_user'),books=page_books,pagination=pagination)
# application.pydefget_gr(isbn,api='review_counts',success_code=200):"""Goodreads API data
return json or None
"""urls={'review_counts':'https://www.goodreads.com/book/review_counts.json'}url=urls[api]res=requests.get(url,params={'key':'yFLoMH1lgWCNlYDs1kWA','isbns':isbn},timeout=10)try:res=requests.get(url,params={'key':'yFLoMH1lgWCNlYDs1kWA','isbns':isbn},timeout=10)exceptrequests.exceptions.ProxyError:res=requests.get(url,params={'key':'yFLoMH1lgWCNlYDs1kWA','isbns':isbn},proxies={'http':os.getenv('http_proxy'),'https':os.getenv('https_proxy')},timeout=10)ifres.status_code==success_code:returnres.json()else:returnNone
# application.py@app.route('/book/<int:book_id>',methods=['GET','POST'])defreview(book_id):"""Book detail
"""book=sess.execute("""SELECT id, title, author, isbn, year FROM book WHERE
id = :book_id""",{"book_id":book_id}).fetchone()gr_data=get_gr(isbn=book[3])ifgr_dataisnotNone:gr_data=gr_data['books'][0]else:gr_data={'work_ratings_count':'','average_rating':''}my_reviews=sess.execute("""SELECT count(*) FROM review WHERE mbr_id = :mbr_id
and book_id = :book_id;""",{'mbr_id':session.get('act_user')['id'],'book_id':book_id}).fetchone()[0]ifengine.name=='sqlite':reviews_qry="""SELECT review.id,
datetime(review.rev_at, 'localtime'),
mbr.username, review.rating, review.review FROM
review LEFT JOIN mbr ON review.mbr_id = mbr.id
WHERE review.book_id = :book_id"""elifengine.name=='postgresql':reviews_qry="""SELECT review.id,
review.rev_at at time zone 'utc' at time zone 'cst',
mbr.username, review.rating, review.review FROM
review LEFT JOIN mbr ON review.mbr_id = mbr.id
WHERE review.book_id = :book_id"""reviews=sess.execute(reviews_qry,{"book_id":book_id}).fetchall()# methodsifrequest.method=='GET':returnrender_template('book.html',act_user=session.get('act_user'),book=book,reviews=reviews,gr_data=gr_data,my_reviews=my_reviews)elifrequest.method=='POST':comment=request.form.get('comment')rating=request.form.get('rating')if(commentisnotNoneandcomment!='')or \
(ratingisnotNoneandrating!=''):sess.execute("""INSERT INTO review (mbr_id, book_id, rating, review)
VALUES (:mbr_id, :book_id, :rating, :review);""",{'mbr_id':session.get('act_user')['id'],'book_id':book_id,'rating':rating,'review':comment})sess.commit()flash(Markup("""<i class='fa fa-2x fa-check-square-o'></i>
You have successfully submitted the comment."""),'success')else:flash(Markup("""<i class='fa fa-2x fa-warning'></i>
You cannot submit empty rating and comments."""),'warning')returnredirect(url_for("review",book_id=book_id))
# application.py@app.route('/api/book',methods=['GET'])defapi():ifsession.get('act_user')isNone:returnrender_template("error.html",act_user=None,err="404 Error",err_info="You have not logged in!")book_isbn=request.args.get('isbn')book=sess.execute("""SELECT id, title, author, isbn, year FROM book WHERE
isbn = :book_isbn""",{"book_isbn":book_isbn}).fetchone()ifbookisNoneorlen(book)==0:returnrender_template("error.html",act_user=session.get('act_user'),err="404 Error",err_info="Book with ISBN = %s not found!"%book_isbn)else:gr_data=get_gr(isbn=book_isbn)ifgr_dataisnotNone:gr_data=gr_data['books'][0]else:gr_data={'work_ratings_count':'','average_rating':''}rslt={'result':True,'book':{'title':book[1],'author':book[2],'year':book[4],'isbn':book[3],'review_count':gr_data['work_ratings_count'],'average_score':gr_data['average_rating']}}returnjsonify(rslt)