NovaBryan/EVE_Dump
Log | Files | 📦 下载最新源码 (.zip) | Refs | README

httpApps.py (8101B)


      1 #Embedded file name: C:\BuildAgent\work\20d73f1b24eed06e\eve\release\V24.01\carbon\common\script\net\httpApps.py
      2 import os
      3 import sys
      4 import logging
      5 import blue
      6 import cherrypy
      7 from carbon.common.script.net.httpAuth import Require
      8 from scriber import httputils
      9 from carbon.common.script.net import httpJinja
     10 log = logging.getLogger('scriber')
     11 
     12 def Host():
     13     host = cherrypy.request.headers.get('Host')
     14     if host:
     15         return host.split(':')
     16     else:
     17         return ('', '')
     18 
     19 
     20 def Convert(var):
     21     try:
     22         return int(var)
     23     except Exception:
     24         sys.exc_clear()
     25         try:
     26             return long(var)
     27         except Exception:
     28             sys.exc_clear()
     29             try:
     30                 return float(var)
     31             except Exception:
     32                 sys.exc_clear()
     33                 if var == 'None':
     34                     return None
     35                 else:
     36                     return var
     37 
     38 
     39 def Pythonize(var):
     40     if type(var) == type([]):
     41         ret = []
     42         for i in var:
     43             ret.append(Convert(i))
     44 
     45         return ret
     46     return Convert(var)
     47 
     48 
     49 class ServerPageHandler(object):
     50     __guid__ = 'httpApps.ServerPageHandler'
     51 
     52     def __init__(self):
     53         pass
     54 
     55     def Handle(self, *args, **kwargs):
     56         sess = None
     57         try:
     58             sess = cherrypy.session['machoSession']
     59             if not sess.userid:
     60                 self.EndWebSession()
     61         except:
     62             pass
     63 
     64         isSP, files = self.GetFiles(args)
     65         if not isSP:
     66             path, fo = files[-1]
     67             cherrypy.response.headers['Cache-Control'] = 'max-age=3600, public'
     68             log.info('path=%s' % path)
     69             log.info('httputils.get_mimetype(path)=%s' % httputils.get_mimetype(path))
     70             log.info('fo=%s' % fo)
     71             log.info('fo.size=%s' % fo.size)
     72             try:
     73                 cherrypy.response.headers['Content-Type'] = httputils.get_mimetype(path)
     74                 return cherrypy.lib.static._serve_fileobj(fo, httputils.get_mimetype(path), fo.size)
     75             except Exception as ex:
     76                 log.exception('Well SHIT!')
     77                 log.error('path=%s' % path)
     78                 log.error('httputils.get_mimetype(path)=%s' % httputils.get_mimetype(path))
     79                 log.error('fo=%s' % fo)
     80                 log.error('fo.size=%s' % fo.size)
     81 
     82         try:
     83             glob = self.ExecutePy(files)
     84         finally:
     85             for fn, fo in files:
     86                 fo.close()
     87 
     88         request, response = self.PrepareReqResp()
     89         action = request.params.get('action')
     90         if action and isinstance(action, list):
     91             request.params['action'] = action[0]
     92         try:
     93             masque = sess.Masquerade()
     94             request.session = sess
     95             try:
     96                 glob['Execute'](request, response, sess)
     97             finally:
     98                 masque.UnMask()
     99                 request.session = None
    100 
    101             if response.contentType is None:
    102                 if response.streamMode == 'b':
    103                     ct = 'application/octet-stream'
    104                 else:
    105                     ct = 'text/html;charset=utf-8'
    106             else:
    107                 ct = response.contentType
    108             data = response.buff.getvalue()
    109             if 'charset=utf-8' in ct.lower():
    110                 data = unicode(data).encode('utf-8')
    111             response.headers['Content-Type'] = ct
    112             return data
    113         finally:
    114             del request
    115             del response
    116 
    117     def GetFiles(self, args):
    118         files = []
    119         filepath, filename = os.path.split(os.path.join(*args))
    120         isSP = filename.lower().endswith('.py')
    121         for fn in (filename, 'app' + filename.capitalize()):
    122             bluepath = 'wwwroot:' + os.path.join(filepath, fn)
    123             fullPath = blue.paths.ResolvePath(bluepath)
    124             if os.path.exists(fullPath):
    125                 rf = blue.ResFile()
    126                 rf.OpenAlways(fullPath)
    127                 files.append((fullPath, rf))
    128             if files and not isSP:
    129                 break
    130 
    131         if not files:
    132             raise cherrypy.NotFound(bluepath)
    133         return (isSP, files)
    134 
    135     def ExecutePy(self, files):
    136         import __builtin__
    137         glob = {'__builtins__': __builtin__}
    138         for fn, fo in files:
    139             data = fo.read()
    140             code = compile(data, fn, 'exec', 0, True)
    141             try:
    142                 exec code in glob
    143             except Exception:
    144                 logging.exception('exec code in glob failed')
    145                 raise
    146 
    147         return glob
    148 
    149     def PrepareReqResp(self):
    150         request, response = cherrypy.request, cherrypy.response
    151         request.rawparams = dict(request.params)
    152         for k, v in request.params.iteritems():
    153             if type(v) is list:
    154                 v = [ Pythonize(e) for e in v ]
    155             else:
    156                 v = Pythonize(v)
    157             if type(v) is list and len(v) == 2:
    158                 if v[0] == v[1]:
    159                     v = v[0]
    160                 else:
    161                     try:
    162                         v.remove('ActionTakeFromQuery')
    163                         v = v[0]
    164                     except ValueError:
    165                         pass
    166 
    167             request.params[k] = v
    168 
    169         def QueryString(variable, caseInsensitive = False, raw = False):
    170             if variable == 'action':
    171                 action = request.params.get('action')
    172                 if action:
    173                     if isinstance(action, list):
    174                         return action[0]
    175                     else:
    176                         return action
    177             params = request.rawparams if raw else request.params
    178             if caseInsensitive:
    179                 variable = variable.lower()
    180                 for k, v in params.iteritems():
    181                     if k.lower() == variable:
    182                         return v
    183 
    184                 return None
    185             else:
    186                 return params.get(variable)
    187 
    188         request.QueryString = QueryString
    189 
    190         def QueryStrings(raw = False):
    191             if raw:
    192                 return request.rawparams
    193             return request.params
    194 
    195         request.QueryStrings = QueryStrings
    196         request.query = request.params
    197         request.Host = Host
    198         request.Form = QueryString
    199         request.FormItems = QueryStrings
    200         request.form = request.params
    201         request.path = request.path_info
    202 
    203         def FullPath():
    204             return request.path_info
    205 
    206         request.FullPath = FullPath
    207         request.args = request.query_string
    208         import StringIO
    209         response.streamMode = None
    210         response.buff = StringIO.StringIO()
    211 
    212         def Write(buff):
    213             response.buff.write(buff)
    214             response.buff.write('\r\n')
    215 
    216         response.Write = Write
    217 
    218         def WriteBinary(buff):
    219             import cStringIO
    220             response.buff = cStringIO.StringIO()
    221             response.streamMode = 'b'
    222             response.buff.write(buffer(buff))
    223 
    224         response.WriteBinary = WriteBinary
    225 
    226         def Redirect(url, args = None):
    227             if args:
    228                 url = url + '?'
    229                 for k, v in args.iteritems():
    230                     url = url + str(k) + '=' + str(v) + '&'
    231 
    232             to = url.encode('UTF-8')
    233             raise cherrypy.HTTPRedirect([to])
    234 
    235         response.Redirect = Redirect
    236         response.contentType = None
    237         return (request, response)
    238 
    239 
    240 class PolarisController(ServerPageHandler):
    241     __guid__ = 'httpApps.PolarisController'
    242 
    243     def __init__(self):
    244         pass
    245 
    246     @cherrypy.expose
    247     @Require()
    248     def default(self, *args, **kwargs):
    249         return self.Handle(*args, **kwargs)
    250 
    251 
    252 class NodeController(object):
    253     __guid__ = 'httpApps.NodeController'
    254 
    255     def __init__(self):
    256         pass
    257 
    258     @cherrypy.expose
    259     def default(self, *args, **kwargs):
    260         return 'NodeController: (args) %s and (kwargs) %s' % (args, kwargs)
    261 
    262 
    263 class MapController(object):
    264     __guid__ = 'httpApps.MapController'
    265 
    266     def __init__(self):
    267         pass
    268 
    269     @cherrypy.expose
    270     def default(self, *args, **kwargs):
    271         return 'MapController: (args) %s and (kwargs) %s' % (args, kwargs)