Source

knowledgeCenter / main.py

# -*- coding: utf-8 -*-
from settings import  *
import math
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)
	unixTime=db.StringProperty(multiline=False,default="0")
	syncFlag=db.StringProperty(multiline=False,default="0")
class wiki(db.Model):
	user= db.StringProperty()
	time = db.DateTimeProperty()
	EN=db.StringProperty(multiline=True)
	CN=db.StringProperty(multiline=True)
	tip=db.StringProperty(multiline=True)
	unixTime=db.StringProperty(multiline=False,default="0")
	syncFlag=db.StringProperty(multiline=False,default="0")
class swap(db.Model):
	time = db.DateTimeProperty()
	content=db.TextProperty()
	unixTime=db.StringProperty(multiline=False,default="0")
	syncFlag=db.StringProperty(multiline=False,default="0")
class li(db.Model):
	time = db.DateTimeProperty()
	content=db.StringProperty(multiline=False)
	unixTime=db.StringProperty(multiline=False,default="0")
	syncFlag=db.StringProperty(multiline=False,default="0")
def en2c(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 c2en(text):
	httplib.HTTPConnection.debuglevel = 1
	url_t = "http://ajax.googleapis.com/ajax/services/language/translate"
	data = urllib.urlencode({'v':'1.0','q':text.encode('utf8'),'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())
	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 Admin(yui.HtmlRequestHandler):
	@yui.authorized(True)
	def get(self):
		WORDS=words.all()
		WIKIS=wiki.all()
		template_values = {
		'WORDS':WORDS,
		'WIKIS':WIKIS,
		}
		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 Mainpage(yui.HtmlRequestHandler):
	def get(self,flag):
		try:
			TIME=getCNnow()
			WORDS=words.all().order("-time").fetch(limit=WORDS_LIMIT)
			WIKIS=wiki.all().order("-time").fetch(limit=WIKI_LIMIT)
			SWAPS=swap.all().order("-time").fetch(limit=SWAP_LIMIT,offset=0)
			LASTSWAP=swap.all().order("-time").fetch(limit=1)[0].content
			LIS=li.all().order("-time").fetch(limit=LI_LIMIT,offset=0)
			LASTLI=li.all().order("-time").fetch(limit=1)[0].content
		except IndexError:
			TIME=getCNnow()
			WORDS=None
			WIKIS=None
			SWAPS=None
			LASTSWAP=None
			LIS=None
			LASTLI=None
		template_values = {
		'WORDSS':WORDS,
		'WIKIS':WIKIS,
		'SWAPS':SWAPS,
		'LASTSWAP':LASTSWAP,
		'LIS':LIS,
		'LASTLI':LASTLI,
		"TIME":TIME,
		}
		# self.before()
		if flag=='':
			path = os.path.join(os.path.dirname(__file__), 'tpl','mainpage.html')
		else:
			path = os.path.join(os.path.dirname(__file__), 'tpl',flag+'.html')
		self.write(template.render(path, template_values))
class ShowAll(yui.HtmlRequestHandler):
	def get(self,flag):
		TIME=getCNnow()
		page_current=int(self.request.get('p') or '1')
		exec('''LIS=%s.all().order("-time")'''%flag)
		pages=math.floor(LIS.count()/PAGE_SIZE)+1
		exec('''LIS=%s.all().order("-time").fetch(PAGE_SIZE,PAGE_SIZE*(page_current-1))'''%flag)
		ps=[i for i in range(1,pages+1)]
		template_values = {
		'%s'%(flag.upper()+'S'):LIS,
		'pages': pages,
		'ps': ps,
		'page_current': page_current,
		"TIME":TIME,
		}
		path = os.path.join(os.path.dirname(__file__), 'tpl','%s.html'%flag)
		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 TranslateHandler(yui.RequestHandler):
	@handleMultibyteUrl
	def get(self,text):
		WORD=words()
		WORD.user='weakdancer'

		if ord(text[0])<=127:
			WORD.EN=text.strip().lower().strip()
			WORD.CN=en2c(text)
		else:
			WORD.CN=text
			WORD.EN=c2en(text).lower().strip()

		WORD.time=getCNnow()
		WORD.put()
		self.write(WORD.EN)
	def post(self):
		text=self.request.get('word')
		WORD=words()
		WORD.user='weakdancer'
		if ord(text[0])<=127:
			WORD.EN=text.lower().strip()
			WORD.CN=en2c(text)
		else:
			WORD.CN=text
			WORD.EN=c2en(text).lower().strip()
		WORD.time=getCNnow()
		WORD.put()
		self.write(WORD.EN)
		self.redirect('/words')

class RememberPage(yui.HtmlRequestHandler):
	def get(self):
		WORDS=words.all().order('-ctr').order('time').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 WikiHandler(yui.HtmlRequestHandler):
	def post(self,flag):
		if flag == 'new':
			name=self.request.get('name')
			tip=self.request.get('tip')
			WIKI=wiki()
			WIKI.user='weakdancer'
			if ord(name[0])<=127:
				WIKI.EN=name
				WIKI.CN=en2c(name)
			else:
				WIKI.CN=name
				WIKI.EN=c2en(name)
			WIKI.tip=tip
			WIKI.time=getCNnow()
			WIKI.put()

			self.redirect('/wiki')

class SwapHandler(yui.HtmlRequestHandler):
	def post(self,flag):
		if flag == 'new':
			content=self.request.get('content')
			SWAP=swap()
			SWAP.content=content
			SWAP.time=getCNnow()
			SWAP.put()
			self.redirect('/swap')
	def get(self,flag):	
		if flag == 'search':
			flag='swap'
			KeyWord=self.request.get('SwapSearch')
			SWAPS=swap.all().order("-time")
			LIS=[]
			for s in SWAPS:
				index=s.content.find(KeyWord)
				if index!=-1:
					LIS.append(s)
			TIME=getCNnow()
			page_current=int(self.request.get('p') or '1')
			pages=math.floor(len(LIS)/PAGE_SIZE)+1
			ps=[i for i in range(1,pages+1)]
			template_values = {
			'%s'%(flag.upper()+'S'):LIS,
			'pages': pages,
			'ps': ps,
			'page_current': page_current,
			"TIME":TIME,
			}
			path = os.path.join(os.path.dirname(__file__), 'tpl','%s.html'%flag)
			self.write(template.render(path, template_values))

class LiHandler(yui.HtmlRequestHandler):
	def post(self,flag):
		if flag == 'new':
			contents=self.request.get('content').strip().split('\n')
			for content in contents:
				LI=li()
				LI.content=content.strip()
				LI.time=getCNnow()
				LI.put()
			self.redirect('/li')


class sdfdfHandler(yui.HtmlRequestHandler):
	def get(self):
		WORDS=words.all()
		for  WORD in WORDS:
			WORD.EN=WORD.EN.strip().lower()
			WORD.put()
		self.redirect('/sfsdfsdfsdfsdfdsfsdf')
class TT(yui.HtmlRequestHandler):
	def get(self):
		import time,calendar,datetime
#		self.write(str(int(time.mktime(datetime.date.today().timetuple()))))
		self.write(str(int(time.time())))
class TIDY(yui.HtmlRequestHandler):
	def get(self):
		LIS=li.all()
		for LI in LIS:
			LI.put()
		LIS=words.all()
		for LI in LIS:
			LI.put()
		LIS=wiki.all()
		for LI in LIS:
			LI.put()
		LIS=swap.all()
		for LI in LIS:
			LI.put()

class NotFound(yui.HtmlRequestHandler):
	@yui.server_cache(60, False)
	def get(self):
	  template_values = {
      }
	  path = os.path.join(os.path.dirname(__file__), 'tpl','404.html')
	  self.write(template.render(path, template_values))
application = yui.WsgiApplication([
	# ('/', Hello),
	('/(words|wiki|swap|li|)', Mainpage),
	('/show/(words|wiki|swap|li)', ShowAll),
	('/showphone', ShowAllPhone),
	('/del', Admin),
	('/translate', TranslateHandler),
	('/translate/(.*)', TranslateHandler),
	('/r', RememberPage),
	('/r/(.*)', RememberPage),
	('/wiki/(.*)', WikiHandler),
	('/swap/(.*)', SwapHandler),
	('/li/(.*)', LiHandler),
	('/lskjlkfdkf', sdfdfHandler),
	('/__TT', TT),
	('/__TIDY', TIDY),
	('.*', NotFound) # not existing, expected to be 404 not found
])

def main():
	util.run_wsgi_app(application)

if __name__ == '__main__':
	main()
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.