Flask挺好
很久没写东西了,寒假比较低效,几乎没写代码。只在慕课网上刷完了linux系列课程,现在用linux熟了很多以及看了大部分《鸟叔-linux服务器架设》那本书,虽然对于写代码并没有什么卵用,但是真的感觉对于网络逻辑传输的硬件软件都有了个很爽的认识。还有又刷了次廖大神的python教程发现比以前多了很多内容。近几天在看一本叫《Data Structures and Algorithms with Python》的书,争取的是每天上午看一章,觉得写的挺好的,刚看到第四章,感觉对于python的理解又深入了一些,准备等看完了再写的总结。
记得刚开始学python时看别人说flask用来入门最好,买了本《Flask Web开发:基于Python的Web应用开发实战》,当时硬是看不懂啊,各种什么蓝图什么的直接就来了。
于是前两天看了下flask,花了半天看了其入门教程,直接动手花了一天写了个简易博客试试其post,get,连接mysql与分页。且连接mysql与分页都是自己写的代码没用模块。瞬间觉得flask用起来真是太爽了,相比django傻乎乎的引入写好的模块感觉flaskpythonnic多了。我觉得既然现在公司框架基本都自己写,所以其实没有必要看那些写好的模块嘛,要什么就自己写,除非是以后工作要用再去了解那些。
效果就是下面那样,前端写的不太好,在不同浏览器中最下面有可能有点移位。
代码目录:
其中仅纪录下遇到的问题:
一:url问题:
刚开始我将(/数值)与(/文章名)作为打开不同页与展开具体文章是的url,但是实际是他只会传入到同一个函数中去,这个坑了我不少时间。后来我将具体文章展开页的url改成了(/article/文章名)就解决了。
二:mysql操作
我用的是py2.7.6中的MySQLdb模块实现的数据库操作,后面在重构代码是用了装饰器
1 def conclos(**kwargs): #定义带参装饰器,可用于输入具体链接数据库的参数,见21行 2 def ifunc(func): 3 def infunc(sql): 4 conn = MySQLdb.Connect( 5 host=kwargs['host'], 6 port = kwargs['port'], 7 user = kwargs['user'], 8 passwd = kwargs['passwd'], 9 db = kwargs['db'], 10 charset = kwargs['charset'], 11 ) 12 cursor = conn.cursor() 13 result = func(cursor,sql) 14 conn.commit() 15 cursor.close() 16 conn.close() 17 return result 18 return infunc 19 return ifunc 20 21 @conclos(host='127.0.0.1',port = 3306,user = 'root',passwd = 'punkisdead',db = 'flasktry',charset = 'utf8',) 22 def exe(cursor,sql): 23 cursor.execute(sql) 24 outcatch = cursor.fetchall() 25 return outcatch #此返回值为[(第一条记录),(第二条纪录)...],后面再做处理就是了
*本来想写成orm的,但是觉得这样的也不错。不过还是应该再写一下orm,毕竟真正用的时候基本都写orm
三:分页
分页功能我还是想了一会儿,后来发现将页数和对应取出的纪录联系起来再传给前段就很容易搞定了,下面是假设每页显示三篇,则见12行通过page参数从数据库提取结果中抽取对应内容即可,然后一起返回
1 def getcontent(page='1', sql = 'select * from article'): 2 conn,cursor=connectdb() 3 cursor.execute(sql) 4 result = cursor.fetchall() 5 if len(result)%3 == 0: 6 pagenum = len(result)/3 7 else: 8 pagenum = len(result)/3 + 1 9 pagenum = range(1,pagenum+1) 10 nav = [] 11 article = [] 12 result = result[ int(page)*3-3 : int(page)*3] 13 for ele in result: 14 nav.append(ele[3]) 15 article.append((ele[0],ele[2])) 16 cursor.close() 17 conn.close() 18 return page,pagenum,nav,article
四:容易实现的‘记住我’功能
只需在login与signup视图函数中成功后设置session['name'] = request.form['name']
再在展示页面
if 'name' in session:
name = session['name']
既可以获取
代码:
1:.py
1 # -*- coding:utf8 -*- 2 #encoding = utf-8 3 from flask import Flask, render_template, request, redirect, url_for, session 4 import MySQLdb 5 6 7 app = Flask(__name__) 8 9 def connectdb(): 10 conn = MySQLdb.Connect( 11 host='127.0.0.1', 12 port = 3306, 13 user = 'root', 14 passwd = 'punkisdead', 15 db = 'flasktry', 16 charset = 'utf8', 17 ) 18 cursor = conn.cursor() 19 return conn, cursor 20 21 def getcontent(page='1', sql = 'select * from article'): 22 conn,cursor=connectdb() 23 cursor.execute(sql) 24 result = cursor.fetchall() 25 if len(result)%3 == 0: 26 pagenum = len(result)/3 27 else: 28 pagenum = len(result)/3 + 1 29 pagenum = range(1,pagenum+1) 30 # pageremain = len(result)%3 31 nav = [] 32 article = [] 33 result = result[ int(page)*3-3 : int(page)*3] 34 for ele in result: 35 nav.append(ele[3]) 36 article.append((ele[0],ele[2])) 37 nav = set(nav) 38 cursor.close() 39 conn.close() 40 return page,pagenum,nav,article 41 42 43 @app.route('/<page>') 44 def index(page): 45 if 'name' in session: 46 name = session['name'] 47 page,pagenum,nav,article = getcontent(page=page) 48 return render_template('index.html',**locals()) 49 50 @app.route('/article/<title>') 51 def article(title): 52 print title 53 if 'name' in session: 54 name = session['name'] 55 conn,cursor = connectdb() 56 search = "select * from article WHERE title = '%s'"%title 57 cursor.execute(search) 58 result = cursor.fetchone() 59 cursor.close() 60 conn.close() 61 getxititle = result[0] 62 getxicontent = result[2] 63 return render_template('article.html',**locals()) 64 65 @app.route('/login/', methods=['POST','GET']) 66 def login(): 67 if request.method=='POST': 68 conn,cursor = connectdb() 69 search = "select passwd from User WHERE NAME = '%s'"%request.form['name'] 70 cursor.execute(search) 71 result = cursor.fetchone() 72 if request.form['passwd'] == result[0]: 73 cursor.close() 74 conn.close() 75 session['name'] = request.form['name'] 76 # name=request.form['name'] 77 # page,pagenum,nav,article=getcontent(1) 78 # return render_template('index.html',**locals()) 79 return redirect(url_for('index', page = '1')) 80 # return render_template('index.html',name=request.form['name']) 81 else: 82 return render_template('login.html',info = 'wrong name or password') 83 return render_template('login.html') 84 85 @app.route('/signup/', methods=['POST','GET']) 86 def signup(): 87 if request.method=='POST': 88 conn,cursor = connectdb() 89 insert = "insert into User VALUES('%s','%s')"%(request.form['name'],request.form['passwd']) 90 cursor.execute(insert) 91 conn.commit() 92 cursor.close() 93 conn.close() 94 session['name'] = request.form['name'] 95 # name=request.form['name'] 96 # page,pagenum,nav,article=getcontent(1) 97 # return render_template('index.html',**locals()) 98 return redirect(url_for('index', page = '1')) 99 return render_template('signup.html') 100 101 if __name__ == '__main__': 102 app.secret_key = 'A0Zr98j/3yX R~XHH!jmN]LWX/,?RT' 103 app.run(debug=True) 104 105 106 # @app.route('/') 107 # def hello_world(): 108 # conn,cursor=connectdb() 109 # cursor.execute('select * from article') 110 # result = cursor.fetchall() 111 # nav = [] 112 # article = [] 113 # for ele in result: 114 # nav.append(ele[3]) 115 # article.append((ele[0],ele[2])) 116 # return render_template('index.html',**locals())
2:index.html
1 <!DOCTYPE html> 2 <html lang="en"> 3 <head> 4 <meta charset="UTF-8"> 5 <link href= {{ url_for('static', filename='style.css')}} rel="stylesheet"> 6 </head> 7 <body> 8 <div class="center sign"> 9 {% if name %} 10 <span class="rs"> 来了啊,{{ name }}</span> 11 {% endif %} 12 {% if not name %} 13 <span class='rs'><a href="/login/">登陆</a></span> 14 <span class='rs'><a href="/signup/">注册</a></span> 15 {% endif %} 16 </div> 17 <div class="cl"></div> 18 <div class="abcenter"> 19 <img src = {{ url_for('static', filename='orpic.jpg')}} id="pic" width='146' height="163"> 20 </div> 21 <div class="abcenter nav"> 22 {% for i in nav %} 23 <span>{{ i }}</span> 24 {% endfor %} 25 </div> 26 <div class="ablittlecenter"> 27 {% for title,content in article %} 28 <div id = 'title'> 29 <a href="article/{{ title }}" style="color:black; text-decoration:none;"><span><b>{{ title }}</b></span></a> 30 </div> 31 <div> 32 <p> 33 {{ content}} 34 </p> 35 </div> 36 {% endfor %} 37 38 </div> 39 <div class="abcenter page"> 40 {% for num in pagenum %} 41 <a href={{ num }} class='rs'><button type="button">{{ num }}</button></a> 42 {% endfor %} 43 </div> 44 <div class="abcenter contra"> 45 <span>邮箱:billiepander@126.com</span> 46 </div> 47 </body> 48 </html>
3:style.css
1 *{ margin:0 } 2 .l{ float:left } 3 .rs{ float:right } 4 .cl{ clear:both } 5 .abcenter{ width:960px;margin:0 auto; text-align:center} 6 .ablittlecenter{ width:860px;margin:0 auto; text-align:center} 7 .ablittlecenterarticle{ width:860px;margin:0 auto; text-align:center} 8 .center{ width:960px; margin:0 auto;} 9 .sign span{ margin-right:10px} 10 #pic{ width:146px; height:146px; border-radius:50%; overflow:hidden } 11 .nav{ background-color:grey; font-size:25px } 12 .ablittlecenter p{ height:76px; overflow:hidden } 13 .ablittlecenterarticle p{ height:450px; overflow:auto } 14 #title{ font-size:24px; margin:15px 0px} 15 .page{padding-top: 80px;} 16 .contra{ position:absolute; margin-left:300px; bottom:0px; background-color:grey;}