Exemplo n.º 1
0
Arquivo: blob.py Projeto: dpq/spooce
 def __call__(self, env, start_response):
     Config = ConfigParser()
     Config.read(configfile)
     params = {"host": "", "user": "", "database": "", "port": ""}
     for param in params:
         if not Config.has_option("BlobStore", param):
             print "Malformed configuration file: mission option %s in section %s" % (param, "BlobStore")
             sys.exit(1)
         params[param] = Config.get("BlobStore", param)
     req = Request(env)
     resp = Response(status=200, content_type="text/plain")
     #engine = create_engine("mysql+mysqldb://%s:%s@%s:%s/%s?charset=utf8&use_unicode=0" %
     #    (params["user"], secret.BlobSecret, params["host"], params["port"], params["database"]), pool_recycle=3600)
     Base = declarative_base(bind=engine)
     local.Session = []
     local.FileEntry = []
     Session.append(sessionmaker(bind=engine))
     FileEntry.append(makeFileEntry(Base))
     if req.path.startswith('/fx'):
         if req.method == "GET":
             resp.status_code, filename, resp.content_type, resp.response = self.__download(req)
             if resp.content_type == "application/octet-stream":
                 resp.headers["Content-Disposition"] = "attachment; filename=%s" % filename
             return resp(env, start_response)
         elif req.method == "POST":
             resp.content_type="text/plain"
             resp.response = self.__upload(req)
             return resp(env, start_response)
     else:
         resp.status_code = 404
         resp.content_type="text/plain"
         resp.response = ""
         return resp(env, start_response)
Exemplo n.º 2
0
def serve_file(file, content_type=None):
    # Reset the stream
    file.seek(0)
    resp = Response(FileWrapper(file), direct_passthrough=True)

    if content_type is None:
        resp.content_type = file.content_type
    else:
        resp.content_type = content_type

    return resp
Exemplo n.º 3
0
Arquivo: warden.py Projeto: dpq/spooce
 def __call__(self, env, start_response):
     req = Request(env)
     Config = ConfigParser()
     Config.read(configfile)
     params = {"host": "", "user": "", "database": "", "port": ""}
     for param in params:
         if not Config.has_option("MySQL", param):
             print "Malformed configuration file: mission option %s in section MySQL" % (param)
             sys.exit(1)
         params[param] = Config.get("MySQL", param)    
     #engine = create_engine("mysql+mysqldb://%s:%s@%s:%s/%s?charset=utf8&use_unicode=0" %
     #    (params["user"], secret.MySQL, params["host"], params["port"], params["database"]), pool_recycle=3600)
     Base = declarative_base(bind=engine)
     local.Session = []
     local.User = []
     local.MethodEmail = []
     local.Session.append(sessionmaker(bind=engine))
     local.User.append(makeUser(Base))
     local.MethodEmail.append(makeMethodEmail(Base))
     resp = Response(status=200)
     if req.path == '/register':
         resp.content_type = "text/html"
         resp.response = self.__register(req)
         return resp(env, start_response)
     elif req.path == '/regemail1':
         resp.content_type = "text/html"
         resp.response = self.__addEmailAuth1(req)
         return resp(env, start_response)
     elif req.path == '/regemail2':
         resp.content_type = "text/html"
         resp.response = self.__addEmailAuth2(req)
         return resp(env, start_response)
     elif req.path == '/regemail3':
         resp.content_type = "text/html"
         resp.response = self.__addEmailAuth3(req)
         return resp(env, start_response)
     elif req.path == '/regemailkill':
         resp.content_type = "text/html"
         resp.response = self.__removeEmailAuth(req)
         return resp(env, start_response)
     elif req.path == '/regemaillist':
         resp.content_type = "text/plain"
         resp.response = self.__listEmailAuth(req)
         return resp(env, start_response)
     elif req.path == '/auth' and req.values.has_key("email") and req.values.has_key("password"):
         resp.content_type = "text/plain"
         resp.response = [self.__authenticateByEmail(req)]
         return resp(env, start_response)
     elif req.path == '/auth' and req.values.has_key("uid"):
         resp.content_type = "text/plain"
         uid = self.__uid(req)
         if uid == None:
             uid = ""
         resp.response = [uid]
         return resp(env, start_response)
     else:
         resp.status_code = 404
         resp.response = [""]
         return resp(env, start_response)
Exemplo n.º 4
0
    def __call__(self, environ, start_response):
        local.application = self
        request = MongoRequest(environ)
        local.url_adapter = adapter = url_map.bind_to_environ(environ)
        environ['mongo.db'] = self.db
        environ['mongo.fs'] = self.fs
        try:
            endpoint, values = adapter.match()
            handler = getattr(views, endpoint)
            data = handler(request, **values)

            # WSGI
            if callable(data):
                return data(environ, start_response)

            data = safe_keys(data)

            data['request'] = request

            # Templates
            template = self.env.get_template("%s.html" % endpoint)
            response = Response()
            response.content_type = "text/html"
            response.add_etag()
            # if DEBUG:
            #   response.make_conditional(request)
            data['endpoint'] = endpoint
            response.data = template.render(**data)
        except HTTPException, e:
            response = e
Exemplo n.º 5
0
def miku(request):
  data = request.files['image'].stream.read()
  img =  HomeImage.split(images.Image(data))[0]
  png = img.execute_transforms(output_encoding=images.PNG)
  r = Response()
  r.content_type = 'image/png'
  r.data = png
  return r
Exemplo n.º 6
0
def application(req):
    if req.method == 'POST':
        file_in = req.files['myfile']
        buf = convert_doc(file_in)

        filename = file_in.filename.replace('.odt', '-converted.odt')
        resp = Response(buf.getvalue())
        resp.content_type = 'application/x-download'
        resp.headers.add('Content-Disposition', 'attachment', filename=filename)
        return resp
    return Response(HTML, content_type='text/html')
Exemplo n.º 7
0
def serve_content(file_handle: TextIO, content_type):
    file_handle.seek(0)
    content = file_handle.read()

    resp = Response()
    resp.content_type = content_type
    resp.status_code = 200
    resp.data = content
    resp.freeze()

    return resp
Exemplo n.º 8
0
Arquivo: repo.py Projeto: dpq/spooce
 def __call__(self, env, start_response):
     req = Request(env)
     Config = ConfigParser()
     Config.read(configfile)
     params = {"host": "", "user": "", "database": "", "port": ""}
     for param in params:
         if not Config.has_option("MySQL", param):
             print "Malformed configuration file: mission option %s in section MySQL" % (param)
             sys.exit(1)
         params[param] = Config.get("MySQL", param)
     #print params
     #engine = create_engine("mysql+mysqldb://%s:%s@%s:%s/%s?charset=utf8&use_unicode=0" %
     #    (params["user"], secret.MySQL, params["host"], params["port"], params["database"]), pool_recycle=3600)
     Base = declarative_base(bind=engine)
     local.Session = []
     local.Package = []
     local.Session.append(sessionmaker(bind=engine))
     local.Package.append(makePackage(Base))
     resp = Response(status=200, content_type="text/plain")
     if req.path == '/pkg/upload':
         resp.content_type="text/html"
         resp.response = self.__upload(req)
         return resp(env, start_response)
     elif req.path == '/pkg/sdk':
         resp.content_disposition="application/force-download"
         resp.content_type="application/python"
         resp.headers.add("Content-Disposition", "attachment; filename=appcfg.py")
         f = open("appcfg.py").read().replace("__REPO_UPLOAD__", '"%s"' % (req.host_url + 'pkg/upload'))
         resp.headers.add("Content-Length", str(len(f)))
         resp.response = [f]
         return resp(env, start_response)
     elif req.path.startswith('/pkg'):
         resp.status_code, resp.content_encoding, resp.response = self.__download(req)
         return resp(env, start_response)
     else:
         resp.status_code = 404
         resp.response = [""]
         return resp(env, start_response)
Exemplo n.º 9
0
def application(req):
    if req.method == 'POST':
        file_in = req.files['myfile']
        buf = convert_doc(file_in)

        filename = file_in.filename.replace('.odt', '-converted.odt')
        filename = urllib.parse.quote(filename)
        resp = Response(buf.getvalue())
        resp.content_type = 'application/x-download'
        resp.headers.add('Content-Disposition',
                         'attachment',
                         filename=filename)
        return resp
    return Response(HTML, content_type='text/html')
Exemplo n.º 10
0
def random_bytes(request, n):
    """Returns n random bytes generated with given seed."""
    n = min(n, 100 * 1024)  # set 100KB limit

    params = CaseInsensitiveDict(request.args.items())
    if 'seed' in params:
        random.seed(int(params['seed']))

    response = Response()

    # Note: can't just use os.urandom here because it ignores the seed
    response.data = bytearray(random.randint(0, 255) for i in range(n))
    response.content_type = 'application/octet-stream'
    return response
Exemplo n.º 11
0
def serve_spec(
    site: str,
    target: EndpointTarget,
    url: str,
    content_type: str,
    serializer: Callable[[Dict[str, Any]], str],
) -> Response:
    data = generate_data(target=target)
    data.setdefault('servers', [])
    add_once(data['servers'], {'url': url, 'description': f"Site: {site}"})
    response = Response(status=200)
    response.data = serializer(data)
    response.content_type = content_type
    response.freeze()
    return response
Exemplo n.º 12
0
def serve_spec(
    site: str,
    url: str,
    content_type: str,
    serializer: Callable[[Dict[str, Any]], str],
) -> Response:
    data = generate_data()
    data.setdefault('servers', [])
    data['servers'].append({
        'url': url,
        'description': f"Site: {site}",
    })
    response = Response(status=200)
    response.data = serializer(data)
    response.content_type = content_type
    response.freeze()
    return response
Exemplo n.º 13
0
    def __call__(self, environ, start_response):
        path_info = environ['PATH_INFO']
        path = re.sub(self.prefix, '', path_info)
        prefix = path_info[:-len(path)]
        if prefix.endswith("/ui"):
            prefix = prefix[:-3]

        if path == "/":
            path = "/index.html"

        if path == "/index.html":
            with open(swagger_ui_3_path + path) as fh:
                content = fh.read()
            content = content.replace(
                "https://petstore.swagger.io/v2/swagger.json",
                prefix + "/openapi.yaml")
            resp = Response()
            resp.content_type = 'text/html'
            resp.status_code = 200
            resp.data = content
            resp.freeze()
            return resp(environ, start_response)

        return serve_file(swagger_ui_3_path + path)(environ, start_response)
Exemplo n.º 14
0
def serve_pil(image, extension):
    resp = Response()
    resp.content_type = mimetypes.guess_type(extension)
    image.save(resp.stream, extension)
    return resp