很久没写东西了,寒假比较低效,几乎没写代码。只在慕课网上刷完了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模块实现的数据库操作,后面在重构代码是用了装饰器

 def conclos(**kwargs):           #定义带参装饰器,可用于输入具体链接数据库的参数,见21行
def ifunc(func):
def infunc(sql):
conn = MySQLdb.Connect(
host=kwargs['host'],
port = kwargs['port'],
user = kwargs['user'],
passwd = kwargs['passwd'],
db = kwargs['db'],
charset = kwargs['charset'],
)
cursor = conn.cursor()
result = func(cursor,sql)
conn.commit()
cursor.close()
conn.close()
return result
return infunc
return ifunc @conclos(host='127.0.0.1',port = 3306,user = 'root',passwd = 'punkisdead',db = 'flasktry',charset = 'utf8',)
def exe(cursor,sql):
cursor.execute(sql)
outcatch = cursor.fetchall()
return outcatch #此返回值为[(第一条记录),(第二条纪录)...],后面再做处理就是了

    *本来想写成orm的,但是觉得这样的也不错。不过还是应该再写一下orm,毕竟真正用的时候基本都写orm

三:分页

  分页功能我还是想了一会儿,后来发现将页数和对应取出的纪录联系起来再传给前段就很容易搞定了,下面是假设每页显示三篇,则见12行通过page参数从数据库提取结果中抽取对应内容即可,然后一起返回

 def getcontent(page='', sql = 'select * from article'):
conn,cursor=connectdb()
cursor.execute(sql)
result = cursor.fetchall()
if len(result)%3 == 0:
pagenum = len(result)/3
else:
pagenum = len(result)/3 + 1
pagenum = range(1,pagenum+1)
nav = []
article = []
result = result[ int(page)*3-3 : int(page)*3]
for ele in result:
nav.append(ele[3])
article.append((ele[0],ele[2]))
cursor.close()
conn.close()
return page,pagenum,nav,article

四:容易实现的‘记住我’功能

  只需在login与signup视图函数中成功后设置session['name'] = request.form['name']

  再在展示页面

  if 'name' in session:

    name = session['name']
既可以获取 代码:
1:.py
 # -*- coding:utf8 -*-
#encoding = utf-8
from flask import Flask, render_template, request, redirect, url_for, session
import MySQLdb app = Flask(__name__) def connectdb():
conn = MySQLdb.Connect(
host='127.0.0.1',
port = 3306,
user = 'root',
passwd = 'punkisdead',
db = 'flasktry',
charset = 'utf8',
)
cursor = conn.cursor()
return conn, cursor def getcontent(page='', sql = 'select * from article'):
conn,cursor=connectdb()
cursor.execute(sql)
result = cursor.fetchall()
if len(result)%3 == 0:
pagenum = len(result)/3
else:
pagenum = len(result)/3 + 1
pagenum = range(1,pagenum+1)
# pageremain = len(result)%3
nav = []
article = []
result = result[ int(page)*3-3 : int(page)*3]
for ele in result:
nav.append(ele[3])
article.append((ele[0],ele[2]))
nav = set(nav)
cursor.close()
conn.close()
return page,pagenum,nav,article @app.route('/<page>')
def index(page):
if 'name' in session:
name = session['name']
page,pagenum,nav,article = getcontent(page=page)
return render_template('index.html',**locals()) @app.route('/article/<title>')
def article(title):
print title
if 'name' in session:
name = session['name']
conn,cursor = connectdb()
search = "select * from article WHERE title = '%s'"%title
cursor.execute(search)
result = cursor.fetchone()
cursor.close()
conn.close()
getxititle = result[0]
getxicontent = result[2]
return render_template('article.html',**locals()) @app.route('/login/', methods=['POST','GET'])
def login():
if request.method=='POST':
conn,cursor = connectdb()
search = "select passwd from User WHERE NAME = '%s'"%request.form['name']
cursor.execute(search)
result = cursor.fetchone()
if request.form['passwd'] == result[0]:
cursor.close()
conn.close()
session['name'] = request.form['name']
# name=request.form['name']
# page,pagenum,nav,article=getcontent(1)
# return render_template('index.html',**locals())
return redirect(url_for('index', page = ''))
# return render_template('index.html',name=request.form['name'])
else:
return render_template('login.html',info = 'wrong name or password')
return render_template('login.html') @app.route('/signup/', methods=['POST','GET'])
def signup():
if request.method=='POST':
conn,cursor = connectdb()
insert = "insert into User VALUES('%s','%s')"%(request.form['name'],request.form['passwd'])
cursor.execute(insert)
conn.commit()
cursor.close()
conn.close()
session['name'] = request.form['name']
# name=request.form['name']
# page,pagenum,nav,article=getcontent(1)
# return render_template('index.html',**locals())
return redirect(url_for('index', page = ''))
return render_template('signup.html') if __name__ == '__main__':
app.secret_key = 'A0Zr98j/3yX R~XHH!jmN]LWX/,?RT'
app.run(debug=True) # @app.route('/')
# def hello_world():
# conn,cursor=connectdb()
# cursor.execute('select * from article')
# result = cursor.fetchall()
# nav = []
# article = []
# for ele in result:
# nav.append(ele[3])
# article.append((ele[0],ele[2]))
# return render_template('index.html',**locals())

.py

 2:index.html

 <!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<link href= {{ url_for('static', filename='style.css')}} rel="stylesheet">
</head>
<body>
<div class="center sign">
{% if name %}
<span class="rs"> 来了啊,{{ name }}</span>
{% endif %}
{% if not name %}
<span class='rs'><a href="/login/">登陆</a></span>
<span class='rs'><a href="/signup/">注册</a></span>
{% endif %}
</div>
<div class="cl"></div>
<div class="abcenter">
<img src = {{ url_for('static', filename='orpic.jpg')}} id="pic" width='146' height="163">
</div>
<div class="abcenter nav">
{% for i in nav %}
<span>{{ i }}</span>
{% endfor %}
</div>
<div class="ablittlecenter">
{% for title,content in article %}
<div id = 'title'>
<a href="article/{{ title }}" style="color:black; text-decoration:none;"><span><b>{{ title }}</b></span></a>
</div>
<div>
<p>
{{ content}}
</p>
</div>
{% endfor %} </div>
<div class="abcenter page">
{% for num in pagenum %}
<a href={{ num }} class='rs'><button type="button">{{ num }}</button></a>
{% endfor %}
</div>
<div class="abcenter contra">
<span>邮箱:billiepander@126.com</span>
</div>
</body>
</html>

index.html

3:style.css

 *{ margin:0 }
.l{ float:left }
.rs{ float:right }
.cl{ clear:both }
.abcenter{ width:960px;margin:0 auto; text-align:center}
.ablittlecenter{ width:860px;margin:0 auto; text-align:center}
.ablittlecenterarticle{ width:860px;margin:0 auto; text-align:center}
.center{ width:960px; margin:0 auto;}
.sign span{ margin-right:10px}
#pic{ width:146px; height:146px; border-radius:50%; overflow:hidden }
.nav{ background-color:grey; font-size:25px }
.ablittlecenter p{ height:76px; overflow:hidden }
.ablittlecenterarticle p{ height:450px; overflow:auto }
#title{ font-size:24px; margin:15px 0px}
.page{padding-top: 80px;}
.contra{ position:absolute; margin-left:300px; bottom:0px; background-color:grey;}

style.css

最新文章

  1. 前端Js框架汇总
  2. CSS布局 ——从display,position, float属性谈起
  3. restful是什么
  4. HDOJ 4652 Dice
  5. 关于 edittext 软键盘退出监听解决办法
  6. POJ 2387 Til the Cows Come Home
  7. cdoj 邱老师看电影
  8. angular.js小知识总结
  9. 【java设计模式】【行为模式Behavioral Pattern】迭代器模式Iterator Pattern
  10. Using mysqldump for Backups(备份还原数据库实例及参数详细说明)
  11. field_automation源码分析
  12. RSA 非对称加密,私钥转码为pkcs8 错误总结
  13. mysql的innodb存储引擎和myisam存储引擎的区别
  14. Python3 urllib抓取指定URL的内容
  15. 《spark机器学习 第二版》 蔡立宇 分享 pdf下载
  16. Django:提交表单时遇到403错误:CSRF verification failed
  17. PostgreSQL参数学习:random_page_cost
  18. Mybatis-Generator插件的使用与Spring集成Mybatis的配置
  19. Python入门之 字符串操作,占位符,比较大小 等
  20. for循环枚举法,全排列+dfs,补充浮点数注意事项

热门文章

  1. (转)QT常用快捷键
  2. 理解angularJS中作用域$scope
  3. CSS布局:div高度随窗口变化而变化(BUG会有滚动条)
  4. php对mongo操作问题
  5. Delphi-LowerCase 函数
  6. C++explicit关键字
  7. 信号量 sem_t 进程同步
  8. 从MVC框架看MVC架构的设计(转)
  9. -_-#【Angular】工具函数
  10. 【转】(DT系列一)DTS结构及其编译方法----不错