当前位置: 首页>>代码示例>>Python>>正文


Python http.HTTPResponse类代码示例

本文整理汇总了Python中wheezy.http.HTTPResponse的典型用法代码示例。如果您正苦于以下问题:Python HTTPResponse类的具体用法?Python HTTPResponse怎么用?Python HTTPResponse使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。


在下文中一共展示了HTTPResponse类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: upload

def upload(request):
    #print 'form:', request.form
    #print 'uploaded:', request.files

    response = HTTPResponse()
    # check data integrity:
    if request.files.get('data') and request.form.get('crc'):

        storage = request.files.get('data')[0] # raw object
        crc = request.form.get('crc')[0] # crc for compressed content

        if str(zlib.crc32(storage.value)) == crc: # check integrity
            # return file save result
            content = zlib.decompress(storage.value)
            # write to file here
            savefile = storage.filename if storage.filename else (datetime.now().strftime('%Y%m%d%H%M%S') + str(random.randint(0,100)) + '.html')
            fout = open(os.path.join(conf.get('upload_dir'), savefile), 'w')
            fout.write(content)
            fout.close()

            response.write(conf.get('upload_url_prefix') + savefile)
        else:
            return bad_request()
    else:
        # bad request
        return bad_request()
            
    return response
开发者ID:Joycc,项目名称:polascii,代码行数:28,代码来源:main.py

示例2: get

    def get(self):
        fortunes = db_session.query(Fortune).all()
        fortunes.append(Fortune(id=0, message="Additional fortune added at request time."))
        fortunes.sort(key=attrgetter("message"))
        template = template_engine.get_template("fortune.html")
        template_html = template.render({"fortunes": fortunes})		

        response = HTTPResponse()
        response.write(template_html)
        return response
开发者ID:0x000F,项目名称:FrameworkBenchmarks,代码行数:10,代码来源:app.py

示例3: get

    def get(self, skip_body=False):

        mime_type, encoding = mimetypes.guess_type(self.filepath)
        response = HTTPResponse(mime_type or 'plain/text', encoding)
        if not skip_body:
            response.headers.append(HTTP_HEADER_ACCEPT_RANGE_NONE)
            file = open(self.filepath, 'rb')
            try:
                response.write_bytes(file.read())
            finally:
                file.close()
        return response
开发者ID:farakavco,项目名称:kakapo,代码行数:12,代码来源:static.py

示例4: get

    def get(self):
        fortunes = db_session.query(Fortune).all()
        fortunes.append(Fortune(id=0, message="Additional fortune added at request time."))
        fortunes.sort(key=attrgetter("message"))
        engine = Engine(loader=FileLoader(["views"]), extensions=[CoreExtension()])
        template = engine.get_template("fortune.html")
        for f in fortunes:
            f.message = bleach.clean(f.message)
        template_html = template.render({"fortunes": fortunes})		

        response = HTTPResponse()
        response.write(template_html)
        return response
开发者ID:based2,项目名称:FrameworkBenchmarks,代码行数:13,代码来源:app.py

示例5: post

    def post(self):
        """
        Handle HTTP POST.
        """

        method = self.get_method()
        body = self.get_body()

        # TODO handle method exception.
        result = method(**body)
        payload = self.encoder.encode(result)

        response = HTTPResponse(content_type="application/json")
        response.status_code = 200
        response.write(payload)

        return response
开发者ID:iakinsey,项目名称:unshadow,代码行数:17,代码来源:metric.py

示例6: post

    def post(self):

        try:
            form = self.request.form
            code = form["code"][0]
        except:
            return bad_request_with_detail("No data posted, or data in incorrect format")

        params = {"grant_type": "authorization_code", "redirect_uri": config.SPOTIFY_CALLBACK_URL, "code": code}

        token_response = requests.post(config.SPOTIFY_TOKEN_ENDPOINT, data=params, headers=auth_header, verify=True)

        response = HTTPResponse()
        response.content_type = "application/json"
        response.status_code = token_response.status_code

        if token_response.status_code == 200:
            json_response = token_response.json()
            refresh_token = json_response["refresh_token"]
            encrypted_token = crypt.encrypt(refresh_token)
            json_response["refresh_token"] = encrypted_token
            response_body = json.dumps(json_response)
            response.write(response_body)
        else:
            response.write_bytes(token_response.content)

        return response
开发者ID:brki,项目名称:spotify-token-auth-wheezy-web,代码行数:27,代码来源:app.py

示例7: get

    def get(self):
        con = session()
        repo = Repository(con)

        CONTENT_TYPE_XML='text/xml'
        CONTENT_TYPE_XML_RSP=CONTENT_TYPE_XML+'; charset=utf-8'

        if DEBUG:
            base_url = 'http://192.168.72.100:8080'
        else:
            base_url = 'http://shoboi.net'

        feed = feedgenerator.Atom1Feed(
            title = 'しょぼいろだ。',
            link = 'http://shobi.net/',
            feed_url = 'http://shoboi.net/atom',
            description = u'エロも笑いも虹も惨事もしょぼいろだで共有してね',
            author_name=u'しょぼい。',
            language = u"ja",
            pubdate = datetime.utcnow()
        )

        upimages = repo.list_upimages()
        for idx, i in enumerate(upimages):
            feed.add_item(
                title = i.title or 'タイトルなし',
                link = '%s/detail/%s' % (base_url, i.id),
                description = """<![CDATA[
                    <a href="%s/detail/%s">
                      <img src="%s/img/%s">
                    </a>
                ]]>""" % (base_url, i.id, base_url, i.thumb),
                author_name = i.author or '名無し',
                pubdate = datetime.now()
            )
            if idx >= 4: # 5件まで
                break;

        response = HTTPResponse()
        content_type = ('Content-Type', CONTENT_TYPE_XML_RSP)
        response.headers[0] = content_type
        response.write(feed.writeString('utf-8'))
        response.cache_dependency = ('d_atom', )
        return response
开发者ID:mshibata,项目名称:imgbbs,代码行数:44,代码来源:views.py

示例8: process

    def process(self, url=None, method='GET', data=None, environ=None, secure=False,
                content_type='html', route_name=None, encoding='UTF-8'):
        content_type_to_http_protocol_content_types = {
            'html': 'text/html; charset={}'.format(encoding),
            'json': 'application/json; charset={}'.format(encoding)
        }
        original_content_type = content_type
        content_type = content_type_to_http_protocol_content_types[content_type]
        if route_name:
            url = router.path_for(route_name)
        if url is None:
            raise ValueError('Please provide correct url for request or proper route_name')
        data = data or {}
        method = method.upper()
        response = HTTPResponse()
        r = self._base_environ()
        r.update({
            'PATH_INFO': url,
            'REQUEST_METHOD': str(method),
            'SERVER_PORT': str('443') if secure else str('80'),
            'wsgi.url_scheme': str('https') if secure else str('http'),
        })
        if method in ('POST', 'PUT'):
            formatter = get_formatter_for(original_content_type)
            data = formatter.format(data).encode(encoding)
            r.update({
                'CONTENT_LENGTH': len(data),
                'CONTENT_TYPE': str(content_type),
                'wsgi.input': FakePayload(data),
            })
        elif method == 'GET':
            # WSGI requires latin-1 encoded strings.
            r['QUERY_STRING'] = bytes(parse.urlencode(data), 'iso-8859-1').decode()
        r.update(environ or {})

        def wsgi_response_handler(response, status_string, headers):
            response.content_type = [header[1] for header in headers if header[0].lower() == 'content-type'].pop()
            response.status_code = HTTP_STATUS_STRING_TO_CODE[status_string]
            response.headers = headers

        output = application(r, partial(wsgi_response_handler, response))
        response.buffer = output
        return response
开发者ID:sergeyglazyrindev,项目名称:ritcore,代码行数:43,代码来源:http.py

示例9: wrap_request

    def wrap_request(self, request, *args, **kwargs):
        '''
        Prepares data and pass control to `restea.Resource` object

        :returns: :class: `wheezy.http.HTTPResponse`
        '''
        data_format, kwargs = self._get_format_name(kwargs)
        formatter = formats.get_formatter(data_format)

        resource = self._resource_class(
            WheezyRequestWrapper(request), formatter
        )
        res, status_code, content_type = resource.dispatch(*args, **kwargs)

        response = HTTPResponse(
            content_type=content_type,
        )
        response.write(res)
        response.status_code = status_code
        return response
开发者ID:kkszysiu,项目名称:restea,代码行数:20,代码来源:wheezywebwrap.py

示例10: ping

def ping(request):
    response = HTTPResponse()
    response.write('Pong!')
    return response
开发者ID:Joycc,项目名称:polascii,代码行数:4,代码来源:main.py

示例11: get

 def get(self):
     response = HTTPResponse()
     response.headers = [(CONTENT_TYPE, CONTENT_TYPE_JSON)]
     response.write(response_db_write_queries())
     return response
开发者ID:CodeArtLibs,项目名称:codeart-benchmarks,代码行数:5,代码来源:_wheezy_web.py

示例12: welcome

def welcome(request):
    response = HTTPResponse()
    response.write('Server is up!')
    return response
开发者ID:huahaiy,项目名称:docker-kgraph,代码行数:4,代码来源:search.py

示例13: plaintext

def plaintext(request):
    response = HTTPResponse()
    response.headers = [("Content-Type", "text/plain; charset=UTF-8")]
    response.write("Hello, world!")
    return response
开发者ID:based2,项目名称:FrameworkBenchmarks,代码行数:5,代码来源:app.py

示例14: get

 def get(self):
     number = int(self.route_args["number"])
     response = HTTPResponse()
     response.write(str(fib(number)))
     return response
开发者ID:reu,项目名称:fibaas,代码行数:5,代码来源:fibaas.py

示例15: post

 def post(self):
     data = self.request.form
     insert(data)
     response = HTTPResponse()
     response.status_code = 201
     return response
开发者ID:prsolucoes,项目名称:benchmarks,代码行数:6,代码来源:main.py


注:本文中的wheezy.http.HTTPResponse类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。