Tornado框架使用http的GET方式傳輸中文漢字的簡(jiǎn)單實(shí)作
來(lái)源:程序員人生 發(fā)布時(shí)間:2015-04-14 08:19:21 閱讀次數(shù):3403次
最近業(yè)余時(shí)間在看Tornado框架的使用,雖然維基百科「Comparison of web application frameworks」把Tornado黑的不行,但上手確切很簡(jiǎn)單

這個(gè)教程的第2個(gè)例子
import textwrap
import tornado.httpserver
import tornado.ioloop
import tornado.options
import tornado.web
from tornado.options import define, options
define("port", default=8000, help="run on the given port", type=int)
class ReverseHandler(tornado.web.RequestHandler):
def get(self, input):
self.write(input[::⑴] + '
')
class WrapHandler(tornado.web.RequestHandler):
def post(self):
text = self.get_argument('text')
width = self.get_argument('width', 40)
self.write(textwrap.fill(text, int(width)) + '
')
class FindbrandHandler( tornado.web.RequestHandler ):
def get(self, input):
input_dcds = input.split('_')
input_dcd = u''
for elem in input_dcds:
if len(elem)>0:
input_dcd += unichr( int(elem) )
print input_dcd.encode('utf⑻')
o_str = 'input: '+input_dcd.encode('utf⑻') + '
output: getcha
'
self.write( o_str )
if __name__ == "__main__":
tornado.options.parse_command_line()
app = tornado.web.Application(
handlers=[
(r"/reverse/(w+)", ReverseHandler),
(r"/wrap", WrapHandler),
(r"/brand/(w+)", FindbrandHandler)
]
)
http_server = tornado.httpserver.HTTPServer(app)
http_server.listen(options.port)
tornado.ioloop.IOLoop.instance().start()
例程的邏輯以下:
添加FindbrandHandle類,繼承RequestHandler,重寫get方法
依照
/brand/(要求內(nèi)容)
的方式載入web.Application,然后運(yùn)行。
用curl要求:
curl localhost:9002/reverse/1234567
會(huì)得到以下返回
7654321
但是輸入中文
curl localhost:9002/reverse/從星星的彈空里
會(huì)得到404頁(yè)
<html><title>404: Not Found</title><body>404: Not Found</body></html>
這是由于http的GET方法,不支持漢語(yǔ),僅支持字母數(shù)字符號(hào)。早些年某些閱讀器訪問百度,也常常看見百度將搜索詞,使用urlencode方法,轉(zhuǎn)化為GET方法支持的url字符串。
這里我們使用unichr()和ord()兩個(gè)函數(shù),實(shí)現(xiàn)unicode字符與整形數(shù)的轉(zhuǎn)換,發(fā)送用下劃線間隔的整形數(shù)。
這里是客戶端例程:
import os
import sys
import nlp_tools as nt
urlstr = 'curl localhost:%d/brand/%s'
if __name__=='__main__':
n_args = len(sys.argv)
line = sys.argv[2]
ecd_data = ''
for word in line.decode('utf⑻'):
ecd_data += '%d_'%( ord(word) )
url_request = ''
if n_args==2:
url_request = urlstr%( 8000, ecd_data )
else:
url_request = urlstr%( int(sys.argv[1]), ecd_data )
print line
print url_request
os.system( url_request )
使用
python call_string_service1.py 9002 從星星的彈空里
調(diào)用該腳本,既可查看履行結(jié)果:
從星星的彈空里
curl localhost:9002/brand/20174_26143_26143_30340_24377_31354_37324_
input: 從星星的彈空里
output: getcha
本實(shí)作使用自寫編碼方式,簡(jiǎn)單演示其他url_encode模塊的工作原理,實(shí)現(xiàn)了中文漢字的傳輸。
生活不易,碼農(nóng)辛苦
如果您覺得本網(wǎng)站對(duì)您的學(xué)習(xí)有所幫助,可以手機(jī)掃描二維碼進(jìn)行捐贈(zèng)