视频1 视频21 视频41 视频61 视频文章1 视频文章21 视频文章41 视频文章61 推荐1 推荐3 推荐5 推荐7 推荐9 推荐11 推荐13 推荐15 推荐17 推荐19 推荐21 推荐23 推荐25 推荐27 推荐29 推荐31 推荐33 推荐35 推荐37 推荐39 推荐41 推荐43 推荐45 推荐47 推荐49 关键词1 关键词101 关键词201 关键词301 关键词401 关键词501 关键词601 关键词701 关键词801 关键词901 关键词1001 关键词1101 关键词1201 关键词1301 关键词1401 关键词1501 关键词1601 关键词1701 关键词1801 关键词1901 视频扩展1 视频扩展6 视频扩展11 视频扩展16 文章1 文章201 文章401 文章601 文章801 文章1001 资讯1 资讯501 资讯1001 资讯1501 标签1 标签501 标签1001 关键词1 关键词501 关键词1001 关键词1501 专题2001
Python的Bottle框架中实现最基本的get和post的方法的教程
2020-11-27 14:33:17 责编:小采
文档
 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() # 密码

 #第二种方式(获取usernamepassword)(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,
 '
username= '+username,
 '
password= '+password) # test
 
 if check_login(username, password):
 return "

Your login information was correct.

" else: return "

Login failed.

" else: return ''' ''' bottle.run(host='localhost', port=8083)

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

运行效果如下:

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 ''' 
 '''

@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中提交的内容。而第一种则可能会出现传说中的乱码问题,谨记!!!

下载本文
显示全文
专题