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看源码感觉实现挺复杂的,我们姑且不在这里 ...
随机推荐
- jquery 工作空间注册
在一些面向对象的语言中有命名空间的概念,好处就是把不同的类放在不同的文件夹下面,这样就不会发生命名冲突,当然命名空间还有其他的作用. 在这里我们讨论的是在JS中怎么使用命名空间.当然JS并没有提供原生 ...
- HTML5手机开发——滚动和惯性缓动
1. 滚动 以下是三种实现方式: 1) 利用原生的css属性 overflow: scroll div id= parent style = overflow:scroll; divid='conte ...
- table 表格隔行换色实现
table 表格隔行换色实现 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "htt ...
- 【行为型】Iterator模式
迭代器模式提供一种方法顺序访问聚合对象中的各个元素,而又不需要暴露该聚合对象的内部表示.对于该模式,估计几乎所有的人都使用过,在此直接给出类结构图参考如下: 如前所述,迭代器模式的思想主要是:一能提供 ...
- [Struts2学习笔记] -- 自定义类型转换
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"% ...
- UVA - 11346 Probability (概率)
Description Probability Time Limit: 1 sec Memory Limit: 16MB Consider rectangular coordinate system ...
- 省队集训day6 B
一道AC自动机题···· 一定要把一个节点没有的儿子接到它fai的儿子,否则会卡到n^2的······· #include<cstdio> #include<iostream> ...
- IOS 多个UIImageView 加载高清大图时内存管理
IOS 多个UIImageView 加载高清大图时内存管理 时间:2014-08-27 10:47 浏览:59人 当我们在某一个View多个UIImageView,且UIImageView都显示的是 ...
- spring获取properties
实际项目中,通常将一些可配置的定制信息放到属性文件中(如数据库连接信息,邮件发送配置信息等),便于统一配置管理.例中将需配置的属性信息放在属性文件/WEB-INF/configInfo.propert ...
- cocos2d-x lua脚本开发 1
自从开始关注OpenResty之后,逐渐关注Lua语言,发现这个语言真真是容易让人喜爱的语言.偶然间发现了cocos2d-x,还支持lua,所以果断尝试一下. 这里是在cocos2d-x官方网站下载了 ...