python的bottle框架中实现最基本的get和post的方法的教程

1、get方式:

# -*- coding: utf-8 -*-
#!/usr/bin/python
# filename: getpost_test.py
# codedtime: 2014-9-20 19:07:04
import bottle
def check_login(username, password):
if username == ‘123’ and password == ‘234’:
return true
else:
return false
@bottle.route(‘/login’)
def login():
if bottle.request.get.get(‘do_submit’,”).strip(): #点击登录按钮
# 第一种方式(latin1编码)
## username = bottle.request.get.get(‘username’,”).strip() # 用户名
## password = bottle.request.get.get(‘password’,”).strip() # 密码
#第二种方式(获取username\password)(latin1编码)
getvalue = bottle.request.query_string
## username = bottle.request.query[‘username’] # an utf8 string provisionally decoded as iso-8859-1 by the server
## password = bottle.request.query[‘password’] # 注:iso-8859-1(即aka latin1编码)
#第三种方式(获取utf-8编码)
username = bottle.request.query.username # the same string correctly re-encoded as utf8 by bottle
password = bottle.request.query.password # the same string correctly re-encoded as utf8 by bottle
print(‘getvalue= ‘+getvalue,
‘\r\nusername= ‘+username,
‘\r\npassword= ‘+password) # test
if check_login(username, password):
return “

your login information was correct.


else:
return “

login failed.


else:
return ”’
username:
password:

”’
bottle.run(host=’localhost’, port=8083)

这里注意说一下bottle编码的问题,只有第三种方式会将我们输入的字符如果是utf-8重新编码为utf-8,当你的内容里有中文或其他非英文字符时,这种方式就显的尤为重要。

运行效果如下:

2015430172604482.png (699×104)

2、post方式:

# -*- coding: utf-8 -*-
#!/usr/bin/python
# filename: getpost_test.py
# codedtime: 2014-9-20 19:07:04
import bottle
def check_login(username, password):
if username == ‘123’ and password == ‘234’:
return true
else:
return false
@bottle.route(‘/login’)
def login():
return ”’
username:
password:

”’
@bottle.route(‘/login’, method=’post’)
def do_login():
# 第一种方式
# username = request.forms.get(‘username’)
# password = request.forms.get(‘password’)
#第二种方式
postvalue = bottle.request.post.decode(‘utf-8’)
username = bottle.request.post.get(‘username’)
password = bottle.request.post.get(‘password’)
if check_login(username, password):
return “

your login information was correct.


else:
return “

login failed.


bottle.run(host=’localhost’, port=8083)

登录网站、提交文章、评论等我们一般都会用post方式而非get方式,那么类似于第二种方式的编码就很用用处,能够正确的处理我们在form中提交的内容。而第一种则可能会出现传说中的乱码问题,谨记!!!

Posted in 未分类

发表评论