Handler.zip
#!/usr/bin/python
# coding:utf-8
from google.appengine.ext import webapp
from google.appengine.api import memcache
from db import Pagedb
from . import BaseHTML
from ..util import page
import zipfile
import datetime
import random
import py.util
import sys
import locale
 
class Zipreader(webapp.RequestHandler):
    def get(self):
        html = BaseHTML("zip.html")
        html.render(self)
    def post(self):
        try:
            if self.request.POST["zip"] :#檢查有沒有選擇檔案
                self.response.out.write("no zip input")
                return
        except:
            pass
        if not hasattr(self.request.POST["zip"], "file"):
            self.response.out.write("it's not a zip")
        else:
            try:
                inputzip = zipfile.ZipFile(self.request.POST["zip"].file, 'r')
            except:
                self.response.out.write("it's not a zip")
            else:
                if self.request.get('test'):
                    self.testprint(inputzip)
                else:
                    txtlist = []
                    for info in inputzip.infolist():
                        if info.filename.rfind('.txt') > 0:
                            txtlist.append(info)
                    html = BaseHTML('import.html')
                    html.content["txtlist"] =  [(info, inputzip.read(info.filename)) for info in txtlist]
                    html.content['memkey'] = self.request.POST["zip"].filename + str(random.randint(0,1000))
                    memcache.set(html.content['memkey'], html.content["txtlist"],3600)
                    html.render(self)
    def testprint(self, zip):
        self.response.out.write('<pre>')
        for info in zip.infolist():
 
            self.response.out.write( info.filename +'\n')
            self.response.out.write(  '\tComment:\t%s\n' % info.comment)
            self.response.out.write(  '\tModified:\t%s\n'% datetime.datetime(*info.date_time))
            self.response.out.write(  '\tSystem:\t\t%s(0 = Windows, 3 = Unix)\n' % info.create_system)
            self.response.out.write(  '\tZIP version:\t%s\n' % info.create_version)
            self.response.out.write(  '\tCompressed:\t%s bytes\n' % info.compress_size)
            self.response.out.write(  '\tUncompressed:\t%s bytes\n' % info.file_size)
            if info.filename.rfind('.txt') > 0:
                self.response.out.write('\tdata:\n%s\n' % str(zip.read(info.filename)))
            self.response.out.write('\n')
        self.response.out.write('</pre>')
 
class Importer(webapp.RequestHandler):
    def __init__(self):
        pass
        #-----------------if error,plz use this function---------------------
        #encoding = "ascii" 
        #if 0:
        #    loc = locale.getdefaultlocale() #取得本地端coding
        #    if loc[1]:
        #        encoding = loc[1]
        #if 1:
        #    encoding = "utf-8"
        #if encoding != "ascii":
        #    sys.setdefaultencoding(encoding)
        #---------------------------------------------------------------------
    def post(self):
        try:
            title_array = self.request.POST['title_converToArray'].split('|') #Edit:Title
            title_array.remove(title_array[-1])#remove none
            pagetitle_array = self.request.POST['str_converToArray'].split(' ') #Edit:pageTitle
            pagetitle_array.remove(pagetitle_array[-1])#remove none
            Dic_title_pagetitle = dict(zip(title_array,pagetitle_array))#{'key':value} : {'title_array':pagetitle_array}
            txtlist = memcache.get(self.request.POST['memkey'])
            if not py.util.checkHasInit():
                page.create_by_first_use()
            if txtlist:
                for key,value in Dic_title_pagetitle.items():
                    for txt,content in txtlist:
                        page.createPage({
                                        'pagetitle':self.getCorrectTitle(value), 
                                        'title':key,
                                        'content':content.decode('utf-8'),
                                        'tag': []
                                        })
                        txtlist.remove((txt,content))
                        break
                self.redirect('/mypage')#轉址
        except KeyError, e:
            self.response.out.write(str(e))
            self.response.set_status(404)
 
    def getCorrectTitle(self,arg):
    #input =>Original type : source/filename.txt
    #output =>filename
        start = arg.find("/")+1
        end = arg.find(".")
        if start and end:
            return arg[start:end]
        else:
            return arg