Tornado Web Server框架编写简易Python服务器

yipeiwu_com6年前服务器

我们都知道在Web开发中,都需要服务器,比如Java Web开发的Tomcat,WebLogic,WebSphere,现在来看利用Tornado Web Server框架如何写一个简易的Python服务器。

一般来说只需要实现get和post方法就可以了。以上次使用redis数据库的例子说明,数据库插入代码如下:

import redis
import datetime
 
class Database:
  def __init__(self):
    self.host = 'localhost'
    self.port = 6379
    self.write_pool = {}
 
  def add_write(self,website,city,year,month,day,deal_number):
    key = '_'.join([website,city,str(year),str(month),str(day)])
    val = deal_number
    self.write_pool[key] = val
 
  def batch_write(self):
    try:
      r = redis.StrictRedis(host=self.host,port=self.port)
      r.mset(self.write_pool)
    except Exception, exception:
      print exception
      
 
def add_data():
  beg = datetime.datetime.now()
  db = Database()
  for i in range(1,10000):
    db.add_write('meituan','beijing',2013,i,1,i)
  db.batch_write()
  end = datetime.datetime.now()
  print end-beg
      
if __name__ == '__main__':
  add_data()

以上代码插入了数据,那么现在用我们的服务器来访问一些数据。

import json
import redis
import tornado.web
import tornado.httpserver
from tornado.options import define, options
 
define("port", default=8888, type=int)
 
class DealHandler(tornado.web.RequestHandler):
  def initialize(self):
    self.port = 6379
    self.host = "localhost"
 
  def get(self):
    website = self.get_argument("website",None)
    city  = self.get_argument("city",None)
    year  = self.get_argument("year",None)
    month  = self.get_argument("month",None)
 
    keyset = []
    for i in range(1,31):
      key = '_'.join([website,city,year,month,str(i)])
      keyset.append(key)
 
    r = redis.StrictRedis(host=self.host,port=self.port)
    self.write( json.dumps(r.mget(keyset)) )
 
class ExampleHandler(tornado.web.RequestHandler):
  def get(self):
    who = self.get_argument("who", None)
    if who:
      self.write("Hello, " + who)
    else:
      self.write("Hello World!")
    
  def post(self):
    who = self.get_argument("who", None)
    if who:
      self.write("Hello, " + who)
    else:
      self.write("Hello World!")
 
class Application(tornado.web.Application):
  def __init__(self):
    handlers = [
      (r"/", ExampleHandler),
      (r"/deal", DealHandler),
    ]
    settings = dict()
    tornado.web.Application.__init__(self, handlers, settings)
 
def create_server():
  tornado.options.parse_command_line()
  http_server = tornado.httpserver.HTTPServer(Application())
  http_server.listen(options.port)
  tornado.ioloop.IOLoop.instance().start()
 
if __name__ == "__main__":
  create_server()

以上代码实现了一个简单的服务器,用于处理http请求。

在浏览器中输入:

http://localhost:8888/deal?website=meituan&city=beijing&year=2013&month=9

即可得到需要的数据。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

Python实现的简单文件传输服务器和客户端

还是那个题目(题目和流程见java版本),感觉光用java写一点新意也没有,恰巧刚学习了python,何不拿来一用,呵呵: 服务器端: import SocketServer, t...

Python面向对象之Web静态服务器

Python面向对象之Web静态服务器

本文实例为大家分享了Python Web静态服务器的具体代码,供大家参考,具体内容如下 功能:用户访问服务器可以返回指定页面 步骤: 1.创建服务器类 2.创建初始化服务器配置...

尝试使用Python多线程抓取代理服务器IP地址的示例

这里以抓取 http://www.proxy.com.ru 站点的代理服务器为例,代码如下: #!/usr/bin/env python #coding:utf-8 import u...

Spring Cloud微服务架构简介

Spring Cloud微服务架构简介

什么是微服务微服务架构风格是一种将一个单一应用程序开发为一组小型服务的方法,每个服务运行在自己的进程中,服务间通信采用轻量级通信机制(通常用HTTP资源API)。这些服务围绕业务能力构建并且可通过全自...

Python3之简单搭建自带服务器的实例讲解

Python3之简单搭建自带服务器的实例讲解

WEB开发,我们先从搭建一个简单的服务器开始,Python自带服务模块,且python3相比于python2有很大不同, 在Python2.6版本里,/usr/bin/lib/pytho...