Ejemplo n.º 1
0
 def sendActivationEmail(self, user):
     msg = email.Message(
         "激活拍卖试验系统账户",
         recipients=[user['email']],
     )
     loader = tornado.template.Loader("/home/btaylor")
     msg.html = loader.load("email/signup.html").generate(user=user)
Ejemplo n.º 2
0
 def make_form_data(self):
     from io import StringIO
     import MimeWriter
     fp = StringIO.StringIO()
     mw = MimeWriter.MimeWriter(fp)
     mw.startmultipartbody("form-data")
     for i in self.inputs:
         if not i.name: continue
         v = i.get()
         if not v: continue
         if type(v) == type(()):
             # XXX Argh!  Have to do it twice, for each coordinate
             if None in v: continue
             disp = 'form-data; name="%s.x"' % i.name
             sw = mw.nextpart()
             sw.addheader("Content-Disposition", disp)
             body = sw.startbody("text/plain")
             body.write(str(v[0]))
             disp = 'form-data; name="%s.y"' % i.name
             sw = mw.nextpart()
             sw.addheader("Content-Disposition", disp)
             body = sw.startbody("text/plain")
             body.write(str(v[1]))
             continue
         disp = 'form-data; name="%s"' % i.name
         data = None
         if i.__class__.__name__ == 'InputFile':
             try:
                 f = open(v)
                 data = f.read()
                 f.close()
             except IOError as msg:
                 print("IOError:", msg)
             else:
                 disp = disp + '; filename="%s"' % v
         sw = mw.nextpart()
         sw.addheader("Content-Disposition", disp)
         if data is not None:
             sw.addheader("Content-Length", str(len(data)))
             body = sw.startbody("text/plain")
             body.write(data)
         else:
             body = sw.startbody("text/plain")
             body.write(v)
     mw.lastpart()
     fp.seek(0)
     import email
     headers = email.Message(fp)
     ctype = headers['content-type']
     ctype = str.join(str.split(ctype))  # Get rid of newlines
     data = fp.read()
     return ctype, data
Ejemplo n.º 3
0
 def start(self, tag, attrs, loc_start, loc_end):
     if not tag:
         return
     # print loc
     if tag == "meta":
         # look for encoding directives
         http_equiv = content = None
         for k, v in attrs:
             if k == "http-equiv":
                 http_equiv = v.lower()
             elif k == "content":
                 content = v
         if http_equiv == "content-type" and content:
             # use email to parse the http header
             header = email.Message(
                 io.StringIO("%s: %s\n\n" % (http_equiv, content)))
             encoding = header.getparam("charset")
             if encoding:
                 self.encoding = encoding
     l_tag = tag.lower()
     if self._elem:
         p_tag = self._elem[-1].tag.lower()
         # if the parent and child are the same tag, then close the
         # parent if it uses optional close tags
         if l_tag in html_optional_close_tags and p_tag == l_tag:
             self.end(tag)
         # special case table tags that should be autoclosed only when
         # hitting a new table row
         elif p_tag in ("td", "th") and l_tag == "tr":
             self.end_tag(p_tag)
         # if the parent and child are block tags, close the parent
         elif p_tag in html_cannot_contain_block_tags and l_tag in html_block_tags:
             self.end_tag(p_tag)
     attrib = {}
     for attr in attrs:
         attrib[attr[0]] = strip_quotes(attr[1])
     ElementTree.TreeBuilder.start(self, tag, attrib)
     el = self._elem[-1]
     self.current = el
     el.ns = None
     el.localName = el.tag
     el.start = loc_start
     el.end = None
     self.nodes.append(el)
     if len(self._elem) > 1:
         self.nodemap[el] = self._elem[-2]
     else:
         self.nodemap[el] = None
     if l_tag in html_no_close_tags:
         self.end_tag(tag, loc_end)
Ejemplo n.º 4
0
 def getreply(self, file):
     self.file = file
     line = self.file.readline()
     if self.debuglevel > 0: print('reply:', repr(line))
     if replyprog.match(line) < 0:
         # Not an HTTP/1.0 response.  Fall back to HTTP/0.9.
         # Push the data back into the file.
         self.file.seek(-len(line), 1)
         self.headers = {}
         app = grailutil.get_grailapp()
         c_type, c_encoding = app.guess_type(self.selector)
         if c_encoding:
             self.headers['content-encoding'] = c_encoding
         # HTTP/0.9 sends HTML by default
         self.headers['content-type'] = c_type or "text/html"
         return 200, "OK", self.headers
     errcode, errmsg = replyprog.group(1, 2)
     errcode = int(errcode)
     errmsg = str.strip(errmsg)
     self.headers = email.Message(self.file, 0)
     return errcode, errmsg, self.headers
Ejemplo n.º 5
0
    def resolve(self, uriRef, baseUri=None):
        """
        Takes a URI or a URI reference plus a base URI, produces a absolutized URI
        if a base URI was given, then attempts to obtain access to an entity
        representing the resource identified by the resulting URI,
        returning the entity as a stream (a file-like object).

        Raises a IriError if the URI scheme is unsupported or if a stream
        could not be obtained for any reason.
        """
        if not isinstance(uriRef, urllib.request.Request):
            if baseUri is not None:
                uri = self.absolutize(uriRef, baseUri)
                scheme = get_scheme(uri)
            else:
                uri = uriRef
                scheme = get_scheme(uriRef)
                # since we didn't use absolutize(), we need to verify here
                if scheme not in self._supported_schemes:
                    if scheme is None:
                        raise ValueError(
                            'When the URI to resolve is a relative '
                            'reference, it must be accompanied by a base URI.')
                    else:
                        raise IriError(IriError.UNSUPPORTED_SCHEME,
                                       scheme=scheme,
                                       resolver=self.__class__.__name__)
            req = urllib.request.Request(uri)
        else:
            req, uri = uriRef, uriRef.get_full_url()

        if self.authorizations and not self.authorize(uri):
            raise IriError(IriError.DENIED_BY_RULE, uri=uri)
        # Bypass urllib for opening local files.
        if scheme == 'file':
            path = uri_to_os_path(uri, attemptAbsolute=False)
            try:
                stream = open(path, 'rb')
            except IOError as e:
                raise IriError(IriError.RESOURCE_ERROR,
                               loc='%s (%s)' % (uri, path),
                               uri=uri,
                               msg=str(e))
            # Add the extra metadata that urllib normally provides (sans
            # the poorly guessed Content-Type header).
            stats = os.stat(path)
            size = stats.st_size
            mtime = _formatdate(stats.st_mtime)
            headers = email.Message(
                io.StringIO('Content-Length: %s\nLast-Modified: %s\n' %
                            (size, mtime)))
            stream = urllib.addinfourl(stream, headers, uri)
        else:
            # urllib.request.urlopen, wrapped by us, will suffice for http, ftp,
            # data and gopher
            try:
                stream = urllib.request.urlopen(req)
            except IOError as e:
                raise IriError(IriError.RESOURCE_ERROR,
                               uri=uri,
                               loc=uri,
                               msg=str(e))
        return stream