Source

wdfanyi / main.py

# -*- coding: utf-8 -*-
import urllib
import os
from urllib import unquote
import urllib2
import urllib,urllib2,httplib
from django.utils import simplejson as json
from sgmllib import SGMLParser
import logging
from time import sleep
from datetime import datetime, timedelta, date
from google.appengine.ext.webapp import util
from google.appengine.ext.webapp import template
import yui
from google.appengine.ext import db

class words(db.Model):
	user= db.StringProperty()
	time = db.DateTimeProperty()
	EN=db.StringProperty(multiline=True)
	CN=db.StringProperty(multiline=True)
	ctr=db.IntegerProperty(default=100)
def fanyi(text):
	httplib.HTTPConnection.debuglevel = 1
	url_t = "http://ajax.googleapis.com/ajax/services/language/translate"
	data = urllib.urlencode({'v':'1.0','q':text,'langpair':'en|zh-CN'})
	req = urllib2.Request(url_t)
	req.add_header('User-Agent', "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 2.0.50727)")
	response = urllib2.urlopen(req,data)
	html = json.loads( response.read())
	return html['responseData']['translatedText']

def getCNnow():
	return datetime.utcnow() + timedelta(hours=+8)
def handleMultibyteUrl(func):
  def handler(self, *paths):
    if not paths: # 没有路径就不用转义了
      return func(self)

    newPath = []

    for path in paths: # 如果有多个参数的话,将其全部转义
      unquotedPath = unquote(path)
      try:
        path = unicode(unquotedPath, 'utf8')
      except:
        try:
          path = unicode(unquotedPath, 'gbk')
        except:
          try:
            path = unicode(unquotedPath, 'big5')
          except:
            try:
              path = unicode(unquotedPath, 'shiftjis')
            except:
              try:
                path = unicode(unquotedPath, 'korean')
              except:
                pass
      newPath.append(path)
    return func(self, *newPath)

  return handler

logging.getLogger().setLevel(logging.DEBUG)


class Hello(yui.RequestHandler):
	def get(self):
		self.write('hello')


class Param(yui.RequestHandler):
	def post(self):
		self.write(self.GET['x'] or '')
		self.write(self.GET['y'] or '')
		self.write(self.POST['x'] or '')
		self.write(self.POST['y'] or '')
		self.write(','.join(self.request.get_all('x')))
		self.write(','.join(self.request.get_all('y')))


class Number(yui.RequestHandler):
	def get(self, num):
		self.write(num)


class Ajax(yui.XhtmlRequestHandler):
	def get(self):
		self.write(r'''<html xmlns="http://www.w3.org/1999/xhtml" lang="en">
<head>
<title>Hello</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.1/jquery.min.js"></script>
</head>
<body>
<input type="text" id="input" value="ooxx"/>
<button>click me</button>
<div id="text"></div>
<script>
$('button').click(function(){
	$.ajax({
		type: 'POST',
		url: '/ajax/',
		data: {'message': $('#input').val()},
		success: function(data){
			$('#text').text(data.message);
		}
	});
});
</script>
</body>
</html>''')

	@yui.client_cache(0)
	def post(self):
		self.set_content_type('json')
		text=self.POST['message']
		httplib.HTTPConnection.debuglevel = 1
		url_t = "http://ajax.googleapis.com/ajax/services/language/translate"
		data = urllib.urlencode({'v':'1.0','q':text,'langpair':'en|zh-CN'})
		req = urllib2.Request(url_t)
		req.add_header('User-Agent', "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 2.0.50727)")
		response = urllib2.urlopen(req,data)
		html = json.loads( response.read())
		WORD=words()
		WORD.user='weakdancer'
		WORD.EN=text
		WORD.CN=html['responseData']['translatedText']
		WORD.time=getCNnow()
		WORD.put()
		self.write('{"message": "%s"}' % WORD.CN)

class User(yui.RequestHandler):
	@yui.authorized()
	@yui.server_cache(60)
	def get(self):
		sleep(0.2)
		self.write('hello, ' + self.request.user.nickname())


class Admin(yui.HtmlRequestHandler):
	@yui.authorized(True)
	def get(self):
		WORDS=words.all()
		template_values = {
		'QUOTES':WORDS,
		}
		path = os.path.join(os.path.dirname(__file__), 'tpl','admin.html')
		self.write(template.render(path, template_values))
	def post(self):
		delitem=self.request.get_all('delitem')
		for item in delitem:
			db.get(item).delete()

		self.redirect('/del')
class NotFound(yui.HtmlRequestHandler):
	@yui.server_cache(60, False)
	def get(self):
	  template_values = {
      }
	  path = os.path.join(os.path.dirname(__file__), 'tpl','mainpage.html')
	  self.write(template.render(path, template_values))
class TranslatePage(yui.HtmlRequestHandler):
	def get(self):
		WORDS=words.all().order("-time").fetch(limit=2)
		template_values = {
		'WORDS':WORDS,
		}
		# self.before()
		path = os.path.join(os.path.dirname(__file__), 'tpl','bingo.html')
		self.write(template.render(path, template_values))
class ShowAll(yui.RequestHandler):
	def get(self):
		WORDS=words.all().order("-time")
		template_values = {
		'WORDS':WORDS,
		}
		path = os.path.join(os.path.dirname(__file__), 'tpl','bingo.html')
		self.write(template.render(path, template_values))
class ShowAllPhone(yui.HtmlRequestHandler):
	def get(self):
		# self.before()
		WORDS=words.all().order("-time")
		for i in ['{{%s}}||{{%s}}\n'%(WORD.EN,WORD.CN) for WORD in WORDS]:
			self.write(i)

class TranslateHandlerEN(yui.RequestHandler):
	@handleMultibyteUrl
	def get(self,text):
		httplib.HTTPConnection.debuglevel = 1
		url_t = "http://ajax.googleapis.com/ajax/services/language/translate"
		data = urllib.urlencode({'v':'1.0','q':text,'langpair':'en|zh-CN'})
		req = urllib2.Request(url_t)
		req.add_header('User-Agent', "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 2.0.50727)")
		response = urllib2.urlopen(req,data)
		html = json.loads( response.read())
		WORD=words()
		WORD.user='weakdancer'
		WORD.EN=text
		WORD.CN=html['responseData']['translatedText']
		WORD.time=getCNnow()
		WORD.put()
		self.write(WORD.CN)
	def post(self):
		text=self.POST['word']
		httplib.HTTPConnection.debuglevel = 1
		url_t = "http://ajax.googleapis.com/ajax/services/language/translate"
		data = urllib.urlencode({'v':'1.0','q':text,'langpair':'en|zh-CN'})
		req = urllib2.Request(url_t)
		req.add_header('User-Agent', "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 2.0.50727)")
		response = urllib2.urlopen(req,data)
		html = json.loads( response.read())
		WORD=words()
		WORD.user='weakdancer'
		WORD.EN=text
		WORD.CN=html['responseData']['translatedText']
		WORD.time=getCNnow()
		WORD.put()
		self.redirect('/')
class TranslateHandlerCN(yui.RequestHandler):
	@handleMultibyteUrl
	def get(self,text):
		httplib.HTTPConnection.debuglevel = 1
		url_t = "http://ajax.googleapis.com/ajax/services/language/translate"
		data = urllib.urlencode({'v':'1.0','q':text.encode('utf-8'),'langpair':'zh-CN|en'})
		req = urllib2.Request(url_t)
		req.add_header('User-Agent', "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 2.0.50727)")
		response = urllib2.urlopen(req,data)
		html = json.loads( response.read())
		WORD=words()
		WORD.user='weakdancer'
		WORD.CN=text
		WORD.EN=html['responseData']['translatedText']
		WORD.time=getCNnow()
		WORD.put()
		self.write(WORD.EN)
	def post(self):
		text=self.POST['word']
		httplib.HTTPConnection.debuglevel = 1
		url_t = "http://ajax.googleapis.com/ajax/services/language/translate"
		data = urllib.urlencode({'v':'1.0','q':text.encode('utf-8'),'langpair':'zh-CN|en'})
		req = urllib2.Request(url_t)
		req.add_header('User-Agent', "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 2.0.50727)")
		response = urllib2.urlopen(req,data)
		html = json.loads( response.read())
		WORD=words()
		WORD.user='weakdancer'
		WORD.CN=text
		WORD.EN=html['responseData']['translatedText']
		WORD.time=getCNnow()
		WORD.put()
		self.write(WORD.EN)
		self.redirect('/')

class RememberPage(yui.HtmlRequestHandler):
	@yui.authorized(True)
	def get(self):
		WORDS=words.all().order('-ctr').fetch(8)
		template_values = {
		'WORDS':WORDS,
		}
		path = os.path.join(os.path.dirname(__file__), 'tpl','remember.html')
		self.write(template.render(path, template_values))
	def post(self,flag):
		if flag == 'r':
			item=db.get(self.request.get('item'))
			item.ctr=item.ctr-1
			item.lastMODtime=getCNnow().date()
			item.put()
		if flag == 'reset':
			item=db.get(self.request.get('item'))
			item.ctr=100
			item.lastMODtime=getCNnow().date()
			item.put()
		if flag == 'del':
			item=db.get(self.request.get('item'))
			item.ctr=0
			item.lastMODtime=getCNnow().date()
			item.put()
		if flag == 'rall':
			items=self.request.get_all('item')
			for item in items:
				item=db.get(item)
				item.ctr=item.ctr-1
				item.lastMODtime=getCNnow().date()
				item.put()
		self.redirect('/r')

class TidyHandler(yui.RequestHandler):
	@yui.authorized(True)
	def get(self):
		WORDS=words.all()
		for WORD in WORDS:
			WORD.ctr=100
			WORD.put()
		self.redirect('/r')


application = yui.WsgiApplication([
	# ('/', Hello),
	('/', TranslatePage),
	('/param', Param),
	('/show', ShowAll),
	('/showphone', ShowAllPhone),
	(r'/(\d+)', Number),
	('/ajax/', Ajax),
	('/user', User),
	('/del', Admin),
	('/translateEN', TranslateHandlerEN),
	('/translateEN/(.*)', TranslateHandlerEN),
	('/translateCN', TranslateHandlerCN),
	('/translateCN/(.*)', TranslateHandlerCN),
	('/r', RememberPage),
	('/r/(.*)', RememberPage),
	('/tidy', TidyHandler),
	('.*', NotFound) # not existing, expected to be 404 not found
])

def main():
	util.run_wsgi_app(application)

if __name__ == '__main__':
	main()