Tornado API Simple Template

Source: Internet
Author: User

# installation

Pip Insatll tornado

# main File web_server.py

#!/usr/bin/env python#Encoding:utf-8ImportTornado.httpserverImporttornado.optionsImportTornado.web fromTornado.optionsImportdefine,optionsImportSys,os,re fromApicodeImportapicodereload (SYS) sys.setdefaultencoding ('Utf-8')#define default call port to 8088Define"Port", default=8088,help="run on the given port", type=int)#Verification Code Demo DemoclassVcodehandler (tornado.web.RequestHandler):#GET Request    defGet (self): result= Self.get_argument ("result", {}) City= Self.get_argument (' City', u'Chongqing') Self.render ("input_code.html", City=city, result=result)#POST Request    defpost (self): result= {'Code': 0,'msg':'Success','result':"'}                #Get ParametersCity = Self.get_argument (' City','CQ') Method= Self.get_argument ('Method','LR') Detail= eval (self.get_argument ('Detail', False)) Imgurl= Self.get_argument ('Imgurl',"') Imgfile= Self.request.files.get ('Imgfile', []) fname="'        #URL Method        ifImgurl andRe.search ('.+\. (jpg|png|bmp|gif)', Imgurl): fname='./static/uploads/%s'% Imgurl.split ('/') [-1] result['result']=Vcode.predict_url (city, Imgurl, Detail, method)#How to upload files        elifImgfile: forImginchImgfile:with Open ('./static/uploads/'+ img['filename'],'WB') as Fw:fw.write (img['Body']) fname='./static/uploads/'+ img['filename'] result['result'] =vcode.predict (city, fname, Detail, method)Else: ErrorMsg="Upload Verification Code picture file error or URL picture format is incorrect"result['Code'] ='-1'result['msg'] =errormsg Self.render ("output_code.html", City=city, Source=fname, Detail=detail, Method=method, result=result)#Captcha Call APIclassVcodeapihandler (tornado.web.RequestHandler):defGet (self): result= {'Code': 1000,'msg':'Call parameter error, please use POST request, City & Imgfile parameter','result':'instruction for use: Http://gitlab.tangees.com/miaoweihong/verify-code'} json_result=Tornado.escape.json_encode (Result) self.write (Json_result)defpost (self): result= {'Code': 0,'msg':'Success','result':"'} City= Self.get_argument (' City','CQ') Method= Self.get_argument ('Method','LR') Detail= eval (self.get_argument ('Detail', False)) Imgfile= Self.request.files.get ('Imgfile', [])        ifImgfile: forImginchImgfile:with Open ('./static/uploads/'+ img['filename'],'WB') as Fw:fw.write (img['Body']) fname='./static/uploads/'+ img['filename']                Try: result['result'] =vcode.predict (city, fname, Detail, method)exceptException as e:result['Code'] = 1001result['msg'] ='Error Uploading file contents'+Str (e)Else: result['Code'] = 1002result['msg'] ='No file content'        #return JSON resultsJson_result =Tornado.escape.json_encode (Result) self.write (Json_result)classTesthandler (tornado.web.RequestHandler):defGet (self): Self.write ('Hello, Jkmiao.')if __name__=="__main__":        #introduce a self-defined moduleVcode =Apicode () tornado.options.parse_command_line () app=tornado.web.Application (Handlers= [(R'/vcode', Vcodehandler), (R'/vcodeapi', Vcodeapihandler)],#URL MatchingTemplate_path = Os.path.join (Os.path.dirname (__file__),"Templates"),#Define the View page address, put the HTML fileStatic_path = Os.path.join (Os.path.dirname (__file__),"Static"),#define static templates, put Css,js and other filesDebug=true,#is the debug modeAutoescape=none,#do not set escape characters) Http_server=tornado.httpserver.HTTPServer (APP) Http_server.listen (Options.port)Print "starting tornado at Port http://127.0.0.1:%d"%options.port tornado.ioloop.IOLoop.instance (). Start ()

Get!

Tornado API Simple Template

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.