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模块实现的数据库操作,后面在重构代码是用了装饰器
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
Flask挺好的更多相关文章
- 第09组 Alpha冲刺(1/6)
队名:观光队 组长博客 作业博客 组员实践情况 王耀鑫 过去两天完成了哪些任务 文字/口头描述 完成服务器连接数据库部分代码 展示GitHub当日代码/文档签入记录 接下来的计划 与服务器连接,配合前 ...
- 团队Arpha1
队名:观光队 组长博客 作业博客 组员实践情况 王耀鑫 **过去两天完成了哪些任务 ** 文字/口头描述 完成服务器连接数据库部分代码 展示GitHub当日代码/文档签入记录 接下来的计划 与服务器连 ...
- Angular+Flask搭建一个记录工具
平时用的最多的文本编辑器就是Notepad++,很多东西都是通过Notepad++直接记录的: 没有看完的网页链接 要整理.收藏的网页 读书笔记 要处理的事情 待看/看过的文档和电子书 等等... 随 ...
- python框架(flask/django/tornado)比较
一.对外数据接口 三者作为web框架,都是通过url映射对外的接口 flask:以decorator的形式,映射到函数中 django:以字典形式,映射到函数 tornado: 以字典形式,映射到类中 ...
- 为什么 Flask 有那么多的好评?
著作权归作者所有.商业转载请联系作者获得授权,非商业转载请注明出处.作者:松鼠奥利奥链接:http://www.zhihu.com/question/28902969/answer/42530571来 ...
- flask简单web应用
推荐一个学习python的网站,个人觉得在这里面收获挺大的,希望对后来学习flask的小伙伴们有帮助.http://www.pythondoc.com/ 用flask框架实现第一个web应用 首先需要 ...
- 一只猿:使用flask来做一个小应用
上周 @萍姐 问我如何抓取天猫上面店铺的评分,看了下挺简单的,于是花了点时间写了个Python脚本,加上web.py做成一个web服务,使用起来还不错,今天来看的时候发现当时为了方便直接用web.py ...
- flask_login 整合 pyjwt + json 简易flask框架
现在很多框架都实现前后端分离,主要为了适应以下几个目的: 1,前后端的分离,可以使前端开发和后端开发更加分工明确,而不是后端还需要在视图模板中加入很多{% XXXX %}标签 2,是为了适应跨域调用或 ...
- flask 即插视图(Pluggable Views)和endpoint
endpoint经常使用flask的人肯定不会面生.其实我一直没有关注过他是怎么寻址的,直到最近经常食用url_for这个函数才引起了我的注意. url_for看源码感觉实现挺复杂的,我们姑且不在这里 ...
随机推荐
- mysql报Fatal error encountered during command execution的解决办法
连接字符串里加上 Allow User Variables=True 解决. 否则时不时的报错,存储过程名长一点也报错,又有时报有时不报,参数传1位数就正常2位数就报错等…… 折腾mysql蛋疼啊
- href 里面 链接前面加/与不加的区别?(绝对路径与相对路径)
在写href链接时,有绝对路径与相对路径,href 里面 链接前面加/与不加的区别? href="/cp/images/lis.jpg" 相对路径 cp前面/会获取当前路径,组合成 ...
- bestcoder单调区间
http://bestcoder.hdu.edu.cn/contests/contest_showproblem.php?cid=584&pid=1006 题解:ORZ Matrix67 ht ...
- iOS Block 用法 (1)-once again
Block简介: Block的实际行为和Function很像,最大的差别是在可以存取同一个Scope的变量值.Block实体形式如下: ^(传入参数列){行为主体}; Block实体开头是“^”,接着 ...
- js渲染引擎 tempo.js
1.引入tempo.js <script src="js/tempo.js" type="text/javascript"></script& ...
- POJ 1704 Georgia and Bob (Nim游戏变形)
题目:http://poj.org/problem?id=1704 思路:Nim游戏策略,做如下转换,如果N是偶数,则两两配对,将两个数之间的格子数(距离)看做成这一堆石头的数量. 如果N是奇数,则将 ...
- 【Algorithm】逆序数的分治求解
逆序数的分治求解,时间复杂度O(nlgn).基本思想是在归并排序的基础上加逆序计数. #include <iostream> #include <cstdio> #includ ...
- POJ3436 ACM Computer Factory(最大流)
题目链接. 分析: 题意很难懂. 大体是这样的:给每个点的具体情况,1.容量 2.进入状态 3.出去状态.求最大流. 因为有很多点,所以如果一个点的出去状态满足另一个点的进入状态,则这两个点可以连一条 ...
- 【转】Android源代码查看途径
原文网址:http://www.it165.net/pro/html/201501/32967.html 作为一个android coder,多阅读android源码对提高android开发水平是很有 ...
- oracle number 和sqlserver numeric的区别
number如果不指定范围默认是可以输入所有位数的小数,numeric如果不指定小数默认是不允许输入小数